threads
listlengths
1
2.99k
[ { "msg_contents": "Hi Hackers,\n\nI propose adding trackable information in postgres_fdw, in order to track remote query correctly.\n\n## Background and motivation\n\nCurrently postgres_fdw connects remote servers by using connect_pg_server(). However the function just calls PQconnectdbParams() with fallback_application_name = \"postgres_fdw.\"\nTherefore, if two or more servers connect to one data server and two queries arrive at the data server, the database administrator cannot determine which queries came from which server.\nThis problem prevents some workload analysis because it cannot track the flow of queries.\n\n## Implementation\n\nI just added local backend's pid to fallback_application_name. This is the key for seaching and matching two logs.\nIn order to use the feature and track remote transactions, user must add backend-pid and application_name to log_line_prefix, like\n\n```\nlog_line_prefix = '%m [%p] [%a] '\n```\n\nHere is the output example. Assume that remote server has a table \"foo,\" and local server imports the schema.\nWhen local server executes foregin scan, the following line was output in the local's logfile.\n\n```\n2021-07-29 03:18:50.630 UTC [21572] [psql] LOG: duration: 23.366 ms statement: select * from foo;\n```\n\nAnd in the remote's one, the following lines were appered.\n\n```\n2021-07-29 03:18:50.628 UTC [21573] [postgres_fdw for remote PID: 21572] LOG: duration: 0.615 ms parse <unnamed>: DECLARE c1 CURSOR FOR\n SELECT id FROM public.foo\n```\n\nTwo lines have same pid, so we can track the log and analyze workloads correctly.\nI will write docs later, but now I want you to review the motivation and implementation.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Thu, 29 Jul 2021 05:12:57 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "[postgres_fdw] add local pid to fallback_application_name" }, { "msg_contents": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com> writes:\n> I propose adding trackable information in postgres_fdw, in order to track remote query correctly.\n\nI don't think this is a great idea as-is. People who need to do this\nsort of thing will all have their own ideas of what they need to track\n--- most obviously, it might be appropriate to include the originating\nserver's name, else you don't know what machine the PID is for.\nSo I think most people with this sort of requirement will be overriding\nthe default application name anyway, so we might as well keep the\ndefault behavior simple.\n\nWhat would be better to think about is how to let users specify this\nkind of behavior for themselves. I think it's possible to set\napplication_name as part of a foreign server's connection options,\nbut at present the result would only be a constant string. Somebody\nwho wished the PID to be in there would like to have some sort of\nformatting escape, say \"%p\" for PID. Extrapolating wildly, maybe we\ncould make all the %-codes known to log_line_prefix available here.\n\nPerhaps this is overkill. But I think the patch you have here is\nnot going to make very many people happy: it'll either be detail\nthey don't want, or too little detail.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 29 Jul 2021 11:06:41 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [postgres_fdw] add local pid to fallback_application_name" }, { "msg_contents": "Dear Tom,\n\nThank you for replying!\n\n> I don't think this is a great idea as-is. People who need to do this\n> sort of thing will all have their own ideas of what they need to track\n> --- most obviously, it might be appropriate to include the originating\n> server's name, else you don't know what machine the PID is for.\n\nI thought this is not big problem because hostname (or IP address) can be\nadded to log_line_prefix. I added only local-pid because this is the only thing\nthat cannot be set in the parameter.\n\n> So I think most people with this sort of requirement will be overriding\n> the default application name anyway, so we might as well keep the\n> default behavior simple.\n\nYeah, this patch assumed that application_name will be not overridden.\nThere is an another approach that PID adds to application_name, but it might be stupid.\n\n> What would be better to think about is how to let users specify this\n> kind of behavior for themselves. I think it's possible to set\n> application_name as part of a foreign server's connection options,\n> but at present the result would only be a constant string. Somebody\n> who wished the PID to be in there would like to have some sort of\n> formatting escape, say \"%p\" for PID. Extrapolating wildly, maybe we\n> could make all the %-codes known to log_line_prefix available here.\n\nI think your argument is better than mine. I will try to implement this approach.\nIf anyone has another argument please tell me.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED\n\n\n\n", "msg_date": "Fri, 30 Jul 2021 03:16:20 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [postgres_fdw] add local pid to fallback_application_name" } ]
[ { "msg_contents": "Hello:\r\n\r\nThere is a small problem with the documentation for the previously added SQL function “bit_count”.\r\nIn the doc, (https://www.postgresql.org/docs/14/functions-binarystring.html)\r\n“bit_count('\\x1234567890'::bytea)” result is \"31\" , but the actual result is \"15\".\r\n\r\nSimilar problems have been fixed in test file (commit: ebedd0c78fc51c293abe56e99a18c67af14da0c9), but the doc has not been modified.\r\nRegards,\r\nWang", "msg_date": "Thu, 29 Jul 2021 09:23:46 +0000", "msg_from": "\"wangzk.fnstxz@fujitsu.com\" <wangzk.fnstxz@fujitsu.com>", "msg_from_op": true, "msg_subject": "Doc: Fixed the result of the bit_count example" }, { "msg_contents": "> On 29 Jul 2021, at 11:23, wangzk.fnstxz@fujitsu.com wrote:\n> \n> Hello:\n> \n> There is a small problem with the documentation for the previously added SQL function “bit_count”.\n> \n> In the doc, (https://www.postgresql.org/docs/14/functions-binarystring.html)\n> “bit_count('\\x1234567890'::bytea)” result is \"31\" , but the actual result is \"15\".\n> \n> Similar problems have been fixed in test file (commit: ebedd0c78fc51c293abe56e99a18c67af14da0c9), but the doc has not been modified.\n\nGood catch, with the default value of standard_conforming_strings the result is\nindeed 15 and should be updated to reflect that. I'll apply this shortly\nbackpatched to 14 where bit_count was introduced.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Thu, 29 Jul 2021 11:35:54 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Doc: Fixed the result of the bit_count example" }, { "msg_contents": "> On 29 Jul 2021, at 11:35, Daniel Gustafsson <daniel@yesql.se> wrote:\n\n> I'll apply this shortly backpatched to 14 where bit_count was introduced.\n\n\nAnd done, thanks!\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Thu, 29 Jul 2021 23:30:53 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Doc: Fixed the result of the bit_count example" } ]
[ { "msg_contents": "Hackers,\n\nWhile reviewing and benchmarking 91e9e89dc (Make nodeSort.c use Datum\nsorts for single column sorts), I noticed that we use a separate\nmemory context to store tuple data and we just reset when we're done\nif the sort fits in memory, or we dump the tuples to disk in the same\norder they're added and reset the context when it does not. There is\na little pfree() work going on via writetup_heap() which I think\npossibly could just be removed to get some additional gains.\n\nAnyway, this context that stores tuples uses the standard aset.c\nallocator which has the usual power of 2 wastage and additional\noverheads of freelists etc. I wondered how much faster it would go if\nI set it to use a generation context instead of an aset.c one.\n\nAfter running make installcheck to make the tenk1 table, running the\nattached tuplesortbench script, I get this:\n\nMaster:\nwork_mem = '4MB';\n Sort Method: external merge Disk: 2496kB\nwork_mem = '4GB';\n Sort Method: quicksort Memory: 5541kB\n\nPatched:\nwork_mem = '4MB';\n Sort Method: quicksort Memory: 3197kB\n\nSo it seems to save quite a bit of memory getting away from rounding\nup allocations to the next power of 2.\n\nPerformance-wise, there's some pretty good gains. (Results in TPS)\n\nwork_mem = '4GB';\nTest master gen sort compare\nTest1 317.2 665.6 210%\nTest2 228.6 388.9 170%\nTest3 207.4 330.7 159%\nTest4 185.5 279.4 151%\nTest5 292.2 563.9 193%\n\nIf I drop the work_mem down to standard the unpatched version does to\ndisk, but the patched version does not. The gains get a little\nbigger.\n\nwork_mem = '4MB';\nTest master gen sort compare\nTest1 177.5 658.2 371%\nTest2 149.7 385.2 257%\nTest3 137.5 330.0 240%\nTest4 129.0 275.1 213%\nTest5 161.7 546.4 338%\n\nThe patch is just a simple 1-liner at the moment. I likely do need to\nadjust what I'm passing as the blockSize to GenerationContextCreate().\n Maybe a better number would be something that's calculated from\nwork_mem, e.g Min(ALLOCSET_DEFAULT_MAXSIZE, ((Size) work_mem) * 64))\nso that we just allocate at most a 16th of work_mem per chunk, but not\nbigger than 8MB. I don't think changing this will affect the\nperformance of the above very much.\n\nDavid", "msg_date": "Fri, 30 Jul 2021 18:42:18 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Use generation context to speed up tuplesorts" }, { "msg_contents": "On Fri, Jul 30, 2021 at 2:42 AM David Rowley <dgrowleyml@gmail.com> wrote:\n> Master:\n> Sort Method: quicksort Memory: 5541kB\n> Patched:\n> Sort Method: quicksort Memory: 3197kB\n\nWhoa.\n\n> work_mem = '4GB';\n> Test master gen sort compare\n> Test1 317.2 665.6 210%\n> Test2 228.6 388.9 170%\n> Test3 207.4 330.7 159%\n> Test4 185.5 279.4 151%\n> Test5 292.2 563.9 193%\n\nVery impressive.\n\nAn early version of what eventually became DSA worked with\nbackend-local memory and I saw very substantial memory usage\nimprovements on large sorts, similar to what you show here. I am not\nsure I saw the same CPU improvements, and in any case I abandoned the\nidea of using that infrastructure to manage backend-local memory at\nsome point, since the whole thing had lots of problems that I didn't\nknow how to solve. What you've done here looks like a much more\npromising approach.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 30 Jul 2021 10:51:10 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Hi,\n\nOn 2021-07-30 18:42:18 +1200, David Rowley wrote:\n> While reviewing and benchmarking 91e9e89dc (Make nodeSort.c use Datum\n> sorts for single column sorts), I noticed that we use a separate\n> memory context to store tuple data and we just reset when we're done\n> if the sort fits in memory, or we dump the tuples to disk in the same\n> order they're added and reset the context when it does not. There is\n> a little pfree() work going on via writetup_heap() which I think\n> possibly could just be removed to get some additional gains.\n> \n> Anyway, this context that stores tuples uses the standard aset.c\n> allocator which has the usual power of 2 wastage and additional\n> overheads of freelists etc. I wondered how much faster it would go if\n> I set it to use a generation context instead of an aset.c one.\n> \n> After running make installcheck to make the tenk1 table, running the\n> attached tuplesortbench script, I get this:\n\n> So it seems to save quite a bit of memory getting away from rounding\n> up allocations to the next power of 2.\n> \n> Performance-wise, there's some pretty good gains. (Results in TPS)\n\nVery nice!\n\n\nI wonder if there's cases where generation.c would regress performance\nover aset.c due to not having an initial / \"keeper\" block?\n\n\n> The patch is just a simple 1-liner at the moment. I likely do need to\n> adjust what I'm passing as the blockSize to GenerationContextCreate().\n> Maybe a better number would be something that's calculated from\n> work_mem, e.g Min(ALLOCSET_DEFAULT_MAXSIZE, ((Size) work_mem) * 64))\n> so that we just allocate at most a 16th of work_mem per chunk, but not\n> bigger than 8MB. I don't think changing this will affect the\n> performance of the above very much.\n\nI think it's bad that both genereration and slab don't have internal\nhandling of block sizes. Needing to err on the size of too big blocks to\nhandle large amounts of memory well, just so the contexts don't need to\ndeal with variably sized blocks isn't a sensible tradeoff.\n\nI don't think it's acceptable to use ALLOCSET_DEFAULT_MAXSIZE or\nMin(ALLOCSET_DEFAULT_MAXSIZE, ((Size) work_mem) * 64) for\ntuplesort.c. There's plenty cases where we'll just sort a handful of\ntuples, and increasing the memory usage of those by a factor of 1024\nisn't good. The Min() won't do any good if a larger work_mem is used.\n\nNor will it be good to use thousands of small allocations for a large\nin-memory tuplesort just because we're concerned about the initial\nallocation size. Both because of the allocation overhead, but\nimportantly also because that will make context resets more expensive.\n\nTo me this says that we should transplant aset.c's block size growing\ninto generation.c.\n\n\nThere is at least one path using tuplecontext that reaches code that\ncould end up freeing memory to a significant enough degree to care about\ngeneration.c effectively not using that memory:\ntuplesort_putdatum()->datumCopy()->EOH_flatten_into()\nOn a quick look I didn't find any expanded record user that frees\nnontrivial amounts of memory, but I didn't look all that carefully.\n\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 30 Jul 2021 13:38:53 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On 7/30/21 10:38 PM, Andres Freund wrote:\n> Hi,\n> \n> On 2021-07-30 18:42:18 +1200, David Rowley wrote:\n>> While reviewing and benchmarking 91e9e89dc (Make nodeSort.c use Datum\n>> sorts for single column sorts), I noticed that we use a separate\n>> memory context to store tuple data and we just reset when we're done\n>> if the sort fits in memory, or we dump the tuples to disk in the same\n>> order they're added and reset the context when it does not. There is\n>> a little pfree() work going on via writetup_heap() which I think\n>> possibly could just be removed to get some additional gains.\n>>\n>> Anyway, this context that stores tuples uses the standard aset.c\n>> allocator which has the usual power of 2 wastage and additional\n>> overheads of freelists etc. I wondered how much faster it would go if\n>> I set it to use a generation context instead of an aset.c one.\n>>\n>> After running make installcheck to make the tenk1 table, running the\n>> attached tuplesortbench script, I get this:\n> \n>> So it seems to save quite a bit of memory getting away from rounding\n>> up allocations to the next power of 2.\n>>\n>> Performance-wise, there's some pretty good gains. (Results in TPS)\n> \n> Very nice!\n> \n\nYes, very nice. I wouldn't have expected such significant difference, \nparticularly in CPU usage. It's pretty interesting that it both reduces \nmemory and CPU usage, I'd have guessed it's either one of the other.\n\n> \n> I wonder if there's cases where generation.c would regress performance\n> over aset.c due to not having an initial / \"keeper\" block?\n> \n\nNot sure. I guess such workload would need to allocate and free a single \nblock (so very little memory) very often. I guess that's possible, but \nI'm not aware of a place doing that very often. Although, maybe decoding \ncould do that for simple (serial) workload.\n\nI'm not opposed to adding a keeper block to Generation, similarly to \nwhat was discussed for Slab not too long ago.\n\n> \n>> The patch is just a simple 1-liner at the moment. I likely do need to\n>> adjust what I'm passing as the blockSize to GenerationContextCreate().\n>> Maybe a better number would be something that's calculated from\n>> work_mem, e.g Min(ALLOCSET_DEFAULT_MAXSIZE, ((Size) work_mem) * 64))\n>> so that we just allocate at most a 16th of work_mem per chunk, but not\n>> bigger than 8MB. I don't think changing this will affect the\n>> performance of the above very much.\n> \n> I think it's bad that both genereration and slab don't have internal\n> handling of block sizes. Needing to err on the size of too big blocks to\n> handle large amounts of memory well, just so the contexts don't need to\n> deal with variably sized blocks isn't a sensible tradeoff.\n> \n\nWell, back then it seemed like a sensible trade off to me, but I agree \nit may have negative consequences. I'm not opposed to revisiting this.\n\n> I don't think it's acceptable to use ALLOCSET_DEFAULT_MAXSIZE or\n> Min(ALLOCSET_DEFAULT_MAXSIZE, ((Size) work_mem) * 64) for\n> tuplesort.c. There's plenty cases where we'll just sort a handful of\n> tuples, and increasing the memory usage of those by a factor of 1024\n> isn't good. The Min() won't do any good if a larger work_mem is used.\n> \n> Nor will it be good to use thousands of small allocations for a large\n> in-memory tuplesort just because we're concerned about the initial\n> allocation size. Both because of the allocation overhead, but\n> importantly also because that will make context resets more expensive.\n> \n\nTrue.\n\n> To me this says that we should transplant aset.c's block size growing\n> into generation.c.\n> \n\nYeah, maybe.\n\n> \n> There is at least one path using tuplecontext that reaches code that\n> could end up freeing memory to a significant enough degree to care about\n> generation.c effectively not using that memory:\n> tuplesort_putdatum()->datumCopy()->EOH_flatten_into()\n> On a quick look I didn't find any expanded record user that frees\n> nontrivial amounts of memory, but I didn't look all that carefully.\n> \n\nNot sure, I'm not familiar with EOH_flatten_into or expanded records. \nBut I wonder if there's some sort of metric that we could track in \nGeneration and use it to identify \"interesting\" places.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Fri, 30 Jul 2021 23:13:26 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Hi,\n\nI spent a bit of time hacking on the Generation context, adding the two \nimprovements discussed in this thread:\n\n1) internal handling of block sizes, similar to what AllocSet does (it \npretty much just copies parts of it)\n\n2) keeper block (we keep one empry block instead of freeing it)\n\n3) I've also added allocChunkLimit, which makes it look a bit more like \nAllocSet (instead of using just blockSize/8, which does not work too \nwell with dynamic blockSize)\n\nI haven't done any extensive tests on it, but it does pass check-world \nwith asserts etc. I haven't touched the comments, those need updating.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Sat, 31 Jul 2021 04:34:04 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Sat, 31 Jul 2021 at 14:34, Tomas Vondra\n<tomas.vondra@enterprisedb.com> wrote:\n> I spent a bit of time hacking on the Generation context, adding the two\n> improvements discussed in this thread:\n>\n> 1) internal handling of block sizes, similar to what AllocSet does (it\n> pretty much just copies parts of it)\n>\n> 2) keeper block (we keep one empry block instead of freeing it)\n>\n> 3) I've also added allocChunkLimit, which makes it look a bit more like\n> AllocSet (instead of using just blockSize/8, which does not work too\n> well with dynamic blockSize)\n>\n> I haven't done any extensive tests on it, but it does pass check-world\n> with asserts etc. I haven't touched the comments, those need updating.\n> regards\n\nThanks for starting work on that. I've only had a quick look, but I\ncan have a more detailed look once you've got it more complete.\n\nFor now it does not really look like the keeper block stuff is wired\nup the same way as in aset.c. I'd expect you to be allocating that in\nthe same malloc as you're using to allocate the context struct itself\nin GenerationContextCreate().\n\nAlso, likely as a result of the above, minContextSize does not seem to\nbe wired up to anything apart from an Assert().\n\nDavid\n\n\n", "msg_date": "Mon, 2 Aug 2021 23:17:48 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Sat, 31 Jul 2021 at 08:38, Andres Freund <andres@anarazel.de> wrote:\n> There is at least one path using tuplecontext that reaches code that\n> could end up freeing memory to a significant enough degree to care about\n> generation.c effectively not using that memory:\n> tuplesort_putdatum()->datumCopy()->EOH_flatten_into()\n> On a quick look I didn't find any expanded record user that frees\n> nontrivial amounts of memory, but I didn't look all that carefully.\n\nI guess we could just use a normal context for datum sorts if we\nthought that might be a problem.\n\nI'm not too familiar with the expanded object code, but I'm struggling\nto imagine why anything would need to do a pfree in there. We just do\nEOH_get_flat_size() to determine how big to make the allocation then\nallocate some memory for EOH_flatten_into() to use to expand the\nobject into.\n\nDavid\n\n\n", "msg_date": "Tue, 3 Aug 2021 10:59:25 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On 8/2/21 1:17 PM, David Rowley wrote:\n> On Sat, 31 Jul 2021 at 14:34, Tomas Vondra\n> <tomas.vondra@enterprisedb.com> wrote:\n>> I spent a bit of time hacking on the Generation context, adding the two\n>> improvements discussed in this thread:\n>>\n>> 1) internal handling of block sizes, similar to what AllocSet does (it\n>> pretty much just copies parts of it)\n>>\n>> 2) keeper block (we keep one empry block instead of freeing it)\n>>\n>> 3) I've also added allocChunkLimit, which makes it look a bit more like\n>> AllocSet (instead of using just blockSize/8, which does not work too\n>> well with dynamic blockSize)\n>>\n>> I haven't done any extensive tests on it, but it does pass check-world\n>> with asserts etc. I haven't touched the comments, those need updating.\n>> regards\n> \n> Thanks for starting work on that. I've only had a quick look, but I\n> can have a more detailed look once you've got it more complete.\n> \n\nA review would be nice, although it can wait - It'd be interesting to \nknow if those patches help with the workload(s) you've been looking at.\n\n> For now it does not really look like the keeper block stuff is wired\n> up the same way as in aset.c. I'd expect you to be allocating that in\n> the same malloc as you're using to allocate the context struct itself\n> in GenerationContextCreate().\n> \n\nYes, that difference is natural. The AllocSet works a bit differently, \nas it does not release the blocks (except during reset), while the \nGeneration context frees the blocks. So it seems pointless to use the \nsame \"keeper\" block as AllocSet - instead my intention was to keep one \n\"allocated\" block as a cache, which should help with tight pfree/palloc \ncycles. Maybe we should not call that \"keeper\" block?\n\n\n> Also, likely as a result of the above, minContextSize does not seem to\n> be wired up to anything apart from an Assert().\n> \n\nHmm, yeah. This is probably due to copying some of the block-growth and \nkeeper block code from AllocSet. There should be just init/max block \nsize, I think.\n\nI did run the same set of benchmarks as for Slab, measuring some usual \nallocation patterns. The results for i5-2500k machine are attached (for \nthe xeon it's almost exactly the same behavior). While running those \ntests I realized the last patch is wrong and sets allocChunkLimit=1, \nwhich is bogus and causes significant regression. So here's an updated \nversion of the patch series too.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Tue, 3 Aug 2021 16:10:23 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Hi,\n\nOn 2021-08-03 10:59:25 +1200, David Rowley wrote:\n> On Sat, 31 Jul 2021 at 08:38, Andres Freund <andres@anarazel.de> wrote:\n> > There is at least one path using tuplecontext that reaches code that\n> > could end up freeing memory to a significant enough degree to care about\n> > generation.c effectively not using that memory:\n> > tuplesort_putdatum()->datumCopy()->EOH_flatten_into()\n> > On a quick look I didn't find any expanded record user that frees\n> > nontrivial amounts of memory, but I didn't look all that carefully.\n> \n> I guess we could just use a normal context for datum sorts if we\n> thought that might be a problem.\n\nI think that's probably a cure worse than the disease. I suspect datum sorts\ncan benefit from the higher density quite a bit...\n\n\n> I'm not too familiar with the expanded object code, but I'm struggling\n> to imagine why anything would need to do a pfree in there. We just do\n> EOH_get_flat_size() to determine how big to make the allocation then\n> allocate some memory for EOH_flatten_into() to use to expand the\n> object into.\n\nI can see some scenarios with a bit more creative uses of expanded\nobjects. We've e.g. been talking about using EA to avoid repeated and partial\ndetoasting overhead and you might need to do some more toast fetches when\nflattening. Toast fetches always allocate, and if the fetch were only for\nlater parts of the tuple, the fetched data would need to be freed.\n\nIt's probably fine to deal with this at later time, and just leave a comment\nsomewhere.\n\nIt could be addressed by having a bump style allocator combined with having\nfreelists. It's not like the tuplesort.c case is actually interested in the\ngenerational behaviour of generation.c (which makes freelists uninteresting),\nit's just that generation.c is the densest allocator that we have right now...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 3 Aug 2021 18:00:23 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Wed, 4 Aug 2021 at 02:10, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\n> A review would be nice, although it can wait - It'd be interesting to\n> know if those patches help with the workload(s) you've been looking at.\n\nI tried out the v2 set of patches using the attached scripts. The\nattached spreadsheet includes the original tests and compares master\nwith the patch which uses the generation context vs that patch plus\nyour v2 patch.\n\nI've also included 4 additional tests, each of which starts with a 1\ncolumn table and then adds another 32 columns testing the performance\nafter adding each additional column. I did this because I wanted to\nsee if the performance was more similar to master when the allocations\nhad less power of 2 wastage from allocset. If, for example, you look\nat row 123 of the spreadsheet you can see both patched and unpatched\nthe allocations were 272 bytes each yet there was still a 50%\nperformance improvement with just the generation context patch when\ncompared to master.\n\nLooking at the spreadsheet, you'll also notice that in the 2 column\ntest of each of the 4 new tests the number of bytes used for each\nallocation is larger with the generation context. 56 vs 48. This is\ndue to the GenerationChunk struct size being later than the Allocset's\nversion by 8 bytes. This is because it also holds the\nGenerationBlock. So with the patch there are some cases where we'll\nuse slightly more memory.\n\nAdditional tests:\n\n1. Sort 10000 tuples on a column with values 0-99 in memory.\n2. As #1 but with 1 million tuples.\n3 As #1 but with a large OFFSET to remove the overhead of sending to the client.\n4. As #2 but with a large OFFSET.\n\nTest #3 above is the most similar one to the original tests and shows\nsimilar gains. When the sort becomes larger (1 million tuple test),\nthe gains reduce. This indicates the gains are coming from improved\nCPU cache efficiency from the removal of the power of 2 wastage in\nmemory allocations.\n\nAll of the tests show that the patches to improve the allocation\nefficiency of generation.c don't help to improve the results of the\ntest cases. I wondered if it's maybe worth trying to see what happens\nif instead of doubling the allocations each time, quadruple them\ninstead. I didn't try this.\n\nDavid", "msg_date": "Sat, 7 Aug 2021 01:07:27 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On 8/6/21 3:07 PM, David Rowley wrote:\n> On Wed, 4 Aug 2021 at 02:10, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\n>> A review would be nice, although it can wait - It'd be interesting to\n>> know if those patches help with the workload(s) you've been looking at.\n> \n> I tried out the v2 set of patches using the attached scripts. The\n> attached spreadsheet includes the original tests and compares master\n> with the patch which uses the generation context vs that patch plus\n> your v2 patch.\n> \n> I've also included 4 additional tests, each of which starts with a 1\n> column table and then adds another 32 columns testing the performance\n> after adding each additional column. I did this because I wanted to\n> see if the performance was more similar to master when the allocations\n> had less power of 2 wastage from allocset. If, for example, you look\n> at row 123 of the spreadsheet you can see both patched and unpatched\n> the allocations were 272 bytes each yet there was still a 50%\n> performance improvement with just the generation context patch when\n> compared to master.\n> \n> Looking at the spreadsheet, you'll also notice that in the 2 column\n> test of each of the 4 new tests the number of bytes used for each\n> allocation is larger with the generation context. 56 vs 48. This is\n> due to the GenerationChunk struct size being later than the Allocset's\n> version by 8 bytes. This is because it also holds the\n> GenerationBlock. So with the patch there are some cases where we'll\n> use slightly more memory.\n> \n> Additional tests:\n> \n> 1. Sort 10000 tuples on a column with values 0-99 in memory.\n> 2. As #1 but with 1 million tuples.\n> 3 As #1 but with a large OFFSET to remove the overhead of sending to the client.\n> 4. As #2 but with a large OFFSET.\n> \n> Test #3 above is the most similar one to the original tests and shows\n> similar gains. When the sort becomes larger (1 million tuple test),\n> the gains reduce. This indicates the gains are coming from improved\n> CPU cache efficiency from the removal of the power of 2 wastage in\n> memory allocations.\n> \n> All of the tests show that the patches to improve the allocation\n> efficiency of generation.c don't help to improve the results of the\n> test cases. I wondered if it's maybe worth trying to see what happens\n> if instead of doubling the allocations each time, quadruple them\n> instead. I didn't try this.\n> \n\nThanks for the scripts and the spreadsheet with results.\n\nI doubt quadrupling the allocations won't help very much, but I suspect \nthe problem might be in the 0004 patch - at least that's what shows \nregression in my results. Could you try with just 0001-0003 applied?\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Sat, 7 Aug 2021 02:10:35 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Sat, 7 Aug 2021 at 12:10, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\n>\n> On 8/6/21 3:07 PM, David Rowley wrote:\n> > All of the tests show that the patches to improve the allocation\n> > efficiency of generation.c don't help to improve the results of the\n> > test cases. I wondered if it's maybe worth trying to see what happens\n> > if instead of doubling the allocations each time, quadruple them\n> > instead. I didn't try this.\n> >\n>\n> I doubt quadrupling the allocations won't help very much, but I suspect\n> the problem might be in the 0004 patch - at least that's what shows\n> regression in my results. Could you try with just 0001-0003 applied?\n\nBut 0004 only changes the logic which controls the threshold of when\nwe allocate an oversized chunk. It looks like the threshold is 512KB\nwith the 0004 patch. My test is only doing a maximum allocation of\n296 bytes so will never allocate an oversized chunk.\n\nCan you explain why you think 0004 would cause performance regressions?\n\nDavid\n\n\n", "msg_date": "Sun, 8 Aug 2021 19:02:50 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Sat, 7 Aug 2021 at 12:10, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\n> > All of the tests show that the patches to improve the allocation\n> > efficiency of generation.c don't help to improve the results of the\n> > test cases. I wondered if it's maybe worth trying to see what happens\n> > if instead of doubling the allocations each time, quadruple them\n> > instead. I didn't try this.\n> >\n>\n> I doubt quadrupling the allocations won't help very much, but I suspect\n> the problem might be in the 0004 patch - at least that's what shows\n> regression in my results. Could you try with just 0001-0003 applied?\n\nI tried the quadrupling of the buffer instead of doubling it each time\nand got the attached. Column E, or green in the graphs show the\nresults of that. It's now much closer to the original patch which just\nmade the block size 8MB.\n\nDavid", "msg_date": "Sun, 8 Aug 2021 22:11:12 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "\n\nOn 8/8/21 9:02 AM, David Rowley wrote:\n> On Sat, 7 Aug 2021 at 12:10, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\n>>\n>> On 8/6/21 3:07 PM, David Rowley wrote:\n>>> All of the tests show that the patches to improve the allocation\n>>> efficiency of generation.c don't help to improve the results of the\n>>> test cases. I wondered if it's maybe worth trying to see what happens\n>>> if instead of doubling the allocations each time, quadruple them\n>>> instead. I didn't try this.\n>>>\n>>\n>> I doubt quadrupling the allocations won't help very much, but I suspect\n>> the problem might be in the 0004 patch - at least that's what shows\n>> regression in my results. Could you try with just 0001-0003 applied?\n> \n> But 0004 only changes the logic which controls the threshold of when\n> we allocate an oversized chunk. It looks like the threshold is 512KB\n> with the 0004 patch. My test is only doing a maximum allocation of\n> 296 bytes so will never allocate an oversized chunk.\n> \n> Can you explain why you think 0004 would cause performance regressions?\n> \n\nIt's based solely on results of my benchmarks, where this patch seems to \ncause performance regression. I agree it's a bit bizzare, considering \nwhat the patch does.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Sun, 8 Aug 2021 14:28:10 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On 8/8/21 12:11 PM, David Rowley wrote:\n> On Sat, 7 Aug 2021 at 12:10, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\n>>> All of the tests show that the patches to improve the allocation\n>>> efficiency of generation.c don't help to improve the results of the\n>>> test cases. I wondered if it's maybe worth trying to see what happens\n>>> if instead of doubling the allocations each time, quadruple them\n>>> instead. I didn't try this.\n>>>\n>>\n>> I doubt quadrupling the allocations won't help very much, but I suspect\n>> the problem might be in the 0004 patch - at least that's what shows\n>> regression in my results. Could you try with just 0001-0003 applied?\n> \n> I tried the quadrupling of the buffer instead of doubling it each time\n> and got the attached. Column E, or green in the graphs show the\n> results of that. It's now much closer to the original patch which just\n> made the block size 8MB.\n> \n\nInteresting, I wouldn't have expected that to make such difference.\n\nI'm not sure quadrupling the size is a good idea, though, because it \nincreases the amount of memory we might be wasting. With the doubling, \nthe amount of wasted /unused memory is limited to ~50%, because the next \nblock is (roughly) equal to sum of already allocated blocks, so \nallocating just 1B on it leaves us with 50%. But quadrupling the size \nmeans we'll end up with ~75% free space. Of course, this is capped by \nthe maximum block size etc. but still ...\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Sun, 8 Aug 2021 14:38:00 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Wed, 4 Aug 2021 at 02:10, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\n> I did run the same set of benchmarks as for Slab, measuring some usual\n> allocation patterns. The results for i5-2500k machine are attached (for\n> the xeon it's almost exactly the same behavior). While running those\n> tests I realized the last patch is wrong and sets allocChunkLimit=1,\n> which is bogus and causes significant regression. So here's an updated\n> version of the patch series too.\n\nI know you're not done with these yet, but FWIW, I was getting an\nAssert failure with these patches on:\n\nAssert(total_allocated == context->mem_allocated);\n\nIt seems to be because you've forgotten to ignore keeper blocks when\nadjusting context->mem_allocated in GenerationReset()\n\nDavid\n\n\n", "msg_date": "Mon, 9 Aug 2021 00:38:27 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Mon, 9 Aug 2021 at 00:38, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\n> I'm not sure quadrupling the size is a good idea, though, because it\n> increases the amount of memory we might be wasting. With the doubling,\n> the amount of wasted /unused memory is limited to ~50%, because the next\n> block is (roughly) equal to sum of already allocated blocks, so\n> allocating just 1B on it leaves us with 50%. But quadrupling the size\n> means we'll end up with ~75% free space. Of course, this is capped by\n> the maximum block size etc. but still ...\n\nYeah, not sure what is best. It does however seem likely that the\nmajority of the performance improvement that I saw is due to either\nmalloc()/free() calls or just having fewer blocks in the context.\n\nMaybe it's worth getting the planner on board with deciding how to do\nthe allocations. It feels a bit overcautious to go allocating blocks\nin each power of two starting at 8192 bytes when doing a 1GB sort.\nMaybe we should be looking towards doing something more like making\nthe init allocation size more like pg_prevpower2_64(Min(work_mem *\n1024L, sort_tuples * tuple_width)), or maybe half or quarter that.\n\nIt would certainly not be the only executor node to allocate memory\nbased on what the planner thought. Just look at ExecHashTableCreate().\n\nDavid\n\n\n", "msg_date": "Mon, 9 Aug 2021 00:51:21 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Hi,\n\nI've spent quite a bit of time investigating the regressions clearly \nvisible in the benchmark results for some allocation/free patterns. \nAttached is a subset of results from a recent run, but the old results \nshow mostly the same thing.\n\nSome allocation patterns (e.g. fifo-cycle of lifo-cycle) are perfectly \nfine - the patches are a clear improvement. For for example results for \nfifo-decrease pattern look like this (showing just timings of palloc):\n\n block chunk 0001 0002 0003 0004\n ----------------------------------------------------\n 32768 512 38497 37234 39817 226451\n\n0001 just adds an extension used for the benchmarking, so it's pretty \nmuch \"master\" without any behavior changes. 0002 and 0003 make some \nchanges that seem to have no impact on this workload, but 0004 makes it \nabout 5x slower. Which is bizarre, because 0004 just tweaks how we \ncalculate the threshold for oversized chunks.\n\nBut that shouldn't have any impact, because with the benchmark \nparameters the threshold should be 64kB, way more than the chunk size \n(which is what we allocate).\n\nSimilarly, it should not matter whether we double or quadruple the block \nsize, because we reach the maximum block size (1MB) very fast in both \ncases, and then just just 1MB blocks for 99% of the benchmark.\n\nI was thinking that maybe the extra allocChunkLimit increases the size \nof the GenerationContext struct, requiring another cacheline. But no, \nit's 3 cachelines in both cases.\n\nBut while trying to investigate / profile this, I noticed a rather \nbizarre behavior, which I can't explain but I suspect it may be related \nto the slowdown.\n\nThe benchmark queries are executing generation_bench_fifo() for a range \nof block size / chunk_size combinations, and look about like this:\n\n select block_size, chunk_size, x.*\n from generate_series(32,512,32) a(chunk_size),\n (values (1024), (2048), (4096), (8192), (16384), (32768))\n AS b(block_size),\n lateral generation_bench_fifo(1000000, block_size, chunk_size,\n 2*chunk_size, 100, 10000, 5000) x;\n\nWhich takes a while to run, and then produces something like this:\n\n block_size | chunk_size | mem_allocated | alloc_ms | free_ms\n ------------+------------+---------------+----------+---------\n 1024 | 32 | 81528832 | 62016 | 24601\n 1024 | 64 | 137449472 | 61951 | 36034\n 1024 | 96 | 208408464 | 85437 | 57984\n ...\n 32768 | 448 | 707756032 | 36605 | 67648\n 32768 | 480 | 757104640 | 36838 | 71967\n 32768 | 512 | 806256640 | 37073 | 76489\n (96 rows)\n\n\nNow, I can run benchmark for a single case (e.g. the last one in the \nresults above), say like this:\n\n select block_size, chunk_size, x.* from\n (values (512)) AS a(chunk_size),\n (values (32768)) AS b(block_size),\n lateral generation_bench_fifo(1000000, block_size, chunk_size,\n 2*chunk_size, 100, 10000, 5000) x;\n\n\nAnd now comes the funny part - if I run it in the same backend as the \n\"full\" benchmark, I get roughly the same results:\n\n block_size | chunk_size | mem_allocated | alloc_ms | free_ms\n ------------+------------+---------------+----------+---------\n 32768 | 512 | 806256640 | 37159 | 76669\n\nbut if I reconnect and run it in the new backend, I get this:\n\n block_size | chunk_size | mem_allocated | alloc_ms | free_ms\n ------------+------------+---------------+----------+---------\n 32768 | 512 | 806158336 | 233909 | 100785\n (1 row)\n\nIt does not matter if I wait a bit before running the query, if I run it \nrepeatedly, etc. The machine is not doing anything else, the CPU is set \nto use \"performance\" governor, etc.\n\nThis is really strange, and the really suspicious thing is that this \nslower timing is very close to the 0004 timing (which is 226451). So \nperhaps the reason for these slowdowns is the same, it's just that with \n0004 it happens all the time.\n\nAccording to perf profiling, it seems there's one pretty significant \nchange - 0004 spends quite a bit of time in asm_exc_page_fault\n\n 41.17% 5.26% postgres postgres [.] GenerationAlloc\n |\n --36.06%--GenerationAlloc\n |\n |--28.95%--asm_exc_page_fault\n | |\n | --23.17%--exc_page_fault\n | |\n\nwhile on 0003 there's not a single frame with asm_exc_page_fault. I have \nno idea why, though.\n\nI wonder if this might be some unexpected / unfortunate interaction with \nkernel memory management, or something like that. Any ideas what might \nbe the root cause, what to look for, etc.?\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Thu, 9 Sep 2021 15:37:59 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Le jeudi 9 septembre 2021, 15:37:59 CET Tomas Vondra a écrit :\n> And now comes the funny part - if I run it in the same backend as the\n> \"full\" benchmark, I get roughly the same results:\n> \n> block_size | chunk_size | mem_allocated | alloc_ms | free_ms\n> ------------+------------+---------------+----------+---------\n> 32768 | 512 | 806256640 | 37159 | 76669\n> \n> but if I reconnect and run it in the new backend, I get this:\n> \n> block_size | chunk_size | mem_allocated | alloc_ms | free_ms\n> ------------+------------+---------------+----------+---------\n> 32768 | 512 | 806158336 | 233909 | 100785\n> (1 row)\n> \n> It does not matter if I wait a bit before running the query, if I run it\n> repeatedly, etc. The machine is not doing anything else, the CPU is set\n> to use \"performance\" governor, etc.\n\nI've reproduced the behaviour you mention.\nI also noticed asm_exc_page_fault showing up in the perf report in that case.\n\nRunning an strace on it shows that in one case, we have a lot of brk calls, \nwhile when we run in the same process as the previous tests, we don't.\n\nMy suspicion is that the previous workload makes glibc malloc change it's \ntrim_threshold and possibly other dynamic options, which leads to constantly \nmoving the brk pointer in one case and not the other.\n\nRunning your fifo test with absurd malloc options shows that indeed that might \nbe the case (I needed to change several, because changing one disable the \ndynamic adjustment for every single one of them, and malloc would fall back to \nusing mmap and freeing it on each iteration):\n\nmallopt(M_TOP_PAD, 1024 * 1024 * 1024);\nmallopt(M_TRIM_THRESHOLD, 256 * 1024 * 1024);\nmallopt(M_MMAP_THRESHOLD, 4*1024*1024*sizeof(long));\n\nI get the following results for your self contained test. I ran the query \ntwice, in each case, seeing the importance of the first allocation and the \nsubsequent ones:\n\nWith default malloc options:\n\n block_size | chunk_size | mem_allocated | alloc_ms | free_ms \n------------+------------+---------------+----------+---------\n 32768 | 512 | 795836416 | 300156 | 207557\n\n block_size | chunk_size | mem_allocated | alloc_ms | free_ms \n------------+------------+---------------+----------+---------\n 32768 | 512 | 795836416 | 211942 | 77207\n\n\nWith the oversized values above:\n\n block_size | chunk_size | mem_allocated | alloc_ms | free_ms \n------------+------------+---------------+----------+---------\n 32768 | 512 | 795836416 | 219000 | 36223\n\n\n block_size | chunk_size | mem_allocated | alloc_ms | free_ms \n------------+------------+---------------+----------+---------\n 32768 | 512 | 795836416 | 75761 | 78082\n(1 row)\n\nI can't tell how representative your benchmark extension would be of real life \nallocation / free patterns, but there is probably something we can improve \nhere.\n\nI'll try to see if I can understand more precisely what is happening.\n\n-- \nRonan Dunklau\n\n\n\n\n", "msg_date": "Wed, 08 Dec 2021 16:51:17 +0100", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On 12/8/21 16:51, Ronan Dunklau wrote:\n> Le jeudi 9 septembre 2021, 15:37:59 CET Tomas Vondra a écrit :\n>> And now comes the funny part - if I run it in the same backend as the\n>> \"full\" benchmark, I get roughly the same results:\n>>\n>> block_size | chunk_size | mem_allocated | alloc_ms | free_ms\n>> ------------+------------+---------------+----------+---------\n>> 32768 | 512 | 806256640 | 37159 | 76669\n>>\n>> but if I reconnect and run it in the new backend, I get this:\n>>\n>> block_size | chunk_size | mem_allocated | alloc_ms | free_ms\n>> ------------+------------+---------------+----------+---------\n>> 32768 | 512 | 806158336 | 233909 | 100785\n>> (1 row)\n>>\n>> It does not matter if I wait a bit before running the query, if I run it\n>> repeatedly, etc. The machine is not doing anything else, the CPU is set\n>> to use \"performance\" governor, etc.\n> \n> I've reproduced the behaviour you mention.\n> I also noticed asm_exc_page_fault showing up in the perf report in that case.\n> \n> Running an strace on it shows that in one case, we have a lot of brk calls, \n> while when we run in the same process as the previous tests, we don't.\n> \n> My suspicion is that the previous workload makes glibc malloc change it's \n> trim_threshold and possibly other dynamic options, which leads to constantly \n> moving the brk pointer in one case and not the other.\n> \n> Running your fifo test with absurd malloc options shows that indeed that might \n> be the case (I needed to change several, because changing one disable the \n> dynamic adjustment for every single one of them, and malloc would fall back to \n> using mmap and freeing it on each iteration):\n> \n> mallopt(M_TOP_PAD, 1024 * 1024 * 1024);\n> mallopt(M_TRIM_THRESHOLD, 256 * 1024 * 1024);\n> mallopt(M_MMAP_THRESHOLD, 4*1024*1024*sizeof(long));\n> \n> I get the following results for your self contained test. I ran the query \n> twice, in each case, seeing the importance of the first allocation and the \n> subsequent ones:\n> \n> With default malloc options:\n> \n> block_size | chunk_size | mem_allocated | alloc_ms | free_ms \n> ------------+------------+---------------+----------+---------\n> 32768 | 512 | 795836416 | 300156 | 207557\n> \n> block_size | chunk_size | mem_allocated | alloc_ms | free_ms \n> ------------+------------+---------------+----------+---------\n> 32768 | 512 | 795836416 | 211942 | 77207\n> \n> \n> With the oversized values above:\n> \n> block_size | chunk_size | mem_allocated | alloc_ms | free_ms \n> ------------+------------+---------------+----------+---------\n> 32768 | 512 | 795836416 | 219000 | 36223\n> \n> \n> block_size | chunk_size | mem_allocated | alloc_ms | free_ms \n> ------------+------------+---------------+----------+---------\n> 32768 | 512 | 795836416 | 75761 | 78082\n> (1 row)\n> \n> I can't tell how representative your benchmark extension would be of real life \n> allocation / free patterns, but there is probably something we can improve \n> here.\n> \n\nThanks for looking at this. I think those allocation / free patterns are\nfairly extreme, and there probably are no workloads doing exactly this.\nThe idea is the actual workloads are likely some combination of these\nextreme cases.\n\n> I'll try to see if I can understand more precisely what is happening.\n> \n\nThanks, that'd be helpful. Maybe we can learn something about tuning\nmalloc parameters to get significantly better performance.\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Wed, 8 Dec 2021 22:07:12 +0100", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Le mercredi 8 décembre 2021, 22:07:12 CET Tomas Vondra a écrit :\n> On 12/8/21 16:51, Ronan Dunklau wrote:\n> > Le jeudi 9 septembre 2021, 15:37:59 CET Tomas Vondra a écrit :\n> >> And now comes the funny part - if I run it in the same backend as the\n> >> \n> >> \"full\" benchmark, I get roughly the same results:\n> >> block_size | chunk_size | mem_allocated | alloc_ms | free_ms\n> >> \n> >> ------------+------------+---------------+----------+---------\n> >> \n> >> 32768 | 512 | 806256640 | 37159 | 76669\n> >> \n> >> but if I reconnect and run it in the new backend, I get this:\n> >> block_size | chunk_size | mem_allocated | alloc_ms | free_ms\n> >> \n> >> ------------+------------+---------------+----------+---------\n> >> \n> >> 32768 | 512 | 806158336 | 233909 | 100785\n> >> \n> >> (1 row)\n> >> \n> >> It does not matter if I wait a bit before running the query, if I run it\n> >> repeatedly, etc. The machine is not doing anything else, the CPU is set\n> >> to use \"performance\" governor, etc.\n> > \n> > I've reproduced the behaviour you mention.\n> > I also noticed asm_exc_page_fault showing up in the perf report in that\n> > case.\n> > \n> > Running an strace on it shows that in one case, we have a lot of brk\n> > calls,\n> > while when we run in the same process as the previous tests, we don't.\n> > \n> > My suspicion is that the previous workload makes glibc malloc change it's\n> > trim_threshold and possibly other dynamic options, which leads to\n> > constantly moving the brk pointer in one case and not the other.\n> > \n> > Running your fifo test with absurd malloc options shows that indeed that\n> > might be the case (I needed to change several, because changing one\n> > disable the dynamic adjustment for every single one of them, and malloc\n> > would fall back to using mmap and freeing it on each iteration):\n> > \n> > mallopt(M_TOP_PAD, 1024 * 1024 * 1024);\n> > mallopt(M_TRIM_THRESHOLD, 256 * 1024 * 1024);\n> > mallopt(M_MMAP_THRESHOLD, 4*1024*1024*sizeof(long));\n> > \n> > I get the following results for your self contained test. I ran the query\n> > twice, in each case, seeing the importance of the first allocation and the\n> > subsequent ones:\n> > \n> > With default malloc options:\n> > block_size | chunk_size | mem_allocated | alloc_ms | free_ms\n> > \n> > ------------+------------+---------------+----------+---------\n> > \n> > 32768 | 512 | 795836416 | 300156 | 207557\n> > \n> > block_size | chunk_size | mem_allocated | alloc_ms | free_ms\n> > \n> > ------------+------------+---------------+----------+---------\n> > \n> > 32768 | 512 | 795836416 | 211942 | 77207\n> > \n> > With the oversized values above:\n> > block_size | chunk_size | mem_allocated | alloc_ms | free_ms\n> > \n> > ------------+------------+---------------+----------+---------\n> > \n> > 32768 | 512 | 795836416 | 219000 | 36223\n> > \n> > block_size | chunk_size | mem_allocated | alloc_ms | free_ms\n> > \n> > ------------+------------+---------------+----------+---------\n> > \n> > 32768 | 512 | 795836416 | 75761 | 78082\n> > \n> > (1 row)\n> > \n> > I can't tell how representative your benchmark extension would be of real\n> > life allocation / free patterns, but there is probably something we can\n> > improve here.\n> \n> Thanks for looking at this. I think those allocation / free patterns are\n> fairly extreme, and there probably are no workloads doing exactly this.\n> The idea is the actual workloads are likely some combination of these\n> extreme cases.\n> \n> > I'll try to see if I can understand more precisely what is happening.\n> \n> Thanks, that'd be helpful. Maybe we can learn something about tuning\n> malloc parameters to get significantly better performance.\n> \n\nApologies for the long email, maybe what I will state here is obvious for \nothers but I learnt a lot, so... \n\nI think I understood what the problem was in your generation tests: depending \non the sequence of allocations we will raise a different maximum for \nmmap_threshold and trim_threshold. When an mmap block is freed, malloc will \nraise it's threshold as it consider memory freed to be better served by \nregular moving of the sbrk pointer, instead of using mmap to map memory. This \nthreshold is upped by multiplying it by two anytime we free a mmap'ed block.\n\nAt the same time, the trim_threshold is raised to double the mmap_threshold, \nconsidering that this amount of memory should not be released to the OS \nbecause we have a good chance of reusing it. \n\nThis can be demonstrated using the attached systemtap script, along with a \npatch adding new traces to generation_context for this purpose:\nWhen running your query:\n\nselect block_size, chunk_size, x.* from\n (values (512)) AS a(chunk_size),\n (values (32768)) AS b(block_size),\n lateral generation_bench_fifo(1000000, block_size, chunk_size,\n 2*chunk_size, 100, 10000, 5000) x;\n\nWe obtain the following trace for thresholds adjustments:\n\n2167837: New thresholds: mmap: 135168 bytes, trim: 270336 bytes\n2167837: New thresholds: mmap: 266240 bytes, trim: 532480 bytes\n2167837: New thresholds: mmap: 528384 bytes, trim: 1056768 bytes\n2167837: New thresholds: mmap: 1052672 bytes, trim: 2105344 bytes\n2167837: New thresholds: mmap: 16003072 bytes, trim: 32006144 bytes\n\nWhen running the full benchmark, we reach a higher threshold at some point:\n\n2181301: New thresholds: mmap: 135168 bytes, trim: 270336 bytes\n2181301: New thresholds: mmap: 266240 bytes, trim: 532480 bytes\n2181301: New thresholds: mmap: 528384 bytes, trim: 1056768 bytes\n2181301: New thresholds: mmap: 1052672 bytes, trim: 2105344 bytes\n2181301: New thresholds: mmap: 16003072 bytes, trim: 32006144 bytes\n2181301: New thresholds: mmap: 24002560 bytes, trim: 48005120 bytes\n\nThis is because at some point in the full benchmark, we allocate a block \nbigger than mmap threshold, which malloc serves by an mmap, then frees it \nwhich means we now also raise the trim_threshold. The subsequent allocations \nin the lone query end up between those thresholds, so are served by moving the \nsbrk pointer, then releasing the memory back to the OS, which turns out to be \nexpensive too. \n\nOne thing that I observed is that that effect of constantly moving the sbrk \npointer still happens, but not as much in a real tuplesort workload. I haven't \ntested the reordering buffer for now, which is the other part of the code using \ngeneration context.\n\nSo, I decided to benchmark trying to control the malloc thresholds. This \nresult is on my local laptop, with an I7 processor, for the benchmark \ninitially proposed by David, with 4GB work_mem and default settings.\n\nI benchmarked master, the original patch with fixed block size, and the one \nadjusting the size.\n\nFor each of them, I ran them using default malloc options (ie, adjusting the \nthresholds dynamically), and with setting MMAP_MMAP_THRESHOLD to 32MB (the \nmaximum on my platform, 4 * 1024 * 1024 * sizeof(long)) and the corresponding \nMMAP_TRIM_THRESHOLD if malloc would have adjusted it by itself reaching this \nvalue (ie, 64MB). I did that by setting the corresponding env variables. \n\nThe results is in the attached spreadsheet.\n\nI will follow up with a benchmark of the test sorting a table with a width \nvarying from 1 to 32 columns.\n\nAs of now, my conclusion is that for glibc malloc, the block size we use \ndoesn't really matter, as long as we tell malloc to not release a certain \namount of memory back to the system once it's been allocated. Setting the \nmmap_threshold to min(work_mem, DEFAULT_MMAP_THRESHOLD_MAX) and trim_threshold \nto two times that would IMO take us to where a long-lived backend would likely \nend anyway: as soon as we alloc min(work_mem, 32MB), we won't give it back to \nthe system, and save us a huge amount a syscalls in common cases. Doing that \nwill not change the allocation profiles for other platforms, and should be safe \nfor those.\n\nThe only problem I see if we were to do that would be for allocations in \nexcess of work_mem, which would no longer trigger a threshold raise since once \nwe're in \"non-dynamic\" mode, glibc's malloc would keep our manually-set \nvalues. I guess this proposal could be refined to set it up dynamically \nourselves when pfreeing blocks, just like malloc does.\n\nWhat do you think of this analysis and idea ?\n\n\n-- \nRonan Dunklau", "msg_date": "Thu, 16 Dec 2021 11:56:15 +0100", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Le jeudi 16 décembre 2021, 11:56:15 CET Ronan Dunklau a écrit :\n> I will follow up with a benchmark of the test sorting a table with a width\n> varying from 1 to 32 columns.\n> \n\nSo please find attached another benchmark for that case.\n\nThe 3 different patchsets tested are:\n\n - master\n - fixed (David's original patch)\n - adjust (Thomas growing blocks patch)\n\nSo it looks like tuning malloc for this would be very benificial for any kind \nof allocation, and by doing so we reduce the problems seen with the growing \nblocks patch to next to nothing, while keeping the ability to not allocate too \nmuch memory from the get go.\n\nI would like to try to implement some dynamic glibc malloc tuning, if that is \nsomething we don't reject on principle from the get go. \n\n\n-- \nRonan Dunklau", "msg_date": "Thu, 16 Dec 2021 17:03:39 +0100", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On 12/16/21 17:03, Ronan Dunklau wrote:\n> Le jeudi 16 décembre 2021, 11:56:15 CET Ronan Dunklau a écrit :\n>> I will follow up with a benchmark of the test sorting a table with a width\n>> varying from 1 to 32 columns.\n>>\n> \n> So please find attached another benchmark for that case.\n> \n> The 3 different patchsets tested are:\n> \n> - master\n> - fixed (David's original patch)\n> - adjust (Thomas growing blocks patch)\n> \n\nPresumably Thomas is me, right?\n\n> So it looks like tuning malloc for this would be very benificial for any kind\n> of allocation, and by doing so we reduce the problems seen with the growing\n> blocks patch to next to nothing, while keeping the ability to not allocate too\n> much memory from the get go.\n> \n\nThanks for running those tests and investigating the glibc behavior! I \nfind those results very interesting. My conclusions from this is that \nthe interaction interaction between \"our\" allocator and the allocator in \nmalloc (e.g. glibc) can be problematic. Which makes benchmarking and \noptimization somewhat tricky because code changes may trigger behavior \nchange in glibc (or whatever allocator backs malloc).\n\nI think it's worth exploring if we can tune this in a reasonable way, \nbut I have a couple concerns related to that:\n\n1) I wonder how glibc-specific this is - I'd bet it applies to other \nallocators (either on another OS or just different allocator on Linux) \ntoo. Tweaking glibc parameters won't affect those systems, of course, \nbut maybe we should allow tweaking those systems too ...\n\n2) In fact, I wonder if different glibc versions behave differently? \nHopefully it's not changing that much, though. Ditto kernel versions, \nbut the mmap/sbrk interface is likely more stable. We can test this.\n\n3) If we bump the thresholds, won't that work against reusing the \nmemory? I mean, if we free a whole block (from any allocator we have), \nglibc might return it to kernel, depending on mmap threshold value. It's \nnot guaranteed, but increasing the malloc thresholds will make that even \nless likely. So we might just as well increase the minimum block size, \nwith about the same effect, no?\n\n\n> I would like to try to implement some dynamic glibc malloc tuning, if that is\n> something we don't reject on principle from the get go.\n> \n\n+1 to that\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 16 Dec 2021 18:00:56 +0100", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Le jeudi 16 décembre 2021, 18:00:56 CET Tomas Vondra a écrit :\n> On 12/16/21 17:03, Ronan Dunklau wrote:\n> > Le jeudi 16 décembre 2021, 11:56:15 CET Ronan Dunklau a écrit :\n> >> I will follow up with a benchmark of the test sorting a table with a\n> >> width\n> >> varying from 1 to 32 columns.\n> > \n> > So please find attached another benchmark for that case.\n> > \n> > The 3 different patchsets tested are:\n> > - master\n> > - fixed (David's original patch)\n> > - adjust (Thomas growing blocks patch)\n> \n> Presumably Thomas is me, right?\n\nI'm really sorry for this typo... Please accept my apologies. \n\n> \n> > So it looks like tuning malloc for this would be very benificial for any\n> > kind of allocation, and by doing so we reduce the problems seen with the\n> > growing blocks patch to next to nothing, while keeping the ability to not\n> > allocate too much memory from the get go.\n> \n> Thanks for running those tests and investigating the glibc behavior! I\n> find those results very interesting. My conclusions from this is that\n> the interaction interaction between \"our\" allocator and the allocator in\n> malloc (e.g. glibc) can be problematic. Which makes benchmarking and\n> optimization somewhat tricky because code changes may trigger behavior\n> change in glibc (or whatever allocator backs malloc).\n> \n> I think it's worth exploring if we can tune this in a reasonable way,\n> but I have a couple concerns related to that:\n> \n> 1) I wonder how glibc-specific this is - I'd bet it applies to other\n> allocators (either on another OS or just different allocator on Linux)\n> too. Tweaking glibc parameters won't affect those systems, of course,\n> but maybe we should allow tweaking those systems too ...\n\nI agree, finding their specific problems and see if we can workaround it would \nbe interesting. I suppose glibc's malloc is the most commonly used allocator \nin production, as it is the default for most Linux distributions.\n\n> \n> 2) In fact, I wonder if different glibc versions behave differently?\n> Hopefully it's not changing that much, though. Ditto kernel versions,\n> but the mmap/sbrk interface is likely more stable. We can test this.\n\nThat could be tested, yes. As a matter of fact, a commit removing the upper \nlimit for MALLOC_MMAP_THRESHOLD has just been committed yesterday to glibc, \nwhich means we can service much bigger allocation without mmap.\n\n\n> \n> 3) If we bump the thresholds, won't that work against reusing the\n> memory? I mean, if we free a whole block (from any allocator we have),\n> glibc might return it to kernel, depending on mmap threshold value. It's\n> not guaranteed, but increasing the malloc thresholds will make that even\n> less likely. So we might just as well increase the minimum block size,\n> with about the same effect, no?\n\nIt is my understanding that malloc will try to compact memory by moving it \naround. So the memory should be actually be released to the kernel at some \npoint. In the meantime, malloc can reuse it for our next invocation (which can \nbe in a different memory context on our side). \n\nIf we increase the minimum block size, this is memory we will actually \nreserve, and it will not protect us against the ramping-up behaviour:\n - the first allocation of a big block may be over mmap_threshold, and serviced \nby an expensive mmap\n - when it's free, the threshold is doubled\n - next invocation is serviced by an sbrk call\n - freeing it will be above the trim threshold, and it will be returned.\n\nAfter several \"big\" allocations, the thresholds will raise to their maximum \nvalues (well, it used to, I need to check what happens with that latest patch \nof glibc...)\n \nThis will typically happen several times as malloc doubles the threshold each \ntime. This is probably the reason quadrupling the block sizes was more \neffective. \n\n\n> \n> > I would like to try to implement some dynamic glibc malloc tuning, if that\n> > is something we don't reject on principle from the get go.\n> \n> +1 to that\n\nOk, I'll work on a patch for this and submit a new thread. \n\n\n-- \nRonan Dunklau\n\n\n\n\n", "msg_date": "Fri, 17 Dec 2021 09:08:06 +0100", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Le vendredi 17 décembre 2021, 09:08:06 CET Ronan Dunklau a écrit :\n> It is my understanding that malloc will try to compact memory by moving it\n> around. So the memory should be actually be released to the kernel at some\n> point. In the meantime, malloc can reuse it for our next invocation (which\n> can be in a different memory context on our side).\n\nI've been told off-list this comment wasn't clear: I meant that it compacts \n*free* memory, consolidating into larger blocks that will eventually reach the \nthreshold, and be released.\n\n-- \nRonan Dunklau\n\n\n\n\n", "msg_date": "Fri, 17 Dec 2021 11:20:11 +0100", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On 12/17/21 09:08, Ronan Dunklau wrote:\n> Le jeudi 16 décembre 2021, 18:00:56 CET Tomas Vondra a écrit :\n>> On 12/16/21 17:03, Ronan Dunklau wrote:\n>>> Le jeudi 16 décembre 2021, 11:56:15 CET Ronan Dunklau a écrit :\n>>>> I will follow up with a benchmark of the test sorting a table with a\n>>>> width\n>>>> varying from 1 to 32 columns.\n>>>\n>>> So please find attached another benchmark for that case.\n>>>\n>>> The 3 different patchsets tested are:\n>>> - master\n>>> - fixed (David's original patch)\n>>> - adjust (Thomas growing blocks patch)\n>>\n>> Presumably Thomas is me, right?\n> \n> I'm really sorry for this typo... Please accept my apologies. \n> \n\nNah, no apology needed. I was just wondering if I missed some patch from\nThomas Munro ...\n\n>>\n>>> So it looks like tuning malloc for this would be very benificial for any\n>>> kind of allocation, and by doing so we reduce the problems seen with the\n>>> growing blocks patch to next to nothing, while keeping the ability to not\n>>> allocate too much memory from the get go.\n>>\n>> Thanks for running those tests and investigating the glibc behavior! I\n>> find those results very interesting. My conclusions from this is that\n>> the interaction interaction between \"our\" allocator and the allocator in\n>> malloc (e.g. glibc) can be problematic. Which makes benchmarking and\n>> optimization somewhat tricky because code changes may trigger behavior\n>> change in glibc (or whatever allocator backs malloc).\n>>\n>> I think it's worth exploring if we can tune this in a reasonable way,\n>> but I have a couple concerns related to that:\n>>\n>> 1) I wonder how glibc-specific this is - I'd bet it applies to other\n>> allocators (either on another OS or just different allocator on Linux)\n>> too. Tweaking glibc parameters won't affect those systems, of course,\n>> but maybe we should allow tweaking those systems too ...\n> \n> I agree, finding their specific problems and see if we can workaround it would \n> be interesting. I suppose glibc's malloc is the most commonly used allocator \n> in production, as it is the default for most Linux distributions.\n> \n\nI wasn't really suggesting to investigate those other allocators in this\npatch - it seems like a task requiring a pretty significant amount of\nwork/time. My point was that we should make it reasonably easy to add\ntweaks for those other environments, if someone is interested enough to\ndo the legwork.\n\n>>\n>> 2) In fact, I wonder if different glibc versions behave differently?\n>> Hopefully it's not changing that much, though. Ditto kernel versions,\n>> but the mmap/sbrk interface is likely more stable. We can test this.\n> \n> That could be tested, yes. As a matter of fact, a commit removing the upper \n> limit for MALLOC_MMAP_THRESHOLD has just been committed yesterday to glibc, \n> which means we can service much bigger allocation without mmap.\n> \n\nYeah, I noticed that commit too. Most systems stick to one glibc\nversion, so it'll take time to reach most systems. Let's continue with\njust one glibc version and then maybe test other versions.\n\n> \n>>\n>> 3) If we bump the thresholds, won't that work against reusing the\n>> memory? I mean, if we free a whole block (from any allocator we have),\n>> glibc might return it to kernel, depending on mmap threshold value. It's\n>> not guaranteed, but increasing the malloc thresholds will make that even\n>> less likely. So we might just as well increase the minimum block size,\n>> with about the same effect, no?\n> \n> It is my understanding that malloc will try to compact memory by moving it \n> around. So the memory should be actually be released to the kernel at some \n> point. In the meantime, malloc can reuse it for our next invocation (which can \n> be in a different memory context on our side). \n> \n> If we increase the minimum block size, this is memory we will actually \n> reserve, and it will not protect us against the ramping-up behaviour:\n> - the first allocation of a big block may be over mmap_threshold, and serviced \n> by an expensive mmap\n> - when it's free, the threshold is doubled\n> - next invocation is serviced by an sbrk call\n> - freeing it will be above the trim threshold, and it will be returned.\n> \n> After several \"big\" allocations, the thresholds will raise to their maximum \n> values (well, it used to, I need to check what happens with that latest patch \n> of glibc...)\n> \n> This will typically happen several times as malloc doubles the threshold each \n> time. This is probably the reason quadrupling the block sizes was more \n> effective. \n> \n\nHmmm, OK. Can we we benchmark the case with large initial block size, at\nleast for comparison?\n\n> \n>>\n>>> I would like to try to implement some dynamic glibc malloc tuning, if that\n>>> is something we don't reject on principle from the get go.\n>>\n>> +1 to that\n> \n> Ok, I'll work on a patch for this and submit a new thread. \n> \n\nCool!\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Fri, 17 Dec 2021 14:39:10 +0100", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Le vendredi 17 décembre 2021, 14:39:10 CET Tomas Vondra a écrit :\n> I wasn't really suggesting to investigate those other allocators in this\n> patch - it seems like a task requiring a pretty significant amount of\n> work/time. My point was that we should make it reasonably easy to add\n> tweaks for those other environments, if someone is interested enough to\n> do the legwork.\n> \n> >> 2) In fact, I wonder if different glibc versions behave differently?\n> >> Hopefully it's not changing that much, though. Ditto kernel versions,\n> >> but the mmap/sbrk interface is likely more stable. We can test this.\n> > \n> > That could be tested, yes. As a matter of fact, a commit removing the\n> > upper\n> > limit for MALLOC_MMAP_THRESHOLD has just been committed yesterday to\n> > glibc,\n> > which means we can service much bigger allocation without mmap.\n> \n> Yeah, I noticed that commit too. Most systems stick to one glibc\n> version, so it'll take time to reach most systems. Let's continue with\n> just one glibc version and then maybe test other versions.\n\nYes, I also need to figure out how to detect we're using glibc as I'm not very \nfamiliar with configure. \n\n> \n> >> 3) If we bump the thresholds, won't that work against reusing the\n> >> memory? I mean, if we free a whole block (from any allocator we have),\n> >> glibc might return it to kernel, depending on mmap threshold value. It's\n> >> not guaranteed, but increasing the malloc thresholds will make that even\n> >> less likely. So we might just as well increase the minimum block size,\n> >> with about the same effect, no?\n> > \n> > It is my understanding that malloc will try to compact memory by moving it\n> > around. So the memory should be actually be released to the kernel at some\n> > point. In the meantime, malloc can reuse it for our next invocation (which\n> > can be in a different memory context on our side).\n> > \n> > If we increase the minimum block size, this is memory we will actually\n> > \n> > reserve, and it will not protect us against the ramping-up behaviour:\n> > - the first allocation of a big block may be over mmap_threshold, and\n> > serviced> \n> > by an expensive mmap\n> > \n> > - when it's free, the threshold is doubled\n> > - next invocation is serviced by an sbrk call\n> > - freeing it will be above the trim threshold, and it will be returned.\n> > \n> > After several \"big\" allocations, the thresholds will raise to their\n> > maximum\n> > values (well, it used to, I need to check what happens with that latest\n> > patch of glibc...)\n> > \n> > This will typically happen several times as malloc doubles the threshold\n> > each time. This is probably the reason quadrupling the block sizes was\n> > more effective.\n> \n> Hmmm, OK. Can we we benchmark the case with large initial block size, at\n> least for comparison?\n\nThe benchmark I called \"fixed\" was with a fixed block size of \nALLOCSET_DEFAULT_MAXSIZE (first proposed patch) and showed roughly the same \nperformance profile as the growing blocks + malloc tuning.\nBut if I understand correctly, you implemented the growing blocks logic after \nconcerns about wasting memory with a constant large block size. If we tune \nmalloc, that memory would not be wasted if we don't alloc it, just not \nreleased as eagerly when it's allocated. \n\nOr do you want a benchmark with an even bigger initial block size ? With the \ngrowing blocks patch with a large initial size ? I can run either, I just want \nto understand what is interesting to you.\n\nOne thing that would be interesting would be to trace the total amount of \nmemory allocated in the different cases. This is something I will need to do \nanyway when I propose that patch; \n\nBest regards,\n\n-- \nRonan Dunklau\n\n\n\n\n", "msg_date": "Fri, 17 Dec 2021 15:00:25 +0100", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Fri, 10 Sept 2021 at 01:38, Tomas Vondra\n<tomas.vondra@enterprisedb.com> wrote:\n> I've spent quite a bit of time investigating the regressions clearly\n> visible in the benchmark results for some allocation/free patterns.\n> Attached is a subset of results from a recent run, but the old results\n> show mostly the same thing.\n\nI started looking at the original patch again and wondered if it might\nbe a good idea to allow the estimates from the planner about the tuple\nsize and the number of tuples to help determine the size of the chunks\nin the generation context. The number of tuples can maybe also help\nsize the array that we're sorting, which would save us allocating just\n1024 elements and doubling it each time we run out of space in the\narray.\n\nThe main problem with that is that there will be many cases where we\nneed to sort but don't have any estimates from the planner, so if we\ndo this, then likely, we'll still need the chunk growing code.\n\nI've attached some benchmark results that I took recently. The\nspreadsheet contains results from 3 versions. master, master + 0001 -\n0002, then master + 0001 - 0003. The 0003 patch makes the code a bit\nmore conservative about the chunk sizes it allocates and also tries to\nallocate the tuple array according to the number of tuples we expect\nto be able to sort in a single batch for when the sort is not\nestimated to fit inside work_mem.\n\nFor the 4MB work_mem test in the spreadsheet, this does end up using\n2MB chunks rather than 4MB chunks. This is because the 10k tuple test\nis just so close to requiring 4MB of memory to perform the sort. This\ndoes mean that for the 10k tuple test, the 0003 patch makes things\nlook quite a bit slower than just with the 0001 + 0002 patch. However,\nI think not making the chunk size the same size as work_mem is a good\nidea.\n\nThe patch is still WIP. I still have a few magic numbers in there,\nfor example the 48 in:\n\nstate->est_tuple_memory = pg_nextpower2_64(state->est_tuples *\n(state->est_tupwidth + 48));\n\nI should really have a sizeof() in there. I've not really looked for\nother opportunities other than in nodeSort.c for where I can pass down\ntuple estimates down into tuplesort.c\n\nDavid", "msg_date": "Sat, 1 Jan 2022 10:26:37 +1300", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Le vendredi 31 décembre 2021, 22:26:37 CET David Rowley a écrit :\n> I've attached some benchmark results that I took recently. The\n> spreadsheet contains results from 3 versions. master, master + 0001 -\n> 0002, then master + 0001 - 0003. The 0003 patch makes the code a bit\n> more conservative about the chunk sizes it allocates and also tries to\n> allocate the tuple array according to the number of tuples we expect\n> to be able to sort in a single batch for when the sort is not\n> estimated to fit inside work_mem.\n\n(Sorry for trying to merge back the discussion on the two sides of the thread)\n\nIn https://www.postgresql.org/message-id/4776839.iZASKD2KPV%40aivenronan, I \nexpressed the idea of being able to tune glibc's malloc behaviour. \n\nI implemented that (patch 0001) to provide a new hook which is called on \nbackend startup, and anytime we set work_mem. This hook is # defined depending \non the malloc implementation: currently a default, no-op implementation is \nprovided as well as a glibc's malloc implementation.\n\nThe glibc's malloc implementation relies on a new GUC, \nglibc_malloc_max_trim_threshold. When set to it's default value of -1, we \ndon't tune malloc at all, exactly as in HEAD. If a different value is provided, \nwe set M_MMAP_THRESHOLD to half this value, and M_TRIM_TRESHOLD to this value, \ncapped by work_mem / 2 and work_mem respectively. \n\nThe net result is that we can then allow to keep more unused memory at the top \nof the heap, and to use mmap less frequently, if the DBA chooses too. A \npossible other use case would be to on the contrary, limit the allocated \nmemory in idle backends to a minimum. \n\nThe reasoning behind this is that glibc's malloc default way of handling those \ntwo thresholds is to adapt to the size of the last freed mmaped block. \n\nI've run the same \"up to 32 columns\" benchmark as you did, with this new patch \napplied on top of both HEAD and your v2 patchset incorporating planner \nestimates for the block sizez. Those are called \"aset\" and \"generation\" in the \nattached spreadsheet. For each, I've run it with \nglibc_malloc_max_trim_threshold set to -1, 1MB, 4MB and 64MB. In each case \nI've measured two things:\n - query latency, as reported by pgbench\n - total memory allocated by malloc at backend ext after running each query \nthree times. This represents the \"idle\" memory consumption, and thus what we \nwaste in malloc inside of releasing back to the system. This measurement has \nbeen performed using the very small module presented in patch 0002. Please \nnote that I in no way propose that we include this module, it was just a \nconvenient way for me to measure memory footprint.\n\nMy conclusion is that the impressive gains you see from using the generation \ncontext with bigger blocks mostly comes from the fact that we allocate bigger \nblocks, and that this moves the mmap thresholds accordingly. I wonder how much \nof a difference it would make on other malloc implementation: I'm afraid the \noptimisation presented here would in fact be specific to glibc's malloc, since \nwe have almost the same gains with both allocators when tuning malloc to keep \nmore memory. I still think both approaches are useful, and would be necessary. \n\nSince this affects all memory allocations, I need to come up with other \nmeaningful scenarios to benchmarks.\n\n\n-- \nRonan Dunklau", "msg_date": "Fri, 07 Jan 2022 12:03:55 +0100", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On 1/7/22 12:03, Ronan Dunklau wrote:\n> Le vendredi 31 décembre 2021, 22:26:37 CET David Rowley a écrit :\n>> I've attached some benchmark results that I took recently. The\n>> spreadsheet contains results from 3 versions. master, master + 0001 -\n>> 0002, then master + 0001 - 0003. The 0003 patch makes the code a bit\n>> more conservative about the chunk sizes it allocates and also tries to\n>> allocate the tuple array according to the number of tuples we expect\n>> to be able to sort in a single batch for when the sort is not\n>> estimated to fit inside work_mem.\n> \n> (Sorry for trying to merge back the discussion on the two sides of the thread)\n> \n> In https://www.postgresql.org/message-id/4776839.iZASKD2KPV%40aivenronan, I\n> expressed the idea of being able to tune glibc's malloc behaviour.\n> \n> I implemented that (patch 0001) to provide a new hook which is called on\n> backend startup, and anytime we set work_mem. This hook is # defined depending\n> on the malloc implementation: currently a default, no-op implementation is\n> provided as well as a glibc's malloc implementation.\n> \n\nNot sure I'd call this a hook - that usually means a way to plug-in \ncustom code through a callback, and this is simply ifdefing a block of \ncode to pick the right implementation. Which may be a good way to do \nthat, just let's not call that a hook.\n\nThere's a commented-out MallocTuneHook() call, probably not needed.\n\nI wonder if #ifdefing is sufficient solution, because it happens at \ncompile time, so what if someone overrides the allocator in LD_PRELOAD? \nThat was a fairly common way to use a custom allocator in an existing \napplication. But I don't know how many people do that with Postgres (I'm \nnot aware of anyone doing that) or if we support that (it'd probably \napply to other stuff too, not just malloc). So maybe it's OK, and I \ncan't think of a better way anyway.\n\n> The glibc's malloc implementation relies on a new GUC,\n> glibc_malloc_max_trim_threshold. When set to it's default value of -1, we\n> don't tune malloc at all, exactly as in HEAD. If a different value is provided,\n> we set M_MMAP_THRESHOLD to half this value, and M_TRIM_TRESHOLD to this value,\n> capped by work_mem / 2 and work_mem respectively.\n> \n> The net result is that we can then allow to keep more unused memory at the top\n> of the heap, and to use mmap less frequently, if the DBA chooses too. A\n> possible other use case would be to on the contrary, limit the allocated\n> memory in idle backends to a minimum.\n> \n> The reasoning behind this is that glibc's malloc default way of handling those\n> two thresholds is to adapt to the size of the last freed mmaped block.\n> \n> I've run the same \"up to 32 columns\" benchmark as you did, with this new patch\n> applied on top of both HEAD and your v2 patchset incorporating planner\n> estimates for the block sizez. Those are called \"aset\" and \"generation\" in the\n> attached spreadsheet. For each, I've run it with\n> glibc_malloc_max_trim_threshold set to -1, 1MB, 4MB and 64MB. In each case\n> I've measured two things:\n> - query latency, as reported by pgbench\n> - total memory allocated by malloc at backend ext after running each query\n> three times. This represents the \"idle\" memory consumption, and thus what we\n> waste in malloc inside of releasing back to the system. This measurement has\n> been performed using the very small module presented in patch 0002. Please\n> note that I in no way propose that we include this module, it was just a\n> convenient way for me to measure memory footprint.\n> \n> My conclusion is that the impressive gains you see from using the generation\n> context with bigger blocks mostly comes from the fact that we allocate bigger\n> blocks, and that this moves the mmap thresholds accordingly. I wonder how much\n> of a difference it would make on other malloc implementation: I'm afraid the\n> optimisation presented here would in fact be specific to glibc's malloc, since\n> we have almost the same gains with both allocators when tuning malloc to keep\n> more memory. I still think both approaches are useful, and would be necessary.\n> \n\nInteresting measurements. It's intriguing that for generation contexts, \nthe default \"-1\" often outperforms \"1MB\" (but not the other options), \nwhile for aset it's pretty much \"the higher value the better\".\n\n> Since this affects all memory allocations, I need to come up with other\n> meaningful scenarios to benchmarks.\n> \n\nOK. Are you thinking about a different microbenchmark, or something \ncloser to real workload?\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Fri, 7 Jan 2022 13:03:28 +0100", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Le vendredi 7 janvier 2022, 13:03:28 CET Tomas Vondra a écrit :\n> On 1/7/22 12:03, Ronan Dunklau wrote:\n> > Le vendredi 31 décembre 2021, 22:26:37 CET David Rowley a écrit :\n> >> I've attached some benchmark results that I took recently. The\n> >> spreadsheet contains results from 3 versions. master, master + 0001 -\n> >> 0002, then master + 0001 - 0003. The 0003 patch makes the code a bit\n> >> more conservative about the chunk sizes it allocates and also tries to\n> >> allocate the tuple array according to the number of tuples we expect\n> >> to be able to sort in a single batch for when the sort is not\n> >> estimated to fit inside work_mem.\n> > \n> > (Sorry for trying to merge back the discussion on the two sides of the\n> > thread)\n> > \n> > In https://www.postgresql.org/message-id/4776839.iZASKD2KPV%40aivenronan,\n> > I expressed the idea of being able to tune glibc's malloc behaviour.\n> > \n> > I implemented that (patch 0001) to provide a new hook which is called on\n> > backend startup, and anytime we set work_mem. This hook is # defined\n> > depending on the malloc implementation: currently a default, no-op\n> > implementation is provided as well as a glibc's malloc implementation.\n> \n> Not sure I'd call this a hook - that usually means a way to plug-in\n> custom code through a callback, and this is simply ifdefing a block of\n> code to pick the right implementation. Which may be a good way to do\n> that, just let's not call that a hook.\n> \n> There's a commented-out MallocTuneHook() call, probably not needed.\n\nOk, I'll clean that up if we decide to proceed with this.\n\n> \n> I wonder if #ifdefing is sufficient solution, because it happens at\n> compile time, so what if someone overrides the allocator in LD_PRELOAD?\n> That was a fairly common way to use a custom allocator in an existing\n> application. But I don't know how many people do that with Postgres (I'm\n> not aware of anyone doing that) or if we support that (it'd probably\n> apply to other stuff too, not just malloc). So maybe it's OK, and I\n> can't think of a better way anyway.\n\nI couldn't think of a better way either, maybe there is something to be done \nwith trying to dlsym something specific to glibc's malloc implementation ?\n\n\n> \n> > The glibc's malloc implementation relies on a new GUC,\n> > glibc_malloc_max_trim_threshold. When set to it's default value of -1, we\n> > don't tune malloc at all, exactly as in HEAD. If a different value is\n> > provided, we set M_MMAP_THRESHOLD to half this value, and M_TRIM_TRESHOLD\n> > to this value, capped by work_mem / 2 and work_mem respectively.\n> > \n> > The net result is that we can then allow to keep more unused memory at the\n> > top of the heap, and to use mmap less frequently, if the DBA chooses too.\n> > A possible other use case would be to on the contrary, limit the\n> > allocated memory in idle backends to a minimum.\n> > \n> > The reasoning behind this is that glibc's malloc default way of handling\n> > those two thresholds is to adapt to the size of the last freed mmaped\n> > block.\n> > \n> > I've run the same \"up to 32 columns\" benchmark as you did, with this new\n> > patch applied on top of both HEAD and your v2 patchset incorporating\n> > planner estimates for the block sizez. Those are called \"aset\" and\n> > \"generation\" in the attached spreadsheet. For each, I've run it with\n> > glibc_malloc_max_trim_threshold set to -1, 1MB, 4MB and 64MB. In each case\n> > \n> > I've measured two things:\n> > - query latency, as reported by pgbench\n> > - total memory allocated by malloc at backend ext after running each\n> > query\n> > \n> > three times. This represents the \"idle\" memory consumption, and thus what\n> > we waste in malloc inside of releasing back to the system. This\n> > measurement has been performed using the very small module presented in\n> > patch 0002. Please note that I in no way propose that we include this\n> > module, it was just a convenient way for me to measure memory footprint.\n> > \n> > My conclusion is that the impressive gains you see from using the\n> > generation context with bigger blocks mostly comes from the fact that we\n> > allocate bigger blocks, and that this moves the mmap thresholds\n> > accordingly. I wonder how much of a difference it would make on other\n> > malloc implementation: I'm afraid the optimisation presented here would\n> > in fact be specific to glibc's malloc, since we have almost the same\n> > gains with both allocators when tuning malloc to keep more memory. I\n> > still think both approaches are useful, and would be necessary.\n> Interesting measurements. It's intriguing that for generation contexts,\n> the default \"-1\" often outperforms \"1MB\" (but not the other options),\n> while for aset it's pretty much \"the higher value the better\".\n\nFor generation context with \"big block sizes\" this result is expected, as the \nmalloc dynamic tuning will adapt to the big block size. This can also be seen \non the \"idle memory\" measurement: the memory consumption is identical to the \n64MB value when using -1, since that's what we converge to. This makes it \npossible to configure postgres to be more conservative with memory: for \nexample, if we have long lived backend where we sometime temporarily set \nwork_mem to a high value, we may end up with a large memory foot print. The \nimplementation I provide also requests a malloc trim when we lower the \nthreshold, making it possible to release memory that would have otherwise been \nkept around forever. \n\nFor aset, the memory allocation pattern is a bit more complicated, and we \ndon't end up with such a high value for mmap_threshold. \n\nAlso, one thing that I haven't explained yet is the weird outlier when there \nis only one column. \n\n\n\n> \n> > Since this affects all memory allocations, I need to come up with other\n> > meaningful scenarios to benchmarks.\n> \n> OK. Are you thinking about a different microbenchmark, or something\n> closer to real workload?\n\nBoth. As for microbenchmarking, I'd like to test the following scenarios:\n - set returning functions allocating a lot of memory\n - maintenance operations: REINDEX TABLE and the like, where we may end up \nwith a large amount of memory used.\n - operations involving large hash tables\n\nFor real workloads, if you have something specific in mind let me know.\n\nOne thing I didn't mention is that I set max_parallel_workers_per_gather to 0 \nin all tests.\n\n\n-- \nRonan Dunklau\n\n\n\n\n", "msg_date": "Fri, 07 Jan 2022 13:49:53 +0100", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Hi,\n\nOn Fri, Jan 07, 2022 at 12:03:55PM +0100, Ronan Dunklau wrote:\n> \n> (Sorry for trying to merge back the discussion on the two sides of the thread)\n> \n> In https://www.postgresql.org/message-id/4776839.iZASKD2KPV%40aivenronan, I \n> expressed the idea of being able to tune glibc's malloc behaviour. \n> \n> I implemented that (patch 0001) to provide a new hook which is called on \n> backend startup, and anytime we set work_mem. This hook is # defined depending \n> on the malloc implementation: currently a default, no-op implementation is \n> provided as well as a glibc's malloc implementation.\n\nThis patch apparently misses something to have the no-op on windows:\n\nhttps://cirrus-ci.com/task/4978247640285184\n[03:03:01.676] Build FAILED.\n[03:03:01.676]\n[03:03:01.676] c:\\cirrus\\contrib\\malloc_stats\\malloc_stats.c(19,15): warning C4013: 'mallinfo2' undefined; assuming extern returning int [c:\\cirrus\\malloc_stats.vcxproj]\n[03:03:01.676] c:\\cirrus\\contrib\\malloc_stats\\malloc_stats.c(18,19): error C2079: 'm' uses undefined struct 'mallinfo2' [c:\\cirrus\\malloc_stats.vcxproj]\n[03:03:01.676] c:\\cirrus\\contrib\\malloc_stats\\malloc_stats.c(32,1): error C2224: left of '.arena' must have struct/union type [c:\\cirrus\\malloc_stats.vcxproj]\n[03:03:01.676] c:\\cirrus\\contrib\\malloc_stats\\malloc_stats.c(32,1): error C2224: left of '.hblkhd' must have struct/union type [c:\\cirrus\\malloc_stats.vcxproj]\n[03:03:01.676] c:\\cirrus\\contrib\\malloc_stats\\malloc_stats.c(32,1): error C2224: left of '.uordblks' must have struct/union type [c:\\cirrus\\malloc_stats.vcxproj]\n[03:03:01.676] c:\\cirrus\\contrib\\malloc_stats\\malloc_stats.c(32,1): error C2224: left of '.fordblks' must have struct/union type [c:\\cirrus\\malloc_stats.vcxproj]\n[03:03:01.676] c:\\cirrus\\contrib\\malloc_stats\\malloc_stats.c(32,1): error C2224: left of '.keepcost' must have struct/union type [c:\\cirrus\\malloc_stats.vcxproj]\n\nI'm also a bit confused about which patch(es) should actually be reviewed in\nthat thread. My understanding is that the original patch might not be relevant\nanymore but I might be wrong. The CF entry should probably be updated to\nclarify that, with an annotation/ title change / author update or something.\n\nIn the meantime I will switch the entry to Waiting on Author.\n\n\n", "msg_date": "Tue, 18 Jan 2022 14:45:39 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Tue, 18 Jan 2022 at 19:45, Julien Rouhaud <rjuju123@gmail.com> wrote:\n> I'm also a bit confused about which patch(es) should actually be reviewed in\n> that thread. My understanding is that the original patch might not be relevant\n> anymore but I might be wrong. The CF entry should probably be updated to\n> clarify that, with an annotation/ title change / author update or something.\n>\n> In the meantime I will switch the entry to Waiting on Author.\n\nI think what's going on here is a bit confusing. There's quite a few\npatches on here that aim to do very different things.\n\nThe patch I originally proposed was just to make tuplesort use\ngeneration memory contexts. This helps speed up tuplesort because\ngeneration contexts allow palloc() to be faster than the standard\nallocator. Additionally, there's no power-of-2 wastage with generation\ncontexts like there is with the standard allocator. This helps fit\nmore tuples on fewer CPU cache lines.\n\nI believe Andres then mentioned that the fixed block size for\ngeneration contexts might become a problem. With the standard\nallocator the actual size of the underlying malloc() grows up until a\nmaximum size. With generation contexts this is always the same, so we\ncould end up with a very large number of blocks which means lots of\nsmall mallocs which could end up slow. Tomas then posted a series of\npatches to address this.\n\nI then posted another patch that has the planner make a choice on the\nsize of the blocks to use for the generation context based on the\ntuple width and number of tuple estimates. My hope there was to\nimprove performance further by making a better choice for how large to\nmake the blocks in the first place. This reduces the need for Tomas'\npatch, but does not eliminate the need for it.\n\nAs of now, I still believe we'll need Tomas' patches to allow the\nblock size to grow up to a maximum size. I think those patches are\nlikely needed before we think about making tuplesort use generation\ncontexts. The reason I believe this is that we don't always have good\nestimates for the number of tuples we're going to sort. nodeSort.c is\nfairly easy as it just fetches tuples once and then sorts them. The\nuse of tuplesort for nodeIncrementalSort.c is much more complex as\nwe'll likely be performing a series of smaller sorts which are much\nharder to get size estimates for. This means there's likely no magic\nblock size that we can use for the generation context that's used to\nstore the tuples in tuplesort. This is also the case for order by\naggregates and probably most other usages of tuplesort.\n\nDavid\n\n\n", "msg_date": "Thu, 20 Jan 2022 14:31:15 +1300", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Le jeudi 20 janvier 2022, 02:31:15 CET David Rowley a écrit :\n> On Tue, 18 Jan 2022 at 19:45, Julien Rouhaud <rjuju123@gmail.com> wrote:\n> > I'm also a bit confused about which patch(es) should actually be reviewed\n> > in that thread. My understanding is that the original patch might not be\n> > relevant anymore but I might be wrong. The CF entry should probably be\n> > updated to clarify that, with an annotation/ title change / author update\n> > or something.\n> > \n> > In the meantime I will switch the entry to Waiting on Author.\n> \n> I think what's going on here is a bit confusing. There's quite a few\n> patches on here that aim to do very different things.\n> \n> The patch I originally proposed was just to make tuplesort use\n> generation memory contexts. This helps speed up tuplesort because\n> generation contexts allow palloc() to be faster than the standard\n> allocator. Additionally, there's no power-of-2 wastage with generation\n> contexts like there is with the standard allocator. This helps fit\n> more tuples on fewer CPU cache lines.\n> \n> I believe Andres then mentioned that the fixed block size for\n> generation contexts might become a problem. With the standard\n> allocator the actual size of the underlying malloc() grows up until a\n> maximum size. With generation contexts this is always the same, so we\n> could end up with a very large number of blocks which means lots of\n> small mallocs which could end up slow. Tomas then posted a series of\n> patches to address this.\n> \n> I then posted another patch that has the planner make a choice on the\n> size of the blocks to use for the generation context based on the\n> tuple width and number of tuple estimates. My hope there was to\n> improve performance further by making a better choice for how large to\n> make the blocks in the first place. This reduces the need for Tomas'\n> patch, but does not eliminate the need for it.\n> \n> As of now, I still believe we'll need Tomas' patches to allow the\n> block size to grow up to a maximum size. I think those patches are\n> likely needed before we think about making tuplesort use generation\n> contexts. The reason I believe this is that we don't always have good\n> estimates for the number of tuples we're going to sort. nodeSort.c is\n> fairly easy as it just fetches tuples once and then sorts them. The\n> use of tuplesort for nodeIncrementalSort.c is much more complex as\n> we'll likely be performing a series of smaller sorts which are much\n> harder to get size estimates for. This means there's likely no magic\n> block size that we can use for the generation context that's used to\n> store the tuples in tuplesort. This is also the case for order by\n> aggregates and probably most other usages of tuplesort.\n> \n\nYou left out the discussion I started about glibc's malloc specific behaviour.\n\nI tried to demonstrate that a big part of the performance gain you were seeing \nwere not in fact due to our allocator by itself, but by the way different block \nsizes allocations interact with this malloc implementation and how it handles \nreleasing memory back to the system. I also tried to show that we can give \nDBAs more control over how much memory to \"waste\" as the price for faster \nallocations.\n\nI agree that the generation context memory manager is useful in the tuplesort \ncontext, if only for the fact that we fall back to disk less quickly due to \nthe reduced wastage of memory, but I would be wary of drawing conclusions too \nquickly based on a specific malloc implementation which shows threshold effects, \nwhich are compounded by our growing block sizes code in general.\n\nI have on my TODO list to run the same kind of benchmarks using jemalloc, to \nbetter isolate the performance gains expected from the generation allocator \nitself from the side effect of avoiding glibc's pattern of releasing memory \nback to the kernel too quickly. \n\nJulien, sorry for the confusion of adding that discussion and those patches \nto the same thread, but I don't really see a way of dissociating those two \naspects.\n\n-- \nRonan Dunklau\n\n\n\n\n", "msg_date": "Thu, 20 Jan 2022 08:36:46 +0100", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Le jeudi 20 janvier 2022, 08:36:46 CET Ronan Dunklau a écrit :\n> Le jeudi 20 janvier 2022, 02:31:15 CET David Rowley a écrit :\n> > On Tue, 18 Jan 2022 at 19:45, Julien Rouhaud <rjuju123@gmail.com> wrote:\n> > > I'm also a bit confused about which patch(es) should actually be\n> > > reviewed\n> > > in that thread. My understanding is that the original patch might not\n> > > be\n> > > relevant anymore but I might be wrong. The CF entry should probably be\n> > > updated to clarify that, with an annotation/ title change / author\n> > > update\n> > > or something.\n> > > \n> > > In the meantime I will switch the entry to Waiting on Author.\n> > \n> > I think what's going on here is a bit confusing. There's quite a few\n> > patches on here that aim to do very different things.\n> > \n> > The patch I originally proposed was just to make tuplesort use\n> > generation memory contexts. This helps speed up tuplesort because\n> > generation contexts allow palloc() to be faster than the standard\n> > allocator. Additionally, there's no power-of-2 wastage with generation\n> > contexts like there is with the standard allocator. This helps fit\n> > more tuples on fewer CPU cache lines.\n> > \n> > I believe Andres then mentioned that the fixed block size for\n> > generation contexts might become a problem. With the standard\n> > allocator the actual size of the underlying malloc() grows up until a\n> > maximum size. With generation contexts this is always the same, so we\n> > could end up with a very large number of blocks which means lots of\n> > small mallocs which could end up slow. Tomas then posted a series of\n> > patches to address this.\n> > \n> > I then posted another patch that has the planner make a choice on the\n> > size of the blocks to use for the generation context based on the\n> > tuple width and number of tuple estimates. My hope there was to\n> > improve performance further by making a better choice for how large to\n> > make the blocks in the first place. This reduces the need for Tomas'\n> > patch, but does not eliminate the need for it.\n> > \n> > As of now, I still believe we'll need Tomas' patches to allow the\n> > block size to grow up to a maximum size. I think those patches are\n> > likely needed before we think about making tuplesort use generation\n> > contexts. The reason I believe this is that we don't always have good\n> > estimates for the number of tuples we're going to sort. nodeSort.c is\n> > fairly easy as it just fetches tuples once and then sorts them. The\n> > use of tuplesort for nodeIncrementalSort.c is much more complex as\n> > we'll likely be performing a series of smaller sorts which are much\n> > harder to get size estimates for. This means there's likely no magic\n> > block size that we can use for the generation context that's used to\n> > store the tuples in tuplesort. This is also the case for order by\n> > aggregates and probably most other usages of tuplesort.\n> \n> You left out the discussion I started about glibc's malloc specific\n> behaviour.\n> \n> I tried to demonstrate that a big part of the performance gain you were\n> seeing were not in fact due to our allocator by itself, but by the way\n> different block sizes allocations interact with this malloc implementation\n> and how it handles releasing memory back to the system. I also tried to\n> show that we can give DBAs more control over how much memory to \"waste\" as\n> the price for faster allocations.\n> \n> I agree that the generation context memory manager is useful in the\n> tuplesort context, if only for the fact that we fall back to disk less\n> quickly due to the reduced wastage of memory, but I would be wary of\n> drawing conclusions too quickly based on a specific malloc implementation\n> which shows threshold effects, which are compounded by our growing block\n> sizes code in general.\n> \n> I have on my TODO list to run the same kind of benchmarks using jemalloc, to\n> better isolate the performance gains expected from the generation allocator\n> itself from the side effect of avoiding glibc's pattern of releasing memory\n> back to the kernel too quickly.\n> \n\nI've run the same 1-to-32-columns sort benchmark, using both glibc malloc and \njemalloc, with the standard aset memory manager or with David's generation v2 \npatch. To use jemalloc, I just use a LD_PRELOAD env variable before starting \npostgres. \n\nI have not tried to measure jemalloc's memory footprint like I did for glibc's \nmalloc in the previous benchmark, as I'm not trying to evaluate jemalloc as a \nglibc's malloc replacement. \n\nPlease find the results attached. As I suspected, most of the gain observed \nwith David's patch come from working around glibc's malloc idiosyncracies but \nthe good news is that it also helps (to a lesser degree) with jemalloc.\n\nI'm not sure how that would behave with growing block sizes though: as Tomas \npatch and stress-testing benchmarks showed, we can hit some particular \nthresholds (and regressions) in glibc's self-tuning behaviour.\n\n-- \nRonan Dunklau", "msg_date": "Tue, 25 Jan 2022 13:34:23 +0100", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Hi:\n\nOn Thu, Jan 20, 2022 at 9:31 AM David Rowley <dgrowleyml@gmail.com> wrote:\n\n>\n> As of now, I still believe we'll need Tomas' patches to allow the\n> block size to grow up to a maximum size. I think those patches are\n> likely needed before we think about making tuplesort use generation\n> contexts. The reason I believe this is that we don't always have good\n> estimates for the number of tuples we're going to sort.\n\n\n+1\n\nI spent some times to study the case here and my current thought is:\nwe can discuss/commit the minimum committable changes which\nshould be beneficial for some cases and no harm for others.\nTomas's patch 0002 would make there are no more blocks needed\nif we switch to GenerationContext (compared with Standard Context). and\nDavid's patch can obviously reduce total memory usage and improve\nthe performance. so IMO Tomas's patch 0002 + David's patch is a committable\npatchset at first round. and Tomas's 0001 patch would be good to have\nas well.\n\nI double checked Tomas's 0002 patch, it looks good to me. and then applied\nDavid's patch with ALLOCSET_DEFAULT_SIZES, testing the same workload.\nHere is the result (number is tps):\n\nwork_mem = '4GB'\n\n| Test Case | master | patched |\n|-----------+--------+---------|\n| Test 1 | 306 | 406 |\n| Test 2 | 225 | 278 |\n| Test 3 | 202 | 248 |\n| Test 4 | 184 | 218 |\n| Test 5 | 281 | 360 |\n\nwork_mem = '4MB'\n\n| Test Case | master | patched |\n|-----------+--------+---------|\n| Test 1 | 124 | 409 |\n| Test 2 | 106 | 280 |\n| Test 3 | 100 | 249 |\n| Test 4 | 97 | 218 |\n| Test 5 | 120 | 369 |\n\n\nI didn't get the performance improvement as much as David's at the\nbeginning, I\nthink that is because David uses the ALLOCSET_DEFAULT_MAXSIZE directly which\nwill need less number of times for memory allocation.\n\nAFAICS, Tomas's patch 0002 + David's patch should be ready for commit for\nround 1.\nWe can try other opportunities like use rows estimation to allocate initial\nmemory and\nGenerationContext improves like 0003/0004. Would this work?\n\n-- \nBest Regards\nAndy Fan\n\nHi:On Thu, Jan 20, 2022 at 9:31 AM David Rowley <dgrowleyml@gmail.com> wrote:\nAs of now, I still believe we'll need Tomas' patches to allow the\nblock size to grow up to a maximum size.  I think those patches are\nlikely needed before we think about making tuplesort use generation\ncontexts.  The reason I believe this is that we don't always have good\nestimates for the number of tuples we're going to sort. +1 I spent some times to study the case here and my current thought is:we can discuss/commit the minimum committable changes which should be beneficial for some cases and no harm for others. Tomas's patch 0002 would make there are no more blocks neededif we switch to GenerationContext (compared with Standard Context). andDavid's patch can obviously reduce total memory usage and improvethe performance.  so IMO Tomas's patch 0002 + David's patch is a committablepatchset at first round.  and Tomas's 0001 patch would be good to haveas well. I double checked Tomas's 0002 patch, it looks good to me.  and then appliedDavid's patch with ALLOCSET_DEFAULT_SIZES,  testing the same workload.Here is the result (number is tps):work_mem = '4GB'| Test Case | master | patched ||-----------+--------+---------|| Test 1    |    306 |     406 || Test 2    |    225 |     278 || Test 3    |    202 |     248 || Test 4    |    184 |     218 || Test 5    |    281 |     360 |work_mem = '4MB'| Test Case | master | patched ||-----------+--------+---------|| Test 1    |    124 |     409 || Test 2    |    106 |     280 || Test 3    |    100 |     249 || Test 4    |    97  |     218 || Test 5    |    120 |     369 |I didn't get the performance improvement as much as David's at the beginning,  Ithink that is because David uses the ALLOCSET_DEFAULT_MAXSIZE directly whichwill need less number of times for memory allocation.AFAICS,  Tomas's patch 0002 + David's patch should be ready for commit for round 1.We can try other opportunities like use rows estimation to allocate initial memory andGenerationContext improves like 0003/0004.  Would this work? -- Best RegardsAndy Fan", "msg_date": "Mon, 7 Feb 2022 05:41:25 +0800", "msg_from": "Andy Fan <zhihui.fan1213@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On 1/25/22 13:34, Ronan Dunklau wrote:\n>\n> ...\n>\n> I've run the same 1-to-32-columns sort benchmark, using both glibc malloc and \n> jemalloc, with the standard aset memory manager or with David's generation v2 \n> patch. To use jemalloc, I just use a LD_PRELOAD env variable before starting \n> postgres. \n> \n> I have not tried to measure jemalloc's memory footprint like I did for glibc's \n> malloc in the previous benchmark, as I'm not trying to evaluate jemalloc as a \n> glibc's malloc replacement. \n> \n> Please find the results attached. As I suspected, most of the gain observed \n> with David's patch come from working around glibc's malloc idiosyncracies but \n> the good news is that it also helps (to a lesser degree) with jemalloc.\n> \n> I'm not sure how that would behave with growing block sizes though: as Tomas \n> patch and stress-testing benchmarks showed, we can hit some particular \n> thresholds (and regressions) in glibc's self-tuning behaviour.\n> \n\nInteresting results!\n\nSo just switching to jemalloc can yield much better performance (in some\ncases), even beating the generation context (on top of glibc malloc).\n\nOf course, those are just simple (somewhat synthetic) benchmarks, and\nthere is no info about memory consumption. Perhaps there are cases where\nthis would be slower than glibc malloc, and I doubt many people to\nswitch to a non-default malloc implementation.\n\nBut I think in general this mostly confirms our suspicion about the\npatch (somewhat accidentally) working around glibc internal behavior.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Sat, 12 Feb 2022 21:44:32 +0100", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On 1/20/22 08:36, Ronan Dunklau wrote:\n> Le jeudi 20 janvier 2022, 02:31:15 CET David Rowley a écrit :\n>> On Tue, 18 Jan 2022 at 19:45, Julien Rouhaud <rjuju123@gmail.com> wrote:\n>>> I'm also a bit confused about which patch(es) should actually be reviewed\n>>> in that thread. My understanding is that the original patch might not be\n>>> relevant anymore but I might be wrong. The CF entry should probably be\n>>> updated to clarify that, with an annotation/ title change / author update\n>>> or something.\n>>>\n>>> In the meantime I will switch the entry to Waiting on Author.\n>>\n>> I think what's going on here is a bit confusing. There's quite a few\n>> patches on here that aim to do very different things.\n>>\n>> The patch I originally proposed was just to make tuplesort use\n>> generation memory contexts. This helps speed up tuplesort because\n>> generation contexts allow palloc() to be faster than the standard\n>> allocator. Additionally, there's no power-of-2 wastage with generation\n>> contexts like there is with the standard allocator. This helps fit\n>> more tuples on fewer CPU cache lines.\n>>\n>> I believe Andres then mentioned that the fixed block size for\n>> generation contexts might become a problem. With the standard\n>> allocator the actual size of the underlying malloc() grows up until a\n>> maximum size. With generation contexts this is always the same, so we\n>> could end up with a very large number of blocks which means lots of\n>> small mallocs which could end up slow. Tomas then posted a series of\n>> patches to address this.\n>>\n>> I then posted another patch that has the planner make a choice on the\n>> size of the blocks to use for the generation context based on the\n>> tuple width and number of tuple estimates. My hope there was to\n>> improve performance further by making a better choice for how large to\n>> make the blocks in the first place. This reduces the need for Tomas'\n>> patch, but does not eliminate the need for it.\n>>\n>> As of now, I still believe we'll need Tomas' patches to allow the\n>> block size to grow up to a maximum size. I think those patches are\n>> likely needed before we think about making tuplesort use generation\n>> contexts. The reason I believe this is that we don't always have good\n>> estimates for the number of tuples we're going to sort. nodeSort.c is\n>> fairly easy as it just fetches tuples once and then sorts them. The\n>> use of tuplesort for nodeIncrementalSort.c is much more complex as\n>> we'll likely be performing a series of smaller sorts which are much\n>> harder to get size estimates for. This means there's likely no magic\n>> block size that we can use for the generation context that's used to\n>> store the tuples in tuplesort. This is also the case for order by\n>> aggregates and probably most other usages of tuplesort.\n>>\n> \n> You left out the discussion I started about glibc's malloc specific behaviour.\n> \n> I tried to demonstrate that a big part of the performance gain you were seeing \n> were not in fact due to our allocator by itself, but by the way different block \n> sizes allocations interact with this malloc implementation and how it handles \n> releasing memory back to the system. I also tried to show that we can give \n> DBAs more control over how much memory to \"waste\" as the price for faster \n> allocations.\n> \n> I agree that the generation context memory manager is useful in the tuplesort \n> context, if only for the fact that we fall back to disk less quickly due to \n> the reduced wastage of memory, but I would be wary of drawing conclusions too \n> quickly based on a specific malloc implementation which shows threshold effects, \n> which are compounded by our growing block sizes code in general.\n> \n\nYeah, I share this concern - how much of the improvement is real and how\nmuch is due to accidentally not hitting some glibc-specific self-tuning\nstuff? Would a realistic workloads get the same improvement or would it\ncause regression? What about non-glibc systems with other malloc?\n\nI'm not against pushing the generation context improvements, e.g.\nsomething like the patches posted in [1], because those seem reasonable\nin general. But I'm somewhat confused about the last patch (adjusting\nallocChunkLimit) causing fairly significant regressions.\n\nI'll try investigating this a bit more next week.\n\n\nregards\n\n\n[1]\nhttps://www.postgresql.org/message-id/flat/bcdd4e3e-c12d-cd2b-7ead-a91ad416100a%40enterprisedb.com#a5ecd4e5a9e7d5b07ff25b5684da894f\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Sat, 12 Feb 2022 21:56:09 +0100", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Sun, 13 Feb 2022 at 09:56, Tomas Vondra\n<tomas.vondra@enterprisedb.com> wrote:\n> I'm not against pushing the generation context improvements, e.g.\n> something like the patches posted in [1], because those seem reasonable\n> in general. But I'm somewhat confused about the last patch (adjusting\n> allocChunkLimit) causing fairly significant regressions.\n\nMy thoughts here are that we should pursue the patch that allows\ngrowing of the block size in the generation context. I do think the\ninvestigation of the malloc() behaviour and performance is worth some\npursuit, I just don't think it should be done here or as part of this\npatch. I think it's a fairly large undertaking to ensure any changes\nto the malloc options are an overall win and not just a win for\nwhatever benchmark we test them on. If they're really an overall win,\nthen shouldn't glibc know about them and maybe adopt them as the\nstandard options?\n\nTo get the ball rolling again on the changes to the generation\ncontext, I took your patches, Tomas, and fixed a few things around the\nkeeper blocks not working correctly. I've now made the keeper block\nbehaviour match how aset.c works. There the keeper block is allocated\nin the same allocation as the context itself. That reduces the number\nof malloc() calls when setting up a new memory context.\n\nOn testing this, I discovered a problem regarding the use of\ngeneration contexts for storing tuples in tuplesort.c. The problem is\nwhen the sort is bounded (e.g. SELECT * FROM ... ORDER BY .. LIMIT N),\nwe'll store and directly throw away any tuples that sort greater than\nthe existing set of N tuples. This causes a problem because once we\nmove away from using the keeper block, initially, we'll at some point\nend up storing a tuple in a newly allocated generation block then\nproceed to pfree() that tuple due to it sorting greater than the\nexisting N tuples. Because we currently always free() newly empty\nblocks, we end up thrashing free()/malloc(). This behaviour results\nin one of the regression test queries in tuplesort.sql going from\ntaking 10 ms to 1 minute, on my machine.\n\nI had a few thoughts about how best to work around this problem.\nFirstly, I thought that we should just *not* use the Generation\ncontext when the sort is bounded. That turns out to be a bit icky as\nwe only make the sort bounding when we call tuplesort_set_bound(),\nwhich is after we've allocated the memory context for storing tuples.\nI thought about maybe just adding another bool flag named\n\"allowBounding\" and use a Generation context if that flag is not set.\nI just don't really like that as a solution. We also cannot make the\nset bound part of the tuplesort_begin_heap() call as\nnodeIncrementalSort.c does reset the bound. Possibly we could ditch\ntuplesort_set_bound() and invent tuplesort_reset_bound() and change\nthe API so the bound is set when making the Tuplesortstate.\n\nThe other way I thought to fix it was by changing the logic for when\ngeneration blocks are freed. In the problem case mentioned above, the\nblock being freed is the current block (which was just allocated). I\nmade some changes to adjust this behaviour so that we no longer free\nthe block when the final chunk is pfree()'d. Instead, that now lingers\nand can be reused by future allocations, providing they fit inside it.\nIf they don't fit then we must free the block, otherwise it would just\nremain empty forever. The problem I see with this method is that\nthere still could be some pathological case that causes us to end up\nstoring just a single tuple per generation block.\n\nHitting the worst case here does seem pretty unlikely, so I'm a bit\ndrawn between if we should just play it safe and stick to the standard\nmemory allocator for bounded sort.\n\nI've attached 2 patches. The 0001 patch adds the new logic to\ngeneration.c to allow the block to grow and also adds the logic to\nskip freeing the current block when it becomes empty. The 0002 patch\nsimply makes tuplesort.c use the generation context for tuples\nunconditionally.\n\nI've also attached the benchmark results I got from this patch running\nthe attached sortbenchall script. It's fairly obvious that there are\nperformance improvements here even when the malloc() usage pattern is\nsimilar to aset.c's\n\nDavid", "msg_date": "Fri, 18 Feb 2022 12:10:51 +1300", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Hi,\n\nOn 2022-02-18 12:10:51 +1300, David Rowley wrote:\n> The other way I thought to fix it was by changing the logic for when\n> generation blocks are freed. In the problem case mentioned above, the\n> block being freed is the current block (which was just allocated). I\n> made some changes to adjust this behaviour so that we no longer free\n> the block when the final chunk is pfree()'d. Instead, that now lingers\n> and can be reused by future allocations, providing they fit inside it.\n\nThat makes sense to me, as long as we keep just one such block.\n\n\n> The problem I see with this method is that there still could be some\n> pathological case that causes us to end up storing just a single tuple per\n> generation block.\n\nCrazy idea: Detect the situation, and recompact. Create a new context, copy\nall the tuples over, delete the old context. That could be a win even in less\nadversarial situations than \"a single tuple per generation block\".\n\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 22 Feb 2022 18:25:04 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On 2/23/22 03:25, Andres Freund wrote:\n> Hi,\n> \n> On 2022-02-18 12:10:51 +1300, David Rowley wrote:\n>> The other way I thought to fix it was by changing the logic for when\n>> generation blocks are freed. In the problem case mentioned above, the\n>> block being freed is the current block (which was just allocated). I\n>> made some changes to adjust this behaviour so that we no longer free\n>> the block when the final chunk is pfree()'d. Instead, that now lingers\n>> and can be reused by future allocations, providing they fit inside it.\n> \n> That makes sense to me, as long as we keep just one such block.\n> \n> \n>> The problem I see with this method is that there still could be some\n>> pathological case that causes us to end up storing just a single tuple per\n>> generation block.\n> \n> Crazy idea: Detect the situation, and recompact. Create a new context, copy\n> all the tuples over, delete the old context. That could be a win even in less\n> adversarial situations than \"a single tuple per generation block\".\n> \n\nWhat about pointers to the chunks in the old memory context?\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Wed, 23 Feb 2022 20:19:52 +0100", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Wed, 23 Feb 2022 at 15:25, Andres Freund <andres@anarazel.de> wrote:\n> On 2022-02-18 12:10:51 +1300, David Rowley wrote:\n> > The other way I thought to fix it was by changing the logic for when\n> > generation blocks are freed. In the problem case mentioned above, the\n> > block being freed is the current block (which was just allocated). I\n> > made some changes to adjust this behaviour so that we no longer free\n> > the block when the final chunk is pfree()'d. Instead, that now lingers\n> > and can be reused by future allocations, providing they fit inside it.\n>\n> That makes sense to me, as long as we keep just one such block.\n\nI've rewritten the patch in such a way that it no longer matters which\nblock becomes free. What I did was add a new field to the\nGenerationContext named \"freeblock\". We now simply store up to 1\nrecently emptied block there instead of calling free() on it. When\nwe're allocating new memory, we'll try and make use of the \"freeblock\"\nwhen we don't have enough space in the current block.\n\nI feel like this is quite a good change as it saves continual\nfree/malloc calls for FIFO pattern users of the generation context.\nSince that's pretty much the workload that this context is intended\nfor, that seems like a very good change to make.\n\nI did consider only recording a block as free once it reaches the\nmaximum size. As I have the code currently, we'll continually reuse\nall blocks, including the initial sized ones. It will end up filling\nblocks quicker as we'll be reusing those smaller initial blocks\ncontinually with FIFO workloads. I'm not entirely sure if that\nmatters. I just wanted to point out that I thought about it.\n\nAside from the freeblock, I've also added code for adding a \"keeper\"\nblock. This is allocated in the same malloc'd chunk as the Generation\ncontext itself. One thing I'm not too sure about is if the keeper\nblock change is worth the trouble. If we pfree() all of the chunks\nout of the keeper block, there's a special case in GenerationFree() to\nempty that block rather than free() it. This also means we need a\nspecial case in GenerationAlloc() so we try to see if the keeper block\nhas any space before we go and allocate a new block. My current\nthoughts are that the keeper block is really only useful for\nGeneration contexts that remain very small and don't ever require\nallocation of additional blocks. This will mean all the memory can be\nallocated along with the context, which saves a malloc and free call.\nDoes anyone have any thoughts on this?\n\n> > The problem I see with this method is that there still could be some\n> > pathological case that causes us to end up storing just a single tuple per\n> > generation block.\n>\n> Crazy idea: Detect the situation, and recompact. Create a new context, copy\n> all the tuples over, delete the old context. That could be a win even in less\n> adversarial situations than \"a single tuple per generation block\".\n\nI think that would need some new MemoryContext API functions in which\ncallers could use to determine the fragmentation and do something\nabout it on the consumer side. Otherwise, as Tomas says, if we did it\nfrom within the context code itself we'd have no visibility of what is\npointing to the memory we're moving around.\n\nIf nobody has any objections to the 0001 patch then I'd like to move\nahead with it in the next few days. For the 0002 patch, I'm currently\nfeeling like we shouldn't be using the Generation context for bounded\nsorts. The only way I can think to do that is with an API change to\ntuplesort. I feel 0001 is useful even without 0002.\n\nDavid", "msg_date": "Wed, 23 Mar 2022 04:08:44 +1300", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Wed, 23 Mar 2022 at 04:08, David Rowley <dgrowleyml@gmail.com> wrote:\n> If nobody has any objections to the 0001 patch then I'd like to move\n> ahead with it in the next few days. For the 0002 patch, I'm currently\n> feeling like we shouldn't be using the Generation context for bounded\n> sorts. The only way I can think to do that is with an API change to\n> tuplesort. I feel 0001 is useful even without 0002.\n\n0001:\nI've made some small revisions to the 0001 patch so that the keeper\nand freeblock are only used again when they're entirely empty. The\nsituation I want to avoid here is that when the current block does not\nhave enough free space to store some new allocation, that we'll then\ntry the freeblock and then keeper block. The problem I saw there is\nthat we may previously have partially filled the keeper or freeblock\nblock and have been unable to store some medium sized allocation which\ncaused us to move to a new block. If we didn't check that the keeper\nand freeblock blocks were empty first then we could end up being able\nto store some small allocation in there where some previous medium\nsized allocation couldn't fit. While that's not necessarily an actual\nproblem, what it does mean is that consecutive allocations might not\nend up in the same block or the next block. Over time in a FIFO type\nworkload it would be possible to get fragmentation, which could result\nin being unable to free blocks. For longer lived contexts I imagine\nthat could end up fairly bad. The updated patch should avoid that\nproblem.\n\n0002:\nThis modifies the tuplesort API so that instead of having a\nrandomAccess bool flag, this is changed to a bitwise flag that we can\nadd further options in the future. It's slightly annoying to break\nthe API, but it's not exactly going to be hard for people to code\naround that. It might also mean we don't have to break the API in the\nfuture if we're doing some change where we can just add a new bitwise\nflag.\n\n0003:\nThis adds a new flag for TUPLESORT_ALLOWBOUNDED and modifies the\nplaces where we set a sort bound to pass the flag. The patch only\nuses the generation context when the flag is not passed.\n\nI feel this is a pretty simple patch and if nobody has any objections\nthen I plan to push all 3 of them on my New Zealand Monday morning.\n\nDavid", "msg_date": "Fri, 1 Apr 2022 22:00:08 +1300", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Fri, Apr 01, 2022 at 10:00:08PM +1300, David Rowley wrote:\n> 0002:\n> This modifies the tuplesort API so that instead of having a\n> randomAccess bool flag,\n\nPer cirrus, this missed updating one line for dtrace.\n\nOn Fri, Apr 01, 2022 at 10:00:08PM +1300, David Rowley wrote:\n> I feel this is a pretty simple patch and if nobody has any objections\n> then I plan to push all 3 of them on my New Zealand Monday morning.\n\nI'll mark the CF as such.\n\n-- \nJustin", "msg_date": "Fri, 1 Apr 2022 08:25:51 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Sat, 2 Apr 2022 at 02:25, Justin Pryzby <pryzby@telsasoft.com> wrote:\n>\n> On Fri, Apr 01, 2022 at 10:00:08PM +1300, David Rowley wrote:\n> > 0002:\n> > This modifies the tuplesort API so that instead of having a\n> > randomAccess bool flag,\n>\n> Per cirrus, this missed updating one line for dtrace.\n\nThanks.\n\nI've pushed all 3 of the patches now.\n\nDavid\n\n\n", "msg_date": "Mon, 4 Apr 2022 23:18:36 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Fri, Apr 01, 2022 at 10:00:08PM +1300, David Rowley wrote:\n> 0002:\n> This modifies the tuplesort API so that instead of having a\n> randomAccess bool flag, this is changed to a bitwise flag that we can\n> add further options in the future. It's slightly annoying to break\n> the API, but it's not exactly going to be hard for people to code\n> around that.\n\nFor what it's worth, the three PGXN extensions using tuplesort_begin_* are\n\"citus\", \"pg_bulkload\", and \"vector\". Nothing calls tuplesort_set_bound().\n\nThis (commit 77bae39) did not change function parameter counts, and\nTUPLESORT_RANDOMACCESS generally has same the same numeric value as \"true\". I\nget no warning if I pass \"true\" for the \"sortopt\" flags parameter. Hence, I\nsuspect this did not break the API. Should we be happy about that? I'm fine\nwith it.\n\n\n", "msg_date": "Sat, 23 Apr 2022 17:59:38 -0700", "msg_from": "Noah Misch <noah@leadboat.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "On Sat, Apr 23, 2022 at 5:59 PM Noah Misch <noah@leadboat.com> wrote:\n> This (commit 77bae39) did not change function parameter counts, and\n> TUPLESORT_RANDOMACCESS generally has same the same numeric value as \"true\". I\n> get no warning if I pass \"true\" for the \"sortopt\" flags parameter. Hence, I\n> suspect this did not break the API. Should we be happy about that? I'm fine\n> with it.\n\nIf I happened to believe that this issue (or one like it) might have\nreal negative consequences, and that those consequences could easily\nbe avoided (by making the API break impossible to overlook), then I\nwould object -- why even take a small chance? Fortunately I don't\nbelieve that we're even taking a small chance here, all things\nconsidered. And so I agree; this issue isn't a concern.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Sat, 23 Apr 2022 18:11:45 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Thanks for raising this.\n\nOn Sun, 24 Apr 2022 at 12:59, Noah Misch <noah@leadboat.com> wrote:\n> This (commit 77bae39) did not change function parameter counts, and\n> TUPLESORT_RANDOMACCESS generally has same the same numeric value as \"true\". I\n> get no warning if I pass \"true\" for the \"sortopt\" flags parameter. Hence, I\n> suspect this did not break the API. Should we be happy about that? I'm fine\n> with it.\n\nI'd be open to doing something like make sortopt the first argument of\neach of the tuplesort_begin* functions if people have concerns about\nthis causing problems. However, given that TUPLESORT_RANDOMACCESS and\ntrue likely have the same value, it seems we'd be more likely to break\ncode down the line if we added some option that's needed that wouldn't\nget set by passing \"true\" as the sortopt.\n\nIf anyone was to use tuplesort_set_bound() without updating their\ntuplesort_begin* then on non-assert builds, nothing would misbehave.\nThere's just a risk of having bad memory fragmentation from using the\ngeneration context for bounded sorts.\n\nDavid\n\n\n", "msg_date": "Sun, 24 Apr 2022 17:16:25 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Hi Ronan,\n\nWe briefly chatted about the glibc-tuning part of this thread at pgcon,\nso I wonder if you're still planning to pursue that. If you do, I\nsuggest we start a fresh thread, so that it's not mixed with the already\ncommitted improvements of generation context.\n\nI wonder what's the situation with the generation context improvements\nalready pushed - does setting the glibc thresholds still help, and if\nyes how much?\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Sun, 18 Jun 2023 20:22:17 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" }, { "msg_contents": "Le dimanche 18 juin 2023, 20:22:17 CEST Tomas Vondra a écrit :\n> Hi Ronan,\n> \n> We briefly chatted about the glibc-tuning part of this thread at pgcon,\n> so I wonder if you're still planning to pursue that. If you do, I\n> suggest we start a fresh thread, so that it's not mixed with the already\n> committed improvements of generation context.\n> \n> I wonder what's the situation with the generation context improvements\n> already pushed - does setting the glibc thresholds still help, and if\n> yes how much?\n\nHi Tomas ! \n\nI'm currently working on it, trying to evaluate the possible benefits on the \ncurrent ASet and Generation contexts usecases. \n\nI'll make sure to use a new thread to post my findings.\n\nThank you for remembering !\n\nBest regards,\n\n--\nRonan Dunklau\n\n\n\n\n\n\n", "msg_date": "Mon, 19 Jun 2023 09:01:56 +0200", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": false, "msg_subject": "Re: Use generation context to speed up tuplesorts" } ]
[ { "msg_contents": "While testing the numeric_power() patch in [1], I found this problem\ntrying to use to_char() to format very small numbers:\n\nSELECT to_char(1.2e-1001, '9.9EEEE'); -- OK\n to_char\n------------\n 1.2e-1001\n\nSELECT to_char(1.2e-1002, '9.9EEEE'); -- fails\nERROR: division by zero\n\nIt turns out that the problem is in get_str_from_var_sci() which\nattempts to divide the input by 1e-1002 to get the significand.\nHowever, it is using power_var_int() to compute 1e-1002, which has a\nmaximum rscale of NUMERIC_MAX_DISPLAY_SCALE (1000), so it returns 0,\nwhich is the correct answer to that scale, and then\nget_str_from_var_sci() attempts to divide by that.\n\nRather than messing with power_var_int(), I think the simplest\nsolution is to just introduce a new local function, as in the attached\npatch. This directly constructs 10^n, for integer n, which is pretty\ntrivial, and doesn't need any numeric multiplication or rounding.\n\nRegards,\nDean\n\n[1] https://www.postgresql.org/message-id/CAEZATCUWUV_BP41Ob7QY12oF%2BqDxjTWfDpkdkcOOuojrDvOLxw%40mail.gmail.com", "msg_date": "Fri, 30 Jul 2021 08:26:14 +0100", "msg_from": "Dean Rasheed <dean.a.rasheed@gmail.com>", "msg_from_op": true, "msg_subject": "Division by zero error in to_char(num, '9.9EEEE')" }, { "msg_contents": "On Fri, 30 Jul 2021 at 08:26, Dean Rasheed <dean.a.rasheed@gmail.com> wrote:\n>\n> SELECT to_char(1.2e-1002, '9.9EEEE'); -- fails\n> ERROR: division by zero\n>\n> I think the simplest\n> solution is to just introduce a new local function, as in the attached\n> patch. This directly constructs 10^n, for integer n, which is pretty\n> trivial, and doesn't need any numeric multiplication or rounding.\n>\n\nUnless there are any objections, I intend to push this shortly. I\nthink it's a fairly straightforward bug fix, and I want to be able to\nuse to_char() in some new numeric regression tests.\n\nRegards,\nDean\n\n\n", "msg_date": "Wed, 4 Aug 2021 08:38:49 +0100", "msg_from": "Dean Rasheed <dean.a.rasheed@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Division by zero error in to_char(num, '9.9EEEE')" } ]
[ { "msg_contents": "Hi, all\r\n\r\nWhen I used SPI_execute_plan function on PG12 which commit 41c6a5be is used,\r\nSegment fault occurred.\r\n\r\nPS: If commit 41c6a5be is not used, this phenomenon will not happen. \r\n\r\nReproduce:\r\nIn a background process, the following steps are executed.\r\n--------------------------\r\nStartTransactionCommand();\r\nSPI_connect();       \r\nplan = SPI_prepare(query,0,NULL); ★the query is a SELECT SQL. \r\nSPI_keepplan(plan);         \r\nSPI_finish();           \r\nCommitTransactionCommand();   \r\nStartTransactionCommand();    \r\nSPI_connect();\r\nSPI_execute_plan(plan, NULL, NULL, true, 0); ★Segment fault\r\n--------------------------\r\n\r\nCore stack:\r\nStack trace of thread 43926:\r\n #0 0x0000000000772f19 EnsurePortalSnapshotExists (postgres)\r\n #1 0x000000000064f85c _SPI_execute_plan (postgres)\r\n #2 0x000000000064fbd1 SPI_execute_plan (postgres)\r\n #3 0x00007fbee784402e xxx (xxx.so)\r\n #4 0x00007fbee78424ae xxxx (xxxx.so)\r\n #5 0x00000000006e91f5 StartBackgroundWorker (postgres)\r\n #6 0x00000000006f5e25 maybe_start_bgworkers (postgres)\r\n #7 0x00000000006f6121 reaper (postgres)\r\n #8 0x00007fbeedf48dc0 __restore_rt (libpthread.so.0)\r\n #9 0x00007fbeebadf75b __select (libc.so.6)\r\n #10 0x00000000006f6ea6 ServerLoop (postgres)\r\n #11 0x00000000006f8c30 PostmasterMain (postgres)\r\n #12 0x0000000000485d99 main (postgres)\r\n #13 0x00007fbeeba0f873 __libc_start_main (libc.so.6)\r\n #14 0x0000000000485e3e _start (postgres)\r\n\r\nIs there a bug in the commit 41c6a5be? Please confirm it.\r\n\r\nRegards, Liu Huailing\r\n\r\n", "msg_date": "Fri, 30 Jul 2021 08:57:35 +0000", "msg_from": "\"liuhuailing@fujitsu.com\" <liuhuailing@fujitsu.com>", "msg_from_op": true, "msg_subject": "Segment fault when excuting SPI function On PG with commit 41c6a5be" }, { "msg_contents": "On Fri, Jul 30, 2021 at 6:57 PM liuhuailing@fujitsu.com\n<liuhuailing@fujitsu.com> wrote:\n>\n> When I used SPI_execute_plan function on PG12 which commit 41c6a5be is used,\n> Segment fault occurred.\n\nI'm not seeing any such commit.\nCan you provide a link to the commit in GitHub?\n\nRegards,\nGreg Nancarrow\nFujitsu Australia\n\n\n", "msg_date": "Fri, 30 Jul 2021 20:30:30 +1000", "msg_from": "Greg Nancarrow <gregn4422@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Segment fault when excuting SPI function On PG with commit\n 41c6a5be" }, { "msg_contents": "On Fri, Jul 30, 2021 at 3:30 AM Greg Nancarrow <gregn4422@gmail.com> wrote:\n\n> On Fri, Jul 30, 2021 at 6:57 PM liuhuailing@fujitsu.com\n> <liuhuailing@fujitsu.com> wrote:\n> >\n> > When I used SPI_execute_plan function on PG12 which commit 41c6a5be is\n> used,\n> > Segment fault occurred.\n>\n> I'm not seeing any such commit.\n> Can you provide a link to the commit in GitHub?\n>\n> Regards,\n> Greg Nancarrow\n> Fujitsu Australia\n>\n>\n> Hi,\nI think Huailing was referring to:\n\ncommit 41c6a5bec25e720d98bd60d77dd5c2939189ed3c\nAuthor: Tom Lane <tgl@sss.pgh.pa.us>\nDate: Fri May 21 14:03:53 2021 -0400\n\n Restore the portal-level snapshot after procedure COMMIT/ROLLBACK.\n\nCheers\n\nOn Fri, Jul 30, 2021 at 3:30 AM Greg Nancarrow <gregn4422@gmail.com> wrote:On Fri, Jul 30, 2021 at 6:57 PM liuhuailing@fujitsu.com\n<liuhuailing@fujitsu.com> wrote:\n>\n> When I used SPI_execute_plan function on PG12 which commit 41c6a5be is used,\n> Segment fault occurred.\n\nI'm not seeing any such commit.\nCan you provide a link to the commit in GitHub?\n\nRegards,\nGreg Nancarrow\nFujitsu Australia\n\nHi,I think Huailing was referring to:commit 41c6a5bec25e720d98bd60d77dd5c2939189ed3cAuthor: Tom Lane <tgl@sss.pgh.pa.us>Date:   Fri May 21 14:03:53 2021 -0400    Restore the portal-level snapshot after procedure COMMIT/ROLLBACK. Cheers", "msg_date": "Fri, 30 Jul 2021 05:12:53 -0700", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: Segment fault when excuting SPI function On PG with commit\n 41c6a5be" }, { "msg_contents": "Em sex., 30 de jul. de 2021 às 05:57, liuhuailing@fujitsu.com <\nliuhuailing@fujitsu.com> escreveu:\n\n> Hi, all\n>\n> When I used SPI_execute_plan function on PG12 which commit 41c6a5be is\n> used,\n> Segment fault occurred.\n>\n> PS: If commit 41c6a5be is not used, this phenomenon will not happen.\n>\n> Reproduce:\n> In a background process, the following steps are executed.\n> --------------------------\n> StartTransactionCommand();\n> SPI_connect();\n> plan = SPI_prepare(query,0,NULL); ★the query is a SELECT SQL.\n> SPI_keepplan(plan);\n> SPI_finish();\n> CommitTransactionCommand();\n> StartTransactionCommand();\n> SPI_connect();\n> SPI_execute_plan(plan, NULL, NULL, true, 0); ★Segment fault\n> --------------------------\n>\n> Core stack:\n> Stack trace of thread 43926:\n> #0 0x0000000000772f19 EnsurePortalSnapshotExists\n> (postgres)\n> #1 0x000000000064f85c _SPI_execute_plan (postgres)\n> #2 0x000000000064fbd1 SPI_execute_plan (postgres)\n> #3 0x00007fbee784402e xxx (xxx.so)\n> #4 0x00007fbee78424ae xxxx (xxxx.so)\n> #5 0x00000000006e91f5 StartBackgroundWorker (postgres)\n> #6 0x00000000006f5e25 maybe_start_bgworkers (postgres)\n> #7 0x00000000006f6121 reaper (postgres)\n> #8 0x00007fbeedf48dc0 __restore_rt (libpthread.so.0)\n> #9 0x00007fbeebadf75b __select (libc.so.6)\n> #10 0x00000000006f6ea6 ServerLoop (postgres)\n> #11 0x00000000006f8c30 PostmasterMain (postgres)\n> #12 0x0000000000485d99 main (postgres)\n> #13 0x00007fbeeba0f873 __libc_start_main (libc.so.6)\n> #14 0x0000000000485e3e _start (postgres)\n>\n> Is there a bug in the commit 41c6a5be? Please confirm it.\n>\nDid you test it on the HEAD too?\n\nregards,\nRanier Vilela\n\nEm sex., 30 de jul. de 2021 às 05:57, liuhuailing@fujitsu.com <liuhuailing@fujitsu.com> escreveu:Hi, all\n\nWhen I used SPI_execute_plan function on PG12 which commit 41c6a5be is used,\nSegment fault occurred.\n\nPS: If commit 41c6a5be is not used, this phenomenon will not happen. \n\nReproduce:\nIn a background process, the following steps are executed.\n--------------------------\nStartTransactionCommand();\nSPI_connect();       \nplan = SPI_prepare(query,0,NULL); ★the query is a SELECT SQL. \nSPI_keepplan(plan);         \nSPI_finish();           \nCommitTransactionCommand();   \nStartTransactionCommand();    \nSPI_connect();\nSPI_execute_plan(plan, NULL, NULL, true, 0); ★Segment fault\n--------------------------\n\nCore stack:\nStack trace of thread 43926:\n                #0  0x0000000000772f19 EnsurePortalSnapshotExists (postgres)\n                #1  0x000000000064f85c _SPI_execute_plan (postgres)\n                #2  0x000000000064fbd1 SPI_execute_plan (postgres)\n                #3  0x00007fbee784402e xxx (xxx.so)\n                #4  0x00007fbee78424ae xxxx (xxxx.so)\n                #5  0x00000000006e91f5 StartBackgroundWorker (postgres)\n                #6  0x00000000006f5e25 maybe_start_bgworkers (postgres)\n                #7  0x00000000006f6121 reaper (postgres)\n                #8  0x00007fbeedf48dc0 __restore_rt (libpthread.so.0)\n                #9  0x00007fbeebadf75b __select (libc.so.6)\n                #10 0x00000000006f6ea6 ServerLoop (postgres)\n                #11 0x00000000006f8c30 PostmasterMain (postgres)\n                #12 0x0000000000485d99 main (postgres)\n                #13 0x00007fbeeba0f873 __libc_start_main (libc.so.6)\n                #14 0x0000000000485e3e _start (postgres)\n\nIs there a bug in the commit 41c6a5be?  Please confirm it.Did you test it on the HEAD too?regards,Ranier Vilela", "msg_date": "Fri, 30 Jul 2021 09:14:02 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Segment fault when excuting SPI function On PG with commit\n 41c6a5be" }, { "msg_contents": "On Fri, Jul 30, 2021 at 08:57:35AM +0000, liuhuailing@fujitsu.com wrote:\n> When I used SPI_execute_plan function on PG12 which commit 41c6a5be is used,\n> Segment fault occurred.\n> \n> PS: If commit 41c6a5be is not used, this phenomenon will not happen. \n\nI see nothing wrong in this commit, FWIW.\n\n> Reproduce:\n> In a background process, the following steps are executed.\n> --------------------------\n> StartTransactionCommand();\n> SPI_connect();       \n> plan = SPI_prepare(query,0,NULL); ★the query is a SELECT SQL. \n> SPI_keepplan(plan);         \n> SPI_finish();           \n> CommitTransactionCommand();   \n> StartTransactionCommand();    \n> SPI_connect();\n> SPI_execute_plan(plan, NULL, NULL, true, 0); ★Segment fault\n> --------------------------\n\nBut I see an issue with your code. It seems to me that you should\npush a snapshot before doing SPI_prepare() and SPI_execute_plan(),\nas of:\nPushActiveSnapshot(GetTransactionSnapshot()); \n--\nMichael", "msg_date": "Fri, 30 Jul 2021 21:38:01 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Segment fault when excuting SPI function On PG with commit\n 41c6a5be" }, { "msg_contents": "Michael Paquier <michael@paquier.xyz> writes:\n> On Fri, Jul 30, 2021 at 08:57:35AM +0000, liuhuailing@fujitsu.com wrote:\n>> When I used SPI_execute_plan function on PG12 which commit 41c6a5be is used,\n>> Segment fault occurred.\n\n> I see nothing wrong in this commit, FWIW.\n> But I see an issue with your code. It seems to me that you should\n> push a snapshot before doing SPI_prepare() and SPI_execute_plan(),\n> as of:\n> PushActiveSnapshot(GetTransactionSnapshot()); \n\nYes. What that commit did was to formalize the requirement that\na snapshot exist *before* entering SPI. Before that, you might\nhave gotten away without one, depending on what you were trying\nto do (in particular, detoasting a toasted output Datum would\nfail if you lack an external snapshot).\n\nThis isn't the first complaint we've seen from somebody whose\ncode used to work and now fails there, however. I wonder if\nwe should convert the Assert into an actual test-and-elog, say\n\n\t/* Otherwise, we'd better have an active Portal */\n\tportal = ActivePortal;\n-\tAssert(portal != NULL);\n+\tif (unlikely(portal == NULL))\n+\t\telog(ERROR, \"must have an outer snapshot or portal\");\n\tAssert(portal->portalSnapshot == NULL);\n\nPerhaps that would help people to realize that the bug is theirs\nnot EnsurePortalSnapshotExists's.\n\nI gather BTW that the OP is trying to test C code in a non-assert\nbuild. Not a great approach.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 30 Jul 2021 11:06:27 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Segment fault when excuting SPI function On PG with commit\n 41c6a5be" }, { "msg_contents": "> On 30 Jul 2021, at 17:06, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> I wonder if we should convert the Assert into an actual test-and-elog, say\n> \n> \t/* Otherwise, we'd better have an active Portal */\n> \tportal = ActivePortal;\n> -\tAssert(portal != NULL);\n> +\tif (unlikely(portal == NULL))\n> +\t\telog(ERROR, \"must have an outer snapshot or portal\");\n> \tAssert(portal->portalSnapshot == NULL);\n> \n> Perhaps that would help people to realize that the bug is theirs\n> not EnsurePortalSnapshotExists's.\n\n+1, that would probably be quite helpful.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Fri, 30 Jul 2021 17:10:30 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Segment fault when excuting SPI function On PG with commit\n 41c6a5be" }, { "msg_contents": "Daniel Gustafsson <daniel@yesql.se> writes:\n>> On 30 Jul 2021, at 17:06, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> I wonder if we should convert the Assert into an actual test-and-elog, say\n>> \n>> \t/* Otherwise, we'd better have an active Portal */\n>> \tportal = ActivePortal;\n>> -\tAssert(portal != NULL);\n>> +\tif (unlikely(portal == NULL))\n>> +\t\telog(ERROR, \"must have an outer snapshot or portal\");\n>> \tAssert(portal->portalSnapshot == NULL);\n>> \n>> Perhaps that would help people to realize that the bug is theirs\n>> not EnsurePortalSnapshotExists's.\n\n> +1, that would probably be quite helpful.\n\nHappy to make it so. Anyone have suggestions about the wording of\nthe message?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 30 Jul 2021 11:22:43 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Segment fault when excuting SPI function On PG with commit\n 41c6a5be" }, { "msg_contents": "On Fri, Jul 30, 2021 at 11:22:43AM -0400, Tom Lane wrote:\n> Happy to make it so. Anyone have suggestions about the wording of\n> the message?\n\nFor the archives, this has been applied as of ef12f32, and the new\nmessage seems explicit enough:\n+ if (unlikely(portal == NULL))\n+ elog(ERROR, \"cannot execute SQL without an outer snapshot or portal\");\n--\nMichael", "msg_date": "Tue, 10 Aug 2021 16:09:11 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Segment fault when excuting SPI function On PG with commit\n 41c6a5be" } ]
[ { "msg_contents": "Hi,\n\nWhen reviewing logicalreplication related patches, I noticed the function\nparam ReorderBufferTXN *txn not used in the function maybe_send_schema(). Since\nthis is not an external function, I think it might be better to remove the unused paramater.\n\nBest regards,\nHouzj", "msg_date": "Fri, 30 Jul 2021 13:27:23 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "param 'txn' not used in function maybe_send_schema()" }, { "msg_contents": "\n\nOn 2021/07/30 22:27, houzj.fnst@fujitsu.com wrote:\n> Hi,\n> \n> When reviewing logicalreplication related patches, I noticed the function\n> param ReorderBufferTXN *txn not used in the function maybe_send_schema(). Since\n> this is not an external function, I think it might be better to remove the unused paramater.\n\n+1\n\nSeems commit 464824323e accidentally added the argument though\nit's not used in maybe_send_schema(). I *guess* that it was used\nin the patches in dev early stage, but it's changed so that no longer used\nwhile it's being reviewed. But maybe we forgot to remove it.\n\nBarring any objection, 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": "Sat, 31 Jul 2021 10:08:03 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: param 'txn' not used in function maybe_send_schema()" }, { "msg_contents": "\n\nOn 2021/07/31 10:08, Fujii Masao wrote:\n> Barring any objection, 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": "Thu, 5 Aug 2021 17:51:25 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: param 'txn' not used in function maybe_send_schema()" } ]
[ { "msg_contents": "Hi,\n\nSince\n\ncommit 960869da0803427d14335bba24393f414b476e2c\nAuthor: Magnus Hagander <magnus@hagander.net>\nDate: 2021-01-17 13:34:09 +0100\n\n Add pg_stat_database counters for sessions and session time\n\npgstat_report_stat() does another timestamp computation via\npgstat_send_connstats(), despite typically having computed one just a few\nlines before.\n\nGiven that timestamp computation isn't all that cheap, that's not great. Even\nmore, that additional timestamp computation makes things *less* accurate:\n\nvoid\npgstat_report_stat(bool disconnect)\n...\n\t/*\n\t * Don't send a message unless it's been at least PGSTAT_STAT_INTERVAL\n\t * msec since we last sent one, or the backend is about to exit.\n\t */\n\tnow = GetCurrentTransactionStopTimestamp();\n\tif (!disconnect &&\n\t\t!TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))\n\t\treturn;\n\n\t/* for backends, send connection statistics */\n\tif (MyBackendType == B_BACKEND)\n\t\tpgstat_send_connstats(disconnect, last_report);\n\n\tlast_report = now;\n\nand then pgstat_send_connstats() does:\n\t/* session time since the last report */\n\tTimestampDifference(((last_report == 0) ? MyStartTimestamp : last_report),\n\t\t\t\t\t\tGetCurrentTimestamp(),\n\t\t\t\t\t\t&secs, &usecs);\n\tmsg.m_session_time = secs * 1000000 + usecs;\n\nWe maintain last_report as GetCurrentTransactionStopTimestamp(), but then use\na separate timestamp in pgstat_send_connstats() to compute the difference from\nlast_report, which is then set to GetCurrentTransactionStopTimestamp()'s\nreturn value.\n\n\nI'm also not all that happy with sending yet another UDP packet for this. This\ndoubles the UDP packets to the stats collector in the common cases (unless\nmore than TABSTAT_QUANTUM tables have stats to report, or shared tables have\nbeen accessed). We already send plenty of \"summary\" information via\nPgStat_MsgTabstat, one of which is sent unconditionally, why do we need a\nseparate message for connection stats?\n\n\nAlternatively we could just not send an update to connection stats every 500ms\nfor every active connection, but only do so at connection end. The database\nstats would only contain stats for disconnected sessions, while the stats for\n\"live\" connections are maintained via backend_status.c. That'd give us *more*\ninformation for less costs, because we then could see idle/active times for\nindividual connections.\n\nThat'd likely be more change than what we would want to do at this point in\nthe release cycle though. But I think we ought to do something about the\nincreased overhead...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sun, 1 Aug 2021 13:55:01 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "On Sun, 2021-08-01 at 13:55 -0700, Andres Freund wrote:\n> Since\n> \n> commit 960869da0803427d14335bba24393f414b476e2c\n> Author: Magnus Hagander <magnus@hagander.net>\n> Date: 2021-01-17 13:34:09 +0100\n> \n> Add pg_stat_database counters for sessions and session time\n> \n> pgstat_report_stat() does another timestamp computation via\n> pgstat_send_connstats(), despite typically having computed one just a few\n> lines before.\n> \n> Given that timestamp computation isn't all that cheap, that's not great. Even\n> more, that additional timestamp computation makes things *less* accurate:\n> \n> void\n> pgstat_report_stat(bool disconnect)\n> ...\n> \t/*\n> \t * Don't send a message unless it's been at least PGSTAT_STAT_INTERVAL\n> \t * msec since we last sent one, or the backend is about to exit.\n> \t */\n> \tnow = GetCurrentTransactionStopTimestamp();\n> \tif (!disconnect &&\n> \t\t!TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))\n> \t\treturn;\n> \n> \t/* for backends, send connection statistics */\n> \tif (MyBackendType == B_BACKEND)\n> \t\tpgstat_send_connstats(disconnect, last_report);\n> \n> \tlast_report = now;\n> \n> and then pgstat_send_connstats() does:\n> \t/* session time since the last report */\n> \tTimestampDifference(((last_report == 0) ? MyStartTimestamp : last_report),\n> \t\t\t\t\t\tGetCurrentTimestamp(),\n> \t\t\t\t\t\t&secs, &usecs);\n> \tmsg.m_session_time = secs * 1000000 + usecs;\n> \n> We maintain last_report as GetCurrentTransactionStopTimestamp(), but then use\n> a separate timestamp in pgstat_send_connstats() to compute the difference from\n> last_report, which is then set to GetCurrentTransactionStopTimestamp()'s\n> return value.\n\nMakes sense to me. How about passing \"now\", which was just initialized from\nGetCurrentTransactionStopTimestamp(), as additional parameter to\npgstat_send_connstats() and use that value instead of taking the current time?\n\n> I'm also not all that happy with sending yet another UDP packet for this. This\n> doubles the UDP packets to the stats collector in the common cases (unless\n> more than TABSTAT_QUANTUM tables have stats to report, or shared tables have\n> been accessed). We already send plenty of \"summary\" information via\n> PgStat_MsgTabstat, one of which is sent unconditionally, why do we need a\n> separate message for connection stats?\n\nAre you suggesting that connection statistics should be shoehorned into\nsome other statistics message? That would reduce the number of UDP packets,\nbut it sounds ugly and confusing to me.\n\n> Alternatively we could just not send an update to connection stats every 500ms\n> for every active connection, but only do so at connection end. The database\n> stats would only contain stats for disconnected sessions, while the stats for\n> \"live\" connections are maintained via backend_status.c. That'd give us *more*\n> information for less costs, because we then could see idle/active times for\n> individual connections.\n\nThat was my original take, but if I remember right, Magnus convinced me that\nit would be more useful to have statistics for open sessions as well.\nWith a connection pool, connections can stay open for a very long time,\nand the accuracy and usefulness of the statistics would become questionable.\n\n> That'd likely be more change than what we would want to do at this point in\n> the release cycle though. But I think we ought to do something about the\n> increased overhead...\n\nIf you are talking about the extra GetCurrentTimestamp() call, and my first\nsuggestion is acceptable, that should be simple.\n\nYours,\nLaurenz Albe\n\n\n\n", "msg_date": "Tue, 17 Aug 2021 10:44:51 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "Hi,\n\nOn 2021-08-17 10:44:51 +0200, Laurenz Albe wrote:\n> On Sun, 2021-08-01 at 13:55 -0700, Andres Freund wrote:\n> > We maintain last_report as GetCurrentTransactionStopTimestamp(), but then use\n> > a separate timestamp in pgstat_send_connstats() to compute the difference from\n> > last_report, which is then set to GetCurrentTransactionStopTimestamp()'s\n> > return value.\n> \n> Makes sense to me. How about passing \"now\", which was just initialized from\n> GetCurrentTransactionStopTimestamp(), as additional parameter to\n> pgstat_send_connstats() and use that value instead of taking the current time?\n\nYes.\n\n\n> > I'm also not all that happy with sending yet another UDP packet for this. This\n> > doubles the UDP packets to the stats collector in the common cases (unless\n> > more than TABSTAT_QUANTUM tables have stats to report, or shared tables have\n> > been accessed). We already send plenty of \"summary\" information via\n> > PgStat_MsgTabstat, one of which is sent unconditionally, why do we need a\n> > separate message for connection stats?\n> \n> Are you suggesting that connection statistics should be shoehorned into\n> some other statistics message? That would reduce the number of UDP packets,\n> but it sounds ugly and confusing to me.\n\nThat ship already has sailed. Look at struct PgStat_MsgTabstat\n\ntypedef struct PgStat_MsgTabstat\n{\n\tPgStat_MsgHdr m_hdr;\n\tOid\t\t\tm_databaseid;\n\tint\t\t\tm_nentries;\n\tint\t\t\tm_xact_commit;\n\tint\t\t\tm_xact_rollback;\n\tPgStat_Counter m_block_read_time;\t/* times in microseconds */\n\tPgStat_Counter m_block_write_time;\n\tPgStat_TableEntry m_entry[PGSTAT_NUM_TABENTRIES];\n} PgStat_MsgTabstat;\n\nGiven that we transport number of commits/commits, block read/write time\nadding the time the connection was active/inactive doesn't really seem like it\nmakes things meaningfully worse?\n\n\n> > Alternatively we could just not send an update to connection stats every 500ms\n> > for every active connection, but only do so at connection end. The database\n> > stats would only contain stats for disconnected sessions, while the stats for\n> > \"live\" connections are maintained via backend_status.c. That'd give us *more*\n> > information for less costs, because we then could see idle/active times for\n> > individual connections.\n> \n> That was my original take, but if I remember right, Magnus convinced me that\n> it would be more useful to have statistics for open sessions as well.\n> With a connection pool, connections can stay open for a very long time,\n> and the accuracy and usefulness of the statistics would become questionable.\n\nThat's not a contradiction to what I propose. Having the data available via\nbackend_status.c allows to sum up the data for active connections and the data\nfor past connections.\n\nI think it's also just cleaner to not constantly report changing preliminary\ndata as pgstat_send_connstats() does.\n\n\n> > That'd likely be more change than what we would want to do at this point in\n> > the release cycle though. But I think we ought to do something about the\n> > increased overhead...\n> \n> If you are talking about the extra GetCurrentTimestamp() call, and my first\n> suggestion is acceptable, that should be simple.\n\nDoubling the number of UDP messages in common workloads seems also problematic\nenough that it should be addressed for 14. It increases the likelihood of\ndropping stats messages on busy systems, which can have downstream impacts.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 17 Aug 2021 02:14:20 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "On Tue, 2021-08-17 at 02:14 -0700, Andres Freund wrote:\n> On 2021-08-17 10:44:51 +0200, Laurenz Albe wrote:\n> > On Sun, 2021-08-01 at 13:55 -0700, Andres Freund wrote:\n> > > We maintain last_report as GetCurrentTransactionStopTimestamp(), but then use\n> > > a separate timestamp in pgstat_send_connstats() to compute the difference from\n> > > last_report, which is then set to GetCurrentTransactionStopTimestamp()'s\n> > > return value.\n> > \n> > Makes sense to me. How about passing \"now\", which was just initialized from\n> > GetCurrentTransactionStopTimestamp(), as additional parameter to\n> > pgstat_send_connstats() and use that value instead of taking the current time?\n> \n> Yes.\n\nHere is a patch for that.\n\n> > > I'm also not all that happy with sending yet another UDP packet for this.\n> > \n> > Are you suggesting that connection statistics should be shoehorned into\n> > some other statistics message? That would reduce the number of UDP packets,\n> > but it sounds ugly and confusing to me.\n> \n> That ship already has sailed. Look at struct PgStat_MsgTabstat\n> \n> Given that we transport number of commits/commits, block read/write time\n> adding the time the connection was active/inactive doesn't really seem like it\n> makes things meaningfully worse?\n\nPoint taken.\n\nI looked at the other statistics sent in pgstat_report_stat(), and I see\nnone that are sent unconditionally. Are you thinking of this:\n\n /*\n * Send partial messages. Make sure that any pending xact commit/abort\n * gets counted, even if there are no table stats to send.\n */\n if (regular_msg.m_nentries > 0 ||\n pgStatXactCommit > 0 || pgStatXactRollback > 0)\n pgstat_send_tabstat(&regular_msg);\n if (shared_msg.m_nentries > 0)\n pgstat_send_tabstat(&shared_msg);\n\nI can't think of a way to hack this up that wouldn't make my stomach turn.\n\n> > > Alternatively we could just not send an update to connection stats every 500ms\n> > > for every active connection, but only do so at connection end. The database\n> > > stats would only contain stats for disconnected sessions, while the stats for\n> > > \"live\" connections are maintained via backend_status.c.\n> > \n> > That was my original take, but if I remember right, Magnus convinced me that\n> > it would be more useful to have statistics for open sessions as well.\n> > With a connection pool, connections can stay open for a very long time,\n> > and the accuracy and usefulness of the statistics would become questionable.\n> \n> That's not a contradiction to what I propose. Having the data available via\n> backend_status.c allows to sum up the data for active connections and the data\n> for past connections.\n> \n> I think it's also just cleaner to not constantly report changing preliminary\n> data as pgstat_send_connstats() does.\n\nCurrently, the data are kept in static variables in the backend process.\nThat would have to change for such an approach, right?\n\n> Doubling the number of UDP messages in common workloads seems also problematic\n> enough that it should be addressed for 14.\n\nOk, but I don't know how to go about it.\n\nYours,\nLaurenz Albe", "msg_date": "Wed, 18 Aug 2021 05:16:38 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "On Tue, Aug 17, 2021 at 02:14:20AM -0700, Andres Freund wrote:\n> Doubling the number of UDP messages in common workloads seems also problematic\n> enough that it should be addressed for 14. It increases the likelihood of\n> dropping stats messages on busy systems, which can have downstream impacts.\n\nI think by \"common workloads\" you mean one with many, shortlived sessions.\n\nThat does sounds like a concern, and I added this as an Opened Item.\n\n-- \nJustin\n\n\n", "msg_date": "Fri, 20 Aug 2021 14:27:20 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "At Wed, 18 Aug 2021 05:16:38 +0200, Laurenz Albe <laurenz.albe@cybertec.at> wrote in \n> On Tue, 2021-08-17 at 02:14 -0700, Andres Freund wrote:\n> > On 2021-08-17 10:44:51 +0200, Laurenz Albe wrote:\n> > > On Sun, 2021-08-01 at 13:55 -0700, Andres Freund wrote:\n> > > > We maintain last_report as GetCurrentTransactionStopTimestamp(), but then use\n> > > > a separate timestamp in pgstat_send_connstats() to compute the difference from\n> > > > last_report, which is then set to GetCurrentTransactionStopTimestamp()'s\n> > > > return value.\n> > > \n> > > Makes sense to me. How about passing \"now\", which was just initialized from\n> > > GetCurrentTransactionStopTimestamp(), as additional parameter to\n> > > pgstat_send_connstats() and use that value instead of taking the current time?\n> > \n> > Yes.\n> \n> Here is a patch for that.\n\nFWIW, looks good to me.\n\n> > > > I'm also not all that happy with sending yet another UDP packet for this.\n> > > \n> > > Are you suggesting that connection statistics should be shoehorned into\n> > > some other statistics message? That would reduce the number of UDP packets,\n> > > but it sounds ugly and confusing to me.\n> > \n> > That ship already has sailed. Look at struct PgStat_MsgTabstat\n> > \n> > Given that we transport number of commits/commits, block read/write time\n> > adding the time the connection was active/inactive doesn't really seem like it\n> > makes things meaningfully worse?\n> \n> Point taken.\n> \n> I looked at the other statistics sent in pgstat_report_stat(), and I see\n> none that are sent unconditionally. Are you thinking of this:\n\nIIUC, that means that pg_stat_report sends at least one\nPgStat_MsgTabstat struct for the database stats purpose if any stats\nare sent. So the connection stats can piggy-back on the packet.\n\n> /*\n> * Send partial messages. Make sure that any pending xact commit/abort\n> * gets counted, even if there are no table stats to send.\n> */\n> if (regular_msg.m_nentries > 0 ||\n> pgStatXactCommit > 0 || pgStatXactRollback > 0)\n> pgstat_send_tabstat(&regular_msg);\n> if (shared_msg.m_nentries > 0)\n> pgstat_send_tabstat(&shared_msg);\n> \n> I can't think of a way to hack this up that wouldn't make my stomach turn.\n\nNo need to change the condition. It's sufficient that the connection\nstats are sent at the same time with transaction stats are sent.\n\n> > > > Alternatively we could just not send an update to connection stats every 500ms\n> > > > for every active connection, but only do so at connection end. The database\n> > > > stats would only contain stats for disconnected sessions, while the stats for\n> > > > \"live\" connections are maintained via backend_status.c.\n> > > \n> > > That was my original take, but if I remember right, Magnus convinced me that\n> > > it would be more useful to have statistics for open sessions as well.\n> > > With a connection pool, connections can stay open for a very long time,\n> > > and the accuracy and usefulness of the statistics would become questionable.\n> > \n> > That's not a contradiction to what I propose. Having the data available via\n> > backend_status.c allows to sum up the data for active connections and the data\n> > for past connections.\n> > \n> > I think it's also just cleaner to not constantly report changing preliminary\n> > data as pgstat_send_connstats() does.\n> \n> Currently, the data are kept in static variables in the backend process.\n> That would have to change for such an approach, right?\n\nTotal session time can be summarized from beentry any time, but I'm\nnot sure how we can summarize active/idle time.. Anyway it's not\nneeded if the attached works.\n\n> > Doubling the number of UDP messages in common workloads seems also problematic\n> > enough that it should be addressed for 14.\n> \n> Ok, but I don't know how to go about it.\n\nThe attached is a heavy-WIP on:\n\n- remove redundant gettimeofday().\n- avoid sending dedicate UCP packet for connection stats.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Tue, 24 Aug 2021 15:12:28 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "On Tue, 2021-08-24 at 15:12 +0900, Kyotaro Horiguchi wrote:\n> At Wed, 18 Aug 2021 05:16:38 +0200, Laurenz Albe <laurenz.albe@cybertec.at> wrote in \n> > On Tue, 2021-08-17 at 02:14 -0700, Andres Freund wrote:\n> > > > > I'm also not all that happy with sending yet another UDP packet for this.\n> > > > \n> > > > Are you suggesting that connection statistics should be shoehorned into\n> > > > some other statistics message?  That would reduce the number of UDP packets,\n> > > > but it sounds ugly and confusing to me.\n> > > \n> > > That ship already has sailed. Look at struct PgStat_MsgTabstat\n> > > \n> > > Given that we transport number of commits/commits, block read/write time\n> > > adding the time the connection was active/inactive doesn't really seem like it\n> > > makes things meaningfully worse?\n> > \n> > Point taken.\n> > \n> > I looked at the other statistics sent in pgstat_report_stat(), and I see\n> > none that are sent unconditionally.\n> \n> IIUC, that means that pg_stat_report sends at least one\n> PgStat_MsgTabstat struct for the database stats purpose if any stats\n> are sent.  So the connection stats can piggy-back on the packet.\n> \n> No need to change the condition. It's sufficient that the connection\n> stats are sent at the same time with transaction stats are sent.\n\n> > > Doubling the number of UDP messages in common workloads seems also problematicenough that it should be addressed for 14.\n> > \n> > Ok, but I don't know how to go about it.\n> \n> The attached is a heavy-WIP on:\n> \n> - remove redundant gettimeofday().\n> - avoid sending dedicate UCP packet for connection stats.\n\nThank you.\n\nPerhaps I misread that, but doesn't that mean that the session statistics\ncould be sent several times? \"pgstat_send_tabstat()\" could be called more than\nonce, right?\n\nYours,\nLaurenz Albe\n\n\n\n", "msg_date": "Tue, 24 Aug 2021 12:34:25 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "At Tue, 24 Aug 2021 12:34:25 +0200, Laurenz Albe <laurenz.albe@cybertec.at> wrote in \n> On Tue, 2021-08-24 at 15:12 +0900, Kyotaro Horiguchi wrote:\n> > \n> > - remove redundant gettimeofday().\n> > - avoid sending dedicate UCP packet for connection stats.\n> \n> Thank you.\n> \n> Perhaps I misread that, but doesn't that mean that the session statistics\n> could be sent several times? \"pgstat_send_tabstat()\" could be called more than\n> once, right?\n\nYes, it can be called two or more times for a call to\npgstat_report_stat, but the patch causes only the first of them convey\neffective connection stats numbers. This is the same way as how\ntransaction stats are treated. If no table activities have taken\nplace at all, pgStatXactCommit/Rollback are not consumed then the\nfollowing condition:\n\n>\t/*\n>\t * Send partial messages. Make sure that any pending xact commit/abort\n>\t * gets counted, even if there are no table stats to send.\n>\t */\n>\tif (regular_msg.m_nentries > 0 ||\n>\t\tpgStatXactCommit > 0 || pgStatXactRollback > 0)\n\nleads to a call to pgstat_send_tabstat() and it sends a tabstat\nmessage without a table stats, which is a \"partial message\".\n\nIn this logic the condition term (pgStatXactCommit > 0 ||\npgStatXactRollback > 0) acts as a single-shot trigger.\n\nSo we can piggy-back on the condition to send something only once.\n\nThe patch sets \"0\" = (DISCONNECT_NOT_YET) to m_disconnect as the\n\"not-effective\" number, but it would be better to add\nDISCONNECT_something to express that state.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Wed, 25 Aug 2021 10:12:41 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "On Wed, Aug 25, 2021 at 10:12:41AM +0900, Kyotaro Horiguchi wrote:\n> Yes, it can be called two or more times for a call to\n> pgstat_report_stat, but the patch causes only the first of them convey\n> effective connection stats numbers. This is the same way as how\n> transaction stats are treated. If no table activities have taken\n> place at all, pgStatXactCommit/Rollback are not consumed then the\n> following condition:\n\nI was looking at this WIP patch, and plugging in the connection\nstatistics to the table-access statistics looks like the wrong\nabstraction to me. I find much cleaner the approach of HEAD to use a\nseparate API to report this information, as of\npgstat_send_connstats().\n\nAs of the two problems discussed on this thread, aka the increased\nnumber of UDP packages and the extra timestamp computations, it seems\nto me that we had better combine the following ideas for HEAD and 14,\nfor now:\n- Avoid the extra timestamp computation as proposed by Laurenz in [1]\n- Throttle the frequency where the connection stat packages are sent,\nas of [2].\n\nMagnus, this open item is assigned to you as the committer of\n960869d. Could you comment on those issues?\n\n[1]: https://www.postgresql.org/message-id/4095ceb328780d1bdba77ac6d9785fd7577ed047.camel@cybertec.at\n[2]: https://www.postgresql.org/message-id/20210801205501.nyxzxoelqoo4x2qc@alap3.anarazel.de\n--\nMichael", "msg_date": "Wed, 25 Aug 2021 12:51:58 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "At Wed, 25 Aug 2021 12:51:58 +0900, Michael Paquier <michael@paquier.xyz> wrote in \n> On Wed, Aug 25, 2021 at 10:12:41AM +0900, Kyotaro Horiguchi wrote:\n> > Yes, it can be called two or more times for a call to\n> > pgstat_report_stat, but the patch causes only the first of them convey\n> > effective connection stats numbers. This is the same way as how\n> > transaction stats are treated. If no table activities have taken\n> > place at all, pgStatXactCommit/Rollback are not consumed then the\n> > following condition:\n> \n> I was looking at this WIP patch, and plugging in the connection\n> statistics to the table-access statistics looks like the wrong\n> abstraction to me. I find much cleaner the approach of HEAD to use a\n> separate API to report this information, as of\n> pgstat_send_connstats().\n> \n> As of the two problems discussed on this thread, aka the increased\n> number of UDP packages and the extra timestamp computations, it seems\n> to me that we had better combine the following ideas for HEAD and 14,\n> for now:\n> - Avoid the extra timestamp computation as proposed by Laurenz in [1]\n> - Throttle the frequency where the connection stat packages are sent,\n> as of [2].\n> \n> Magnus, this open item is assigned to you as the committer of\n> 960869d. Could you comment on those issues?\n> \n> [1]: https://www.postgresql.org/message-id/4095ceb328780d1bdba77ac6d9785fd7577ed047.camel@cybertec.at\n> [2]: https://www.postgresql.org/message-id/20210801205501.nyxzxoelqoo4x2qc@alap3.anarazel.de\n\nAbout [2], we need to maintain session active/idel times on additional\nmenbers in backend status. Letting gpgstat_report_activity to\ndirectly scribble on backend status array would work?\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Wed, 25 Aug 2021 13:21:52 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "At Wed, 25 Aug 2021 13:21:52 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> At Wed, 25 Aug 2021 12:51:58 +0900, Michael Paquier <michael@paquier.xyz> wrote in \n> > - Throttle the frequency where the connection stat packages are sent,\n> > as of [2].\n> > \n> > Magnus, this open item is assigned to you as the committer of\n> > 960869d. Could you comment on those issues?\n> > \n> > [1]: https://www.postgresql.org/message-id/4095ceb328780d1bdba77ac6d9785fd7577ed047.camel@cybertec.at\n> > [2]: https://www.postgresql.org/message-id/20210801205501.nyxzxoelqoo4x2qc@alap3.anarazel.de\n> \n> About [2], we need to maintain session active/idel times on additional\n> menbers in backend status. Letting gpgstat_report_activity to\n> directly scribble on backend status array would work?\n\nSo the attached is roughly that (just a PoC, of course).\n\n- accumulate active and idle time on backend status array.\n (pgstat_report_activity)\n\n- pgstat_get_db_session_time() and friends read pgstat file then sum\n up relevant members in backend status array. (So it scans on the\n array for every number of every database X().\n\n- The function pgstat_send_connstats is called only at the end of a\n connection. It reads backend status element then send the numbers\n to stats collector. pgstat_shutdown_hook needs to be moved from\n on_shmem_exit to before_shmem_exit to read MyBEEntry.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\ndiff --git a/src/backend/postmaster/pgstat.c b/src/backend/postmaster/pgstat.c\nindex 7fcc3f6ded..47973f1e30 100644\n--- a/src/backend/postmaster/pgstat.c\n+++ b/src/backend/postmaster/pgstat.c\n@@ -244,8 +244,6 @@ static int\tpgStatXactCommit = 0;\n static int\tpgStatXactRollback = 0;\n PgStat_Counter pgStatBlockReadTime = 0;\n PgStat_Counter pgStatBlockWriteTime = 0;\n-PgStat_Counter pgStatActiveTime = 0;\n-PgStat_Counter pgStatTransactionIdleTime = 0;\n SessionEndType pgStatSessionEndCause = DISCONNECT_NORMAL;\n \n /* Record that's written to 2PC state file when pgstat state is persisted */\n@@ -323,7 +321,7 @@ static void pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg);\n static void pgstat_send_funcstats(void);\n static void pgstat_send_slru(void);\n static HTAB *pgstat_collect_oids(Oid catalogid, AttrNumber anum_oid);\n-static void pgstat_send_connstats(bool disconnect, TimestampTz last_report);\n+static void pgstat_send_connstats(TimestampTz now);\n \n static PgStat_TableStatus *get_tabstat_entry(Oid rel_id, bool isshared);\n \n@@ -876,10 +874,8 @@ pgstat_report_stat(bool disconnect)\n \t\treturn;\n \n \t/* for backends, send connection statistics */\n-\tif (MyBackendType == B_BACKEND)\n-\t\tpgstat_send_connstats(disconnect, last_report);\n-\n-\tlast_report = now;\n+\tif (MyBackendType == B_BACKEND && disconnect)\n+\t\tpgstat_send_connstats(now);\n \n \t/*\n \t * Destroy pgStatTabHash before we start invalidating PgStat_TableEntry\n@@ -1368,39 +1364,41 @@ pgstat_drop_relation(Oid relid)\n * pgstat_send_connstats() -\n *\n *\tTell the collector about session statistics.\n- *\tThe parameter \"disconnect\" will be true when the backend exits.\n- *\t\"last_report\" is the last time we were called (0 if never).\n * ----------\n */\n static void\n-pgstat_send_connstats(bool disconnect, TimestampTz last_report)\n+pgstat_send_connstats(TimestampTz now)\n {\n \tPgStat_MsgConn msg;\n-\tlong\t\tsecs;\n-\tint\t\t\tusecs;\n+\tvolatile PgBackendStatus *beentry = MyBEEntry;\n \n \tif (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)\n \t\treturn;\n \n \tpgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_CONNECTION);\n \tmsg.m_databaseid = MyDatabaseId;\n+\tmsg.m_disconnect = pgStatSessionEndCause;\n \n-\t/* session time since the last report */\n-\tTimestampDifference(((last_report == 0) ? MyStartTimestamp : last_report),\n-\t\t\t\t\t\tGetCurrentTimestamp(),\n-\t\t\t\t\t\t&secs, &usecs);\n-\tmsg.m_session_time = secs * 1000000 + usecs;\n+\tmsg.m_count = 1;\n \n-\tmsg.m_disconnect = disconnect ? pgStatSessionEndCause : DISCONNECT_NOT_YET;\n+\tif (pgstat_track_activities && beentry)\n+\t{\n+\t\tmsg.m_session_time =\n+\t\t\t(PgStat_Counter)(now - beentry->st_proc_start_timestamp) * 1000;\n+\t\tmsg.m_active_time = beentry->st_session_active_time;\n+\t\tmsg.m_idle_in_xact_time = beentry->st_session_idle_time;\n \n-\tmsg.m_active_time = pgStatActiveTime;\n-\tpgStatActiveTime = 0;\n-\n-\tmsg.m_idle_in_xact_time = pgStatTransactionIdleTime;\n-\tpgStatTransactionIdleTime = 0;\n-\n-\t/* report a new session only the first time */\n-\tmsg.m_count = (last_report == 0) ? 1 : 0;\n+\t\tPGSTAT_BEGIN_WRITE_ACTIVITY(beentry);\n+\t\tbeentry->st_session_active_time = 0;\n+\t\tbeentry->st_session_idle_time = 0;\n+\t\tPGSTAT_END_WRITE_ACTIVITY(beentry);\n+\t}\n+\telse\n+\t{\n+\t\tmsg.m_session_time = 0;\n+\t\tmsg.m_active_time = 0;\n+\t\tmsg.m_idle_in_xact_time = 0;\n+\t}\n \n \tpgstat_send(&msg, sizeof(PgStat_MsgConn));\n }\n@@ -2877,7 +2875,7 @@ pgstat_initialize(void)\n \tprevWalUsage = pgWalUsage;\n \n \t/* Set up a process-exit hook to clean up */\n-\ton_shmem_exit(pgstat_shutdown_hook, 0);\n+\tbefore_shmem_exit(pgstat_shutdown_hook, 0);\n }\n \n /* ------------------------------------------------------------\ndiff --git a/src/backend/utils/activity/backend_status.c b/src/backend/utils/activity/backend_status.c\nindex e19c4506ef..0f0eecc3b4 100644\n--- a/src/backend/utils/activity/backend_status.c\n+++ b/src/backend/utils/activity/backend_status.c\n@@ -336,6 +336,8 @@ pgstat_bestart(void)\n \tlbeentry.st_activity_start_timestamp = 0;\n \tlbeentry.st_state_start_timestamp = 0;\n \tlbeentry.st_xact_start_timestamp = 0;\n+\tlbeentry.st_session_active_time = 0;\n+\tlbeentry.st_session_idle_time = 0;\n \tlbeentry.st_databaseid = MyDatabaseId;\n \n \t/* We have userid for client-backends, wal-sender and bgworker processes */\n@@ -590,9 +592,9 @@ pgstat_report_activity(BackendState state, const char *cmd_str)\n \n \t\tif (beentry->st_state == STATE_RUNNING ||\n \t\t\tbeentry->st_state == STATE_FASTPATH)\n-\t\t\tpgstat_count_conn_active_time(secs * 1000000 + usecs);\n+\t\t\tbeentry->st_session_active_time += secs * 1000000 + usecs;\n \t\telse\n-\t\t\tpgstat_count_conn_txn_idle_time(secs * 1000000 + usecs);\n+\t\t\tbeentry->st_session_idle_time += secs * 1000000 + usecs;\n \t}\n \n \t/*\ndiff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c\nindex f0e09eae4d..62b60077c1 100644\n--- a/src/backend/utils/adt/pgstatfuncs.c\n+++ b/src/backend/utils/adt/pgstatfuncs.c\n@@ -1635,6 +1635,56 @@ pg_stat_get_db_blk_write_time(PG_FUNCTION_ARGS)\n \tPG_RETURN_FLOAT8(result);\n }\n \n+/* XXXXX */\n+static double\n+_pg_stat_active_session_stats(Oid dbid, int type)\n+{\n+\tint\t\t\tnum_backends = pgstat_fetch_stat_numbackends();\n+\tint\t\t\tcurr_backend;\n+\tTimestampTz\tnow = GetCurrentTimestamp();\n+\tdouble\t\tresult = 0.0;\n+\tint\t\t\tnsessions = 0;\n+\n+\n+\t/* Add session time of active backends */\n+\t/* 1-based index */\n+\tfor (curr_backend = 1; curr_backend <= num_backends; curr_backend++)\n+\t{\n+\t\tLocalPgBackendStatus *local_beentry;\n+\t\tPgBackendStatus *beentry;\n+\n+\t\tlocal_beentry = pgstat_fetch_stat_local_beentry(curr_backend);\n+\t\tif (!local_beentry)\n+\t\t\tcontinue;\n+\n+\t\tbeentry = &local_beentry->backendStatus;\n+\n+\t\tif (beentry->st_databaseid != dbid)\n+\t\t\tcontinue;\n+\n+\t\tswitch (type) /* define enum !*/\n+\t\t{\n+\t\t\tcase 0: /* SESSION TIME */\n+\t\t\t\tresult +=\n+\t\t\t\t\t(double)(now - beentry->st_proc_start_timestamp) / 1000;\n+\t\t\t\tbreak;\n+\t\t\tcase 1: /* SESSION ACTIVE TIME */\n+\t\t\t\tresult += (double)beentry->st_session_active_time / 1000;\n+\t\t\t\tbreak;\n+\t\t\tcase 2: /* SESSION IDLE TIME */\n+\t\t\t\tresult += (double)beentry->st_session_idle_time / 1000;\n+\t\t\t\tbreak;\n+\t\t\tcase 3: /* SESSION NUMBER */\n+\t\t\t\tnsessions++;\n+\t\t}\n+\t}\n+\n+\tif (type < 3)\n+\t\treturn result;\n+\n+\treturn (double)nsessions;\n+}\n+\n Datum\n pg_stat_get_db_session_time(PG_FUNCTION_ARGS)\n {\n@@ -1646,6 +1696,8 @@ pg_stat_get_db_session_time(PG_FUNCTION_ARGS)\n \tif ((dbentry = pgstat_fetch_stat_dbentry(dbid)) != NULL)\n \t\tresult = ((double) dbentry->total_session_time) / 1000.0;\n \n+\tresult += _pg_stat_active_session_stats(dbid, 0);\n+\n \tPG_RETURN_FLOAT8(result);\n }\n \n@@ -1660,6 +1712,8 @@ pg_stat_get_db_active_time(PG_FUNCTION_ARGS)\n \tif ((dbentry = pgstat_fetch_stat_dbentry(dbid)) != NULL)\n \t\tresult = ((double) dbentry->total_active_time) / 1000.0;\n \n+\tresult += _pg_stat_active_session_stats(dbid, 1);\n+\n \tPG_RETURN_FLOAT8(result);\n }\n \n@@ -1674,6 +1728,8 @@ pg_stat_get_db_idle_in_transaction_time(PG_FUNCTION_ARGS)\n \tif ((dbentry = pgstat_fetch_stat_dbentry(dbid)) != NULL)\n \t\tresult = ((double) dbentry->total_idle_in_xact_time) / 1000.0;\n \n+\tresult += _pg_stat_active_session_stats(dbid, 2);\n+\n \tPG_RETURN_FLOAT8(result);\n }\n \n@@ -1687,6 +1743,7 @@ pg_stat_get_db_sessions(PG_FUNCTION_ARGS)\n \tif ((dbentry = pgstat_fetch_stat_dbentry(dbid)) != NULL)\n \t\tresult = (int64) (dbentry->n_sessions);\n \n+\tresult += (int64)_pg_stat_active_session_stats(dbid, 3);\n \tPG_RETURN_INT64(result);\n }\n \ndiff --git a/src/include/pgstat.h b/src/include/pgstat.h\nindex f779b48b8c..9311111690 100644\n--- a/src/include/pgstat.h\n+++ b/src/include/pgstat.h\n@@ -931,13 +931,6 @@ extern PgStat_MsgWal WalStats;\n extern PgStat_Counter pgStatBlockReadTime;\n extern PgStat_Counter pgStatBlockWriteTime;\n \n-/*\n- * Updated by pgstat_count_conn_*_time macros, called by\n- * pgstat_report_activity().\n- */\n-extern PgStat_Counter pgStatActiveTime;\n-extern PgStat_Counter pgStatTransactionIdleTime;\n-\n \n /*\n * Updated by the traffic cop and in errfinish()\n@@ -1039,10 +1032,6 @@ extern void pgstat_initstats(Relation rel);\n \t(pgStatBlockReadTime += (n))\n #define pgstat_count_buffer_write_time(n)\t\t\t\t\t\t\t\\\n \t(pgStatBlockWriteTime += (n))\n-#define pgstat_count_conn_active_time(n)\t\t\t\t\t\t\t\\\n-\t(pgStatActiveTime += (n))\n-#define pgstat_count_conn_txn_idle_time(n)\t\t\t\t\t\t\t\\\n-\t(pgStatTransactionIdleTime += (n))\n \n extern void pgstat_count_heap_insert(Relation rel, PgStat_Counter n);\n extern void pgstat_count_heap_update(Relation rel, bool hot);\ndiff --git a/src/include/utils/backend_status.h b/src/include/utils/backend_status.h\nindex 8042b817df..ebd5755247 100644\n--- a/src/include/utils/backend_status.h\n+++ b/src/include/utils/backend_status.h\n@@ -124,6 +124,10 @@ typedef struct PgBackendStatus\n \tTimestampTz st_activity_start_timestamp;\n \tTimestampTz st_state_start_timestamp;\n \n+\t/* Session active/idle time in microsecnods */\n+\tint64\t\tst_session_active_time;\n+\tint64\t\tst_session_idle_time;\n+\n \t/* Database OID, owning user's OID, connection client address */\n \tOid\t\t\tst_databaseid;\n \tOid\t\t\tst_userid;", "msg_date": "Wed, 25 Aug 2021 14:59:37 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "Hi,\n\nOn 2021-08-20 14:27:20 -0500, Justin Pryzby wrote:\n> On Tue, Aug 17, 2021 at 02:14:20AM -0700, Andres Freund wrote:\n> > Doubling the number of UDP messages in common workloads seems also problematic\n> > enough that it should be addressed for 14. It increases the likelihood of\n> > dropping stats messages on busy systems, which can have downstream impacts.\n> \n> I think by \"common workloads\" you mean one with many, shortlived sessions.\n\nYou don't need short-lived sessions. You just need sessions that don't\nprocess queries all the time (so that there's only one or a few queries\nwithin each PGSTAT_STAT_INTERVAL). The connection stats aren't sent once\nper session, they're sent once per PGSTAT_STAT_INTERVAL.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 25 Aug 2021 01:17:19 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "Hi,\n\nOn 2021-08-25 12:51:58 +0900, Michael Paquier wrote:\n> I was looking at this WIP patch, and plugging in the connection\n> statistics to the table-access statistics looks like the wrong\n> abstraction to me. I find much cleaner the approach of HEAD to use a\n> separate API to report this information, as of\n> pgstat_send_connstats().\n\nAs I said before, this ship has long sailed:\n\ntypedef struct PgStat_MsgTabstat\n{\n\tPgStat_MsgHdr m_hdr;\n\tOid\t\t\tm_databaseid;\n\tint\t\t\tm_nentries;\n\tint\t\t\tm_xact_commit;\n\tint\t\t\tm_xact_rollback;\n\tPgStat_Counter m_block_read_time;\t/* times in microseconds */\n\tPgStat_Counter m_block_write_time;\n\tPgStat_TableEntry m_entry[PGSTAT_NUM_TABENTRIES];\n} PgStat_MsgTabstat;\n\n\n> As of the two problems discussed on this thread, aka the increased\n> number of UDP packages and the extra timestamp computations, it seems\n> to me that we had better combine the following ideas for HEAD and 14,\n> for now:\n> - Avoid the extra timestamp computation as proposed by Laurenz in [1]\n> - Throttle the frequency where the connection stat packages are sent,\n> as of [2].\n\nI think in that case we'd have to do the bigger redesign and move \"live\"\nconnection stats to backend_status.c...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 25 Aug 2021 01:20:03 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "On Wed, Aug 25, 2021 at 01:20:03AM -0700, Andres Freund wrote:\n> On 2021-08-25 12:51:58 +0900, Michael Paquier wrote:\n> As I said before, this ship has long sailed:\n> \n> typedef struct PgStat_MsgTabstat\n> {\n> \tPgStat_MsgHdr m_hdr;\n> \tOid\t\t\tm_databaseid;\n> \tint\t\t\tm_nentries;\n> \tint\t\t\tm_xact_commit;\n> \tint\t\t\tm_xact_rollback;\n> \tPgStat_Counter m_block_read_time;\t/* times in microseconds */\n> \tPgStat_Counter m_block_write_time;\n> \tPgStat_TableEntry m_entry[PGSTAT_NUM_TABENTRIES];\n> } PgStat_MsgTabstat;\n\nWell, I kind of misread what you meant upthread then.\nPgStat_MsgTabstat has a name a bit misleading, especially if you\nassign connection stats to it.\n\n>> As of the two problems discussed on this thread, aka the increased\n>> number of UDP packages and the extra timestamp computations, it seems\n>> to me that we had better combine the following ideas for HEAD and 14,\n>> for now:\n>> - Avoid the extra timestamp computation as proposed by Laurenz in [1]\n>> - Throttle the frequency where the connection stat packages are sent,\n>> as of [2].\n> \n> I think in that case we'd have to do the bigger redesign and move \"live\"\n> connection stats to backend_status.c...\n\nHmm. A redesign is not really an option for 14 at this stage. And I\nam not really comfortable with the latest proposal from upthread to\nplug in that to pgstat_send_tabstat to report things once per\ntransaction, either. It really looks like this needs more thoughts,\nand it would mean that a revert may be the most appropriate choice\nfor the moment. That's the last-resort option, surely, but we are\npost-beta3 so there is no much margin left.\n--\nMichael", "msg_date": "Fri, 27 Aug 2021 13:57:45 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "On Fri, 2021-08-27 at 13:57 +0900, Michael Paquier wrote:\n> > I think in that case we'd have to do the bigger redesign and move \"live\"\n> > connection stats to backend_status.c...\n> \n> Hmm.  A redesign is not really an option for 14 at this stage.  And I\n> am not really comfortable with the latest proposal from upthread to\n> plug in that to pgstat_send_tabstat to report things once per\n> transaction, either.  It really looks like this needs more thoughts,\n> and it would mean that a revert may be the most appropriate choice\n> for the moment.  That's the last-resort option, surely, but we are\n> post-beta3 so there is no much margin left.\n\nIn the view of that, how about doubling PGSTAT_STAT_INTERVAL to 1000\nmilliseconds? That would mean slightly less up-to-date statistics, but\nI doubt that that will be a problem. And it should even out the increase\nin statistics messages, except in the case of lots of short-lived\nsessions. But in that scenario you cannot have session statistics\nwithout lots of extra messages, and such a workload has enough performance\nproblems as it is, so I don't think we have to specifically worry about it.\n\nYours,\nLaurenz Albe\n\n\n\n", "msg_date": "Tue, 31 Aug 2021 04:55:35 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "On Tue, Aug 31, 2021 at 04:55:35AM +0200, Laurenz Albe wrote:\n> In the view of that, how about doubling PGSTAT_STAT_INTERVAL to 1000\n> milliseconds? That would mean slightly less up-to-date statistics, but\n> I doubt that that will be a problem. And it should even out the increase\n> in statistics messages, except in the case of lots of short-lived\n> sessions. But in that scenario you cannot have session statistics\n> without lots of extra messages, and such a workload has enough performance\n> problems as it is, so I don't think we have to specifically worry about it.\n\nPerhaps we could do that. Now, increasing an interval for the sake of\nbalancing the extra load created by a feature while impacting the\nwhole set of stats is not really appealing.\n--\nMichael", "msg_date": "Wed, 1 Sep 2021 10:33:15 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "Hi,\n\nOn August 31, 2021 6:33:15 PM PDT, Michael Paquier <michael@paquier.xyz> wrote:\n>On Tue, Aug 31, 2021 at 04:55:35AM +0200, Laurenz Albe wrote:\n>> In the view of that, how about doubling PGSTAT_STAT_INTERVAL to 1000\n>> milliseconds? That would mean slightly less up-to-date statistics, but\n>> I doubt that that will be a problem. And it should even out the increase\n>> in statistics messages, except in the case of lots of short-lived\n>> sessions. But in that scenario you cannot have session statistics\n>> without lots of extra messages, and such a workload has enough performance\n>> problems as it is, so I don't think we have to specifically worry about it.\n>\n>Perhaps we could do that. Now, increasing an interval for the sake of\n>balancing the extra load created by a feature while impacting the\n>whole set of stats is not really appealing.\n\nI think it's not helpful. Still increases the number of messages substantially in workloads with a lot of connections doing occasional queries. Which is common.\n\nAndres\n-- \nSent from my Android device with K-9 Mail. Please excuse my brevity.\n\n\n", "msg_date": "Tue, 31 Aug 2021 18:55:58 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "=?US-ASCII?Q?Re=3A_pgstat=5Fsend=5Fconnstats=28=29_introduces?=\n =?US-ASCII?Q?_unnecessary_timestamp_and_UDP_overhead?=" }, { "msg_contents": "On Tue, 2021-08-31 at 18:55 -0700, Andres Freund wrote:\n> > > On Tue, Aug 31, 2021 at 04:55:35AM +0200, Laurenz Albe wrote:In the view of that, how about doubling PGSTAT_STAT_INTERVAL to 1000\n> > \n> > > milliseconds?  That would mean slightly less up-to-date statistics, but\n> > > I doubt that that will be a problem.\n>\n> I think it's not helpful. Still increases the number of messages substantially in workloads\n> with a lot of connections doing occasional queries. Which is common.\n\nHow come? If originally you send table statistics every 500ms, and now you send\ntable statistics and session statistics every second, that should amount to the\nsame thing. Where is my misunderstanding?\n\nYours,\nLaurenz Albe\n\n\n\n", "msg_date": "Wed, 01 Sep 2021 05:39:14 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "On Wed, 2021-09-01 at 10:33 +0900, Michael Paquier wrote:\n> On Tue, Aug 31, 2021 at 04:55:35AM +0200, Laurenz Albe wrote:\n> > In the view of that, how about doubling PGSTAT_STAT_INTERVAL to 1000\n> > milliseconds?\n> \n> Perhaps we could do that.  Now, increasing an interval for the sake of\n> balancing the extra load created by a feature while impacting the\n> whole set of stats is not really appealing.\n\nI agree. But if the best fix is too invasive at this point, the\nalternatives are reverting the patch or choosing a less appealing\nsolution.\n\nYours,\nLaurenz Albe\n\n\n\n", "msg_date": "Wed, 01 Sep 2021 05:42:19 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "On 2021-09-01 05:39:14 +0200, Laurenz Albe wrote:\n> On Tue, 2021-08-31 at 18:55 -0700, Andres Freund wrote:\n> > > > On Tue, Aug 31, 2021 at 04:55:35AM +0200, Laurenz Albe wrote:In the view of that, how about doubling PGSTAT_STAT_INTERVAL to 1000\n> > > \n> > > > milliseconds?� That would mean slightly less up-to-date statistics, but\n> > > > I doubt that that will be a problem.\n> >\n> > I think it's not helpful. Still increases the number of messages substantially in workloads\n> > with a lot of connections doing occasional queries. Which is common.\n> \n> How come? If originally you send table statistics every 500ms, and now you send\n> table statistics and session statistics every second, that should amount to the\n> same thing. Where is my misunderstanding?\n\nConsider the case of one query a second.\n\n\n", "msg_date": "Tue, 31 Aug 2021 21:16:25 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "On 2021-08-27 13:57:45 +0900, Michael Paquier wrote:\n> On Wed, Aug 25, 2021 at 01:20:03AM -0700, Andres Freund wrote:\n> > On 2021-08-25 12:51:58 +0900, Michael Paquier wrote:\n> > As I said before, this ship has long sailed:\n> > \n> > typedef struct PgStat_MsgTabstat\n> > {\n> > \tPgStat_MsgHdr m_hdr;\n> > \tOid\t\t\tm_databaseid;\n> > \tint\t\t\tm_nentries;\n> > \tint\t\t\tm_xact_commit;\n> > \tint\t\t\tm_xact_rollback;\n> > \tPgStat_Counter m_block_read_time;\t/* times in microseconds */\n> > \tPgStat_Counter m_block_write_time;\n> > \tPgStat_TableEntry m_entry[PGSTAT_NUM_TABENTRIES];\n> > } PgStat_MsgTabstat;\n> \n> Well, I kind of misread what you meant upthread then.\n> PgStat_MsgTabstat has a name a bit misleading, especially if you\n> assign connection stats to it.\n\nISTM we should just do this fairly obvious change. Given that we already\ntransport commit / rollback / IO stats, I don't see why the connection stats\nchange anything to a meaningful degree. I'm fairly baffled why that's not the\nobvious thing to do for v14.\n\n\n", "msg_date": "Tue, 31 Aug 2021 21:56:50 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "On Tue, 2021-08-31 at 21:16 -0700, Andres Freund wrote:\n> On 2021-09-01 05:39:14 +0200, Laurenz Albe wrote:\n> > On Tue, 2021-08-31 at 18:55 -0700, Andres Freund wrote:\n> > > > > On Tue, Aug 31, 2021 at 04:55:35AM +0200, Laurenz Albe wrote:In the\n> > > > > view of that, how about doubling PGSTAT_STAT_INTERVAL to 1000\n> > > > > milliseconds?  That would mean slightly less up-to-date statistics, but\n> > > > > I doubt that that will be a problem.\n> > > \n> > > I think it's not helpful. Still increases the number of messages substantially in workloads\n> > > with a lot of connections doing occasional queries. Which is common.\n> > \n> > How come?  If originally you send table statistics every 500ms, and now you send\n> > table statistics and session statistics every second, that should amount to the\n> > same thing.  Where is my misunderstanding?\n> \n> Consider the case of one query a second.\n\nI guess I am too stupid. I don't see it.\n\nYours,\nLaurenz Albe\n\n\n\n", "msg_date": "Wed, 01 Sep 2021 10:56:04 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "On Wed, 2021-09-01 at 10:56 +0200, Laurenz Albe wrote:\n> On Tue, 2021-08-31 at 21:16 -0700, Andres Freund wrote:\n> > On 2021-09-01 05:39:14 +0200, Laurenz Albe wrote:\n> > > On Tue, 2021-08-31 at 18:55 -0700, Andres Freund wrote:\n> > > > > > On Tue, Aug 31, 2021 at 04:55:35AM +0200, Laurenz Albe wrote:In the\n> > > > > > view of that, how about doubling PGSTAT_STAT_INTERVAL to 1000\n> > > > > > milliseconds?  That would mean slightly less up-to-date statistics, but\n> > > > > > I doubt that that will be a problem.\n> > > > \n> > > > I think it's not helpful. Still increases the number of messages substantially in workloads\n> > > > with a lot of connections doing occasional queries. Which is common.\n> > > \n> > > How come?  If originally you send table statistics every 500ms, and now you send\n> > > table statistics and session statistics every second, that should amount to the\n> > > same thing.  Where is my misunderstanding?\n> > \n> > Consider the case of one query a second.\n> \n> I guess I am too stupid.  I don't see it.\n\nFinally got it. That would send a message every second, and with connection statistics,\ntwice as many.\n\nHere is my next suggestion for a band-aid to mitigate this problem:\nIntroduce a second, much longer interval for reporting session statistics.\n\n--- a/src/backend/postmaster/pgstat.c\n+++ b/src/backend/postmaster/pgstat.c\n@@ -77,6 +77,8 @@\n #define PGSTAT_STAT_INTERVAL\t500 /* Minimum time between stats file\n \t\t\t\t\t\t\t\t\t * updates; in milliseconds. */\n \n+#define PGSTAT_CONSTAT_INTERVAL\t60000\t/* interval to report connection statistics */\n+\n #define PGSTAT_RETRY_DELAY\t\t10\t/* How long to wait between checks for a\n \t\t\t\t\t\t\t\t\t * new file; in milliseconds. */\n \n@@ -889,8 +891,13 @@ pgstat_report_stat(bool disconnect)\n \t\t!TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))\n \t\treturn;\n \n-\t/* for backends, send connection statistics */\n-\tif (MyBackendType == B_BACKEND)\n+\t/*\n+\t * For backends, send connection statistics, but only every\n+\t * PGSTAT_CONSTAT_INTERVAL or when the backend terminates.\n+\t */\n+\tif (MyBackendType == B_BACKEND &&\n+\t\t(TimestampDifferenceExceeds(last_report, now, PGSTAT_CONSTAT_INTERVAL) ||\n+\t\t disconnect))\n \t\tpgstat_send_connstats(disconnect, last_report, now);\n \n \tlast_report = now;\n\nThat should keep the extra load moderate, except for workloads with lots of tiny connections\n(for which this may be the least of their problems).\n\nYours,\nLaurenz Albe\n\n\n\n", "msg_date": "Fri, 03 Sep 2021 04:51:46 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "Hi,\n\nOn 2021-08-31 21:56:50 -0700, Andres Freund wrote:\n> On 2021-08-27 13:57:45 +0900, Michael Paquier wrote:\n> > On Wed, Aug 25, 2021 at 01:20:03AM -0700, Andres Freund wrote:\n> > > On 2021-08-25 12:51:58 +0900, Michael Paquier wrote:\n> > > As I said before, this ship has long sailed:\n> > >\n> > > typedef struct PgStat_MsgTabstat\n> > > {\n> > > \tPgStat_MsgHdr m_hdr;\n> > > \tOid\t\t\tm_databaseid;\n> > > \tint\t\t\tm_nentries;\n> > > \tint\t\t\tm_xact_commit;\n> > > \tint\t\t\tm_xact_rollback;\n> > > \tPgStat_Counter m_block_read_time;\t/* times in microseconds */\n> > > \tPgStat_Counter m_block_write_time;\n> > > \tPgStat_TableEntry m_entry[PGSTAT_NUM_TABENTRIES];\n> > > } PgStat_MsgTabstat;\n> >\n> > Well, I kind of misread what you meant upthread then.\n> > PgStat_MsgTabstat has a name a bit misleading, especially if you\n> > assign connection stats to it.\n>\n> ISTM we should just do this fairly obvious change. Given that we already\n> transport commit / rollback / IO stats, I don't see why the connection stats\n> change anything to a meaningful degree. I'm fairly baffled why that's not the\n> obvious thing to do for v14.\n\nHere's how I think that would look like. While writing up this draft, I found\ntwo more issues:\n\n- On windows / 32 bit systems, the session time would overflow if idle for\n longer than ~4300s. long is only 32 bit. Easy to fix obviously.\n- Right now walsenders, including database connected walsenders, are not\n reported in connection stats. That doesn't seem quite right to me.\n\nIn the patch I made the message for connecting an explicitly reported message,\nthat seems cleaner, because it then happens at a clearly defined point. I\ndidn't do the same for disconnecting, but perhaps that would be better? Then\nwe could get rid of the whole pgStatSessionEndCause variable.\n\nGreetings,\n\nAndres Freund", "msg_date": "Fri, 3 Sep 2021 17:04:31 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "On Fri, 2021-09-03 at 17:04 -0700, Andres Freund wrote:\n> Hi,\n> \n> On 2021-08-31 21:56:50 -0700, Andres Freund wrote:\n> > On 2021-08-27 13:57:45 +0900, Michael Paquier wrote:\n> > > On Wed, Aug 25, 2021 at 01:20:03AM -0700, Andres Freund wrote:\n> > > > On 2021-08-25 12:51:58 +0900, Michael Paquier wrote:\n> > > > As I said before, this ship has long sailed:\n> > > > \n> > > > typedef struct PgStat_MsgTabstat\n> > > > {\n> > > >         PgStat_MsgHdr m_hdr;\n> > > >         Oid                     m_databaseid;\n> > > >         int                     m_nentries;\n> > > >         int                     m_xact_commit;\n> > > >         int                     m_xact_rollback;\n> > > >         PgStat_Counter m_block_read_time;       /* times in microseconds */\n> > > >         PgStat_Counter m_block_write_time;\n> > > >         PgStat_TableEntry m_entry[PGSTAT_NUM_TABENTRIES];\n> > > > } PgStat_MsgTabstat;\n> > > \n> > > Well, I kind of misread what you meant upthread then.\n> > > PgStat_MsgTabstat has a name a bit misleading, especially if you\n> > > assign connection stats to it.\n> > \n> > ISTM we should just do this fairly obvious change. Given that we already\n> > transport commit / rollback / IO stats, I don't see why the connection stats\n> > change anything to a meaningful degree. I'm fairly baffled why that's not the\n> > obvious thing to do for v14.\n> \n> Here's how I think that would look like.\n\nThank you!\n\n> While writing up this draft, I found\n> two more issues:\n> \n> - On windows / 32 bit systems, the session time would overflow if idle for\n>   longer than ~4300s. long is only 32 bit. Easy to fix obviously.\n\nOops, yes. Thanks for spotting that.\n\n> - Right now walsenders, including database connected walsenders, are not\n>   reported in connection stats. That doesn't seem quite right to me.\n\nI think that walsenders not only use a different protocol, but often have\nsession characteristics quite different from normal backends.\nFor example, they are always \"active\", even when they are doing nothing.\nTherefore, I think it is confusing to report them together with normal\ndatabase sessions.\n\nIf at all, walsender statistics should be reported separately.\n\n> In the patch I made the message for connecting an explicitly reported message,\n> that seems cleaner, because it then happens at a clearly defined point. I\n> didn't do the same for disconnecting, but perhaps that would be better? Then\n> we could get rid of the whole pgStatSessionEndCause variable.\n\nI see your point, but I am not certain if it is worth adding yet another message\nfor a small thing like that. I have no strong opinion on that though.\n\n\nReading your patch, I am still confused about the following:\nThere are potentially several calls to \"pgstat_send_tabstat\" in \"pgstat_report_stat\".\nIt seems to me that if it were called more than once, session statistics would\nbe reported and counted several times, which would be wrong.\n\nYours,\nLaurenz Albe\n\n\n\n", "msg_date": "Mon, 06 Sep 2021 09:12:58 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "Hi,\n\nOn 2021-09-06 09:12:58 +0200, Laurenz Albe wrote:\n> Reading your patch, I am still confused about the following:\n> There are potentially several calls to \"pgstat_send_tabstat\" in \"pgstat_report_stat\".\n> It seems to me that if it were called more than once, session statistics would\n> be reported and counted several times, which would be wrong.\n\nThe accumulator variables are set to zero after being sent. So no data should\nbe sent multiple times as far as I can tell.\n\nRegards,\n\nAndres\n\n\n", "msg_date": "Mon, 6 Sep 2021 00:22:02 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "On Mon, 2021-09-06 at 00:22 -0700, Andres Freund wrote:\n> On 2021-09-06 09:12:58 +0200, Laurenz Albe wrote:\n> > Reading your patch, I am still confused about the following:\n> > There are potentially several calls to \"pgstat_send_tabstat\" in \"pgstat_report_stat\".\n> > It seems to me that if it were called more than once, session statistics would\n> > be reported and counted several times, which would be wrong.\n> \n> The accumulator variables are set to zero after being sent. So no data should\n> be sent multiple times as far as I can tell.\n\nAh, I missed that. Then I see no problem with that approach.\n\nYours,\nLaurenz Albe\n\n\n\n", "msg_date": "Mon, 06 Sep 2021 09:37:55 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "On Fri, 2021-09-03 at 17:04 -0700, Andres Freund wrote:\n> Here's how I think that would look like. While writing up this draft, I found\n> two more issues:\n> \n> - On windows / 32 bit systems, the session time would overflow if idle for\n>   longer than ~4300s. long is only 32 bit. Easy to fix obviously.\n> - Right now walsenders, including database connected walsenders, are not\n>   reported in connection stats. That doesn't seem quite right to me.\n> \n> In the patch I made the message for connecting an explicitly reported message,\n> that seems cleaner, because it then happens at a clearly defined point. I\n> didn't do the same for disconnecting, but perhaps that would be better? Then\n> we could get rid of the whole pgStatSessionEndCause variable.\n\nI have gone over your patch and made the following changes:\n\n- cache the last report time in a static variable pgLastSessionReportTime\n- add a comment to explain why we only track normal backends\n- pgindent\n- an attempt at a commit message\n\nYours,\nLaurenz Albe", "msg_date": "Wed, 08 Sep 2021 06:11:56 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "\nOn 9/8/21 12:11 AM, Laurenz Albe wrote:\n> On Fri, 2021-09-03 at 17:04 -0700, Andres Freund wrote:\n>> Here's how I think that would look like. While writing up this draft, I found\n>> two more issues:\n>>\n>> - On windows / 32 bit systems, the session time would overflow if idle for\n>>   longer than ~4300s. long is only 32 bit. Easy to fix obviously.\n>> - Right now walsenders, including database connected walsenders, are not\n>>   reported in connection stats. That doesn't seem quite right to me.\n>>\n>> In the patch I made the message for connecting an explicitly reported message,\n>> that seems cleaner, because it then happens at a clearly defined point. I\n>> didn't do the same for disconnecting, but perhaps that would be better? Then\n>> we could get rid of the whole pgStatSessionEndCause variable.\n> I have gone over your patch and made the following changes:\n>\n> - cache the last report time in a static variable pgLastSessionReportTime\n> - add a comment to explain why we only track normal backends\n> - pgindent\n> - an attempt at a commit message\n>\n\nHi,\n\n\nthis is an open item for release 14. Is someone going to commit?\n\n\ncheers\n\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Wed, 15 Sep 2021 10:47:33 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "On 2021-09-15 10:47:33 -0400, Andrew Dunstan wrote:\n> this is an open item for release 14. Is someone going to commit?\n\nWill do. Although I do wish the original committer would have chimed in at\nsome point...\n\n\n", "msg_date": "Wed, 15 Sep 2021 13:48:09 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "On Wed, Sep 15, 2021 at 01:48:09PM -0700, Andres Freund wrote:\n> Will do. Although I do wish the original committer would have chimed in at\n> some point...\n\nThanks, Andres.\n--\nMichael", "msg_date": "Thu, 16 Sep 2021 08:41:30 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "Hi,\n\nOn 2021-09-08 06:11:56 +0200, Laurenz Albe wrote:\n> I have gone over your patch and made the following changes:\n> \n> - cache the last report time in a static variable pgLastSessionReportTime\n> - add a comment to explain why we only track normal backends\n> - pgindent\n> - an attempt at a commit message\n\nThanks!\n\nI pushed this. The only substantive change I made is that I moved the\nMyBackendType == B_BACKEND check into a new pgstat_should_report_connstat(),\nand called that from pgstat_report_connect() and\npgstat_report_disconnect(). Otherwise we'd report connect/disconnect for\nwalsenders, but not the session time, which seems even weirder.\n\nClosed the open item.\n\nI'm not convinced that ignorign walsenders is a good policy decision, but I\nthink that's a fair judgement call, and we can evolve that in future\nreleases...\n\n\nOne thing that'd be nice to have is a few regression tests in stats.sql. Of\ncourse we couldn't test precise counts, but just verifying that some of the\ncounters increase seems like it would provide a decent increase in \"actual\"\ncoverage. One of the more painful things in working on the shared memory stats\npatch is that nearly all stats features have no tests, making it very easy to\nsilently break things.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 16 Sep 2021 02:22:33 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "On Thu, 2021-09-16 at 02:22 -0700, Andres Freund wrote:\n> I pushed this. The only substantive change I made is that I moved the\n> MyBackendType == B_BACKEND check into a new pgstat_should_report_connstat(),\n> and called that from pgstat_report_connect() and\n> pgstat_report_disconnect(). Otherwise we'd report connect/disconnect for\n> walsenders, but not the session time, which seems even weirder.\n\nOh, right, I didn't think of that.\n\nThanks for all the work you put into this.\n\n> I'm not convinced that ignorign walsenders is a good policy decision, but I\n> think that's a fair judgement call, and we can evolve that in future\n> releases...\n\nThe use case that is on my mind is to figure out the percentage of time\nwhen transactions are idle to be able to estimate the connection pool size.\nwalsenders, for which you typically don't want to use a connection pool,\nwould skew the statistics.\n\nYours,\nLaurenz Albe\n\n\n\n", "msg_date": "Thu, 16 Sep 2021 15:55:07 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and\n UDP overhead" }, { "msg_contents": "On Wed, Sep 15, 2021 at 10:48 PM Andres Freund <andres@anarazel.de> wrote:\n>\n> On 2021-09-15 10:47:33 -0400, Andrew Dunstan wrote:\n> > this is an open item for release 14. Is someone going to commit?\n>\n> Will do. Although I do wish the original committer would have chimed in at\n> some point...\n\nCrap. My apologies for this -- I had somehow managed to press the\n\"mute\" button in gmail on tihs thread when I cleaned things up after\nreturning from my vacation, so I hadn't spotted anything in it until I\nsaw your commit happening a short wihle ago. I have no idea how I\nmanaged to do that, but clearly I did. Sorry!\n\nAIUI the commit has taken care of the urgent things for 14, correct? I\nsee there are some discussions points left and I'll review the thread\nand see if I have any input on those as well a bit later, of course,\nbut just so I'm not missing something else that's urgent?\n\nAgain, my apologies for completely missing this!\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/\n Work: https://www.redpill-linpro.com/\n\n\n", "msg_date": "Thu, 16 Sep 2021 16:38:04 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" }, { "msg_contents": "Hi,\n\nOn 2021-09-16 16:38:04 +0200, Magnus Hagander wrote:\n> On Wed, Sep 15, 2021 at 10:48 PM Andres Freund <andres@anarazel.de> wrote:\n> >\n> > On 2021-09-15 10:47:33 -0400, Andrew Dunstan wrote:\n> > > this is an open item for release 14. Is someone going to commit?\n> >\n> > Will do. Although I do wish the original committer would have chimed in at\n> > some point...\n> \n> Crap. My apologies for this -- I had somehow managed to press the\n> \"mute\" button in gmail on tihs thread when I cleaned things up after\n> returning from my vacation, so I hadn't spotted anything in it until I\n> saw your commit happening a short wihle ago. I have no idea how I\n> managed to do that, but clearly I did. Sorry!\n\nHah, that explains that ;)\n\n\n> AIUI the commit has taken care of the urgent things for 14, correct? I\n> see there are some discussions points left and I'll review the thread\n> and see if I have any input on those as well a bit later, of course,\n> but just so I'm not missing something else that's urgent?\n\nI think so.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 16 Sep 2021 18:52:44 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgstat_send_connstats() introduces unnecessary timestamp and UDP\n overhead" } ]
[ { "msg_contents": "Hi,\n\nWhile looking at a patch I noticed that SubPostmasterMain() for bgworkers\nunconditionally does\n\n\t\t/* Need a PGPROC to run CreateSharedMemoryAndSemaphores */\n\t\tInitProcess();\n\nwhich presents a problem, because StartBackgroundWorker() then does\n\n\t/*\n\t * If we're not supposed to have shared memory access, then detach from\n\t * shared memory. If we didn't request shared memory access, the\n\t * postmaster won't force a cluster-wide restart if we exit unexpectedly,\n\t * so we'd better make sure that we don't mess anything up that would\n\t * require that sort of cleanup.\n\t */\n\tif ((worker->bgw_flags & BGWORKER_SHMEM_ACCESS) == 0)\n\t{\n\t\tShutdownLatchSupport();\n\t\tdsm_detach_all();\n\t\tPGSharedMemoryDetach();\n\t}\n\nwhich presents a problem: We've initialized all kind of references to shared\nmemory, own a PGPROC, but have detached from shared memory.\n\nIn practice this will lead pretty quickly to a segfault, because process exit\nwill run proc_exit callbacks, which in turn will try to do a ProcKill(). Or\nlogging dereferences MyProc, or ...\n\nIt seems the above code block would need to at least do shmem_exit() before\nthe PGSharedMemoryDetach()?\n\nThis code has been introduced in\n\ncommit 4d155d8b08fe08c1a1649fdbad61c6dcf4a8671f\nAuthor: Robert Haas <rhaas@postgresql.org>\nDate: 2014-05-07 14:54:43 -0400\n\n Detach shared memory from bgworkers without shmem access.\n\n Since the postmaster won't perform a crash-and-restart sequence\n for background workers which don't request shared memory access,\n we'd better make sure that they can't corrupt shared memory.\n\n Patch by me, review by Tom Lane.\n\nbut before that things were just slightly differently broken...\n\n\nI tested both the crash and that a shmem_exit() fixes it with an ugly hack in\nregress.c. I don't really know how to write a good testcase for this, given\nthat the communication facilities of a unconnected bgworker are quite\nlimited... I guess the bgworker could create files or something :(.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sun, 1 Aug 2021 23:51:16 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" }, { "msg_contents": "Hi,\n\nOn 2021-08-01 23:51:16 -0700, Andres Freund wrote:\n> In practice this will lead pretty quickly to a segfault, because process exit\n> will run proc_exit callbacks, which in turn will try to do a ProcKill(). Or\n> logging dereferences MyProc, or ...\n> \n> It seems the above code block would need to at least do shmem_exit() before\n> the PGSharedMemoryDetach()?\n\n> I tested both the crash and that a shmem_exit() fixes it with an ugly hack in\n> regress.c. I don't really know how to write a good testcase for this, given\n> that the communication facilities of a unconnected bgworker are quite\n> limited... I guess the bgworker could create files or something :(.\n\nHm. There may be another way: Because BackgroundWorkerEntry() does not\nactually need a lock, we could transport BackgroundWorkerData via\nbackend_save_variables(). To make the connected case work, we'd of course\ncontinue to call CreateSharedMemoryAndSemaphores (and thus InitProcess()) for\nthose.\n\nBut that doesn't really seem better? Sure, it's nice to not need a pgproc\nentry unnecessarily, but it's not like unconnected bgworkers are commonly\nused and it does seem like it'd end up with more complicated code?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 2 Aug 2021 00:01:42 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" }, { "msg_contents": "On Mon, Aug 2, 2021 at 2:51 AM Andres Freund <andres@anarazel.de> wrote:\n> which presents a problem: We've initialized all kind of references to shared\n> memory, own a PGPROC, but have detached from shared memory.\n>\n> In practice this will lead pretty quickly to a segfault, because process exit\n> will run proc_exit callbacks, which in turn will try to do a ProcKill(). Or\n> logging dereferences MyProc, or ...\n>\n> It seems the above code block would need to at least do shmem_exit() before\n> the PGSharedMemoryDetach()?\n>\n> This code has been introduced in\n>\n> commit 4d155d8b08fe08c1a1649fdbad61c6dcf4a8671f\n> Author: Robert Haas <rhaas@postgresql.org>\n> Date: 2014-05-07 14:54:43 -0400\n>\n> Detach shared memory from bgworkers without shmem access.\n>\n> Since the postmaster won't perform a crash-and-restart sequence\n> for background workers which don't request shared memory access,\n> we'd better make sure that they can't corrupt shared memory.\n>\n> Patch by me, review by Tom Lane.\n>\n> but before that things were just slightly differently broken...\n\nIf you're saying that this code has been 100% broken for 7 years and\nnobody's noticed until now, then that suggests that nobody actually\nuses non-shmem-connected bgworkers. I sort of hate to give up on that\nconcept but if we've really gone that many years without anyone\nnoticing obvious breakage then maybe we should.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 2 Aug 2021 10:54:15 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> If you're saying that this code has been 100% broken for 7 years and\n> nobody's noticed until now, then that suggests that nobody actually\n> uses non-shmem-connected bgworkers. I sort of hate to give up on that\n> concept but if we've really gone that many years without anyone\n> noticing obvious breakage then maybe we should.\n\nWell, the problem only exists on Windows so maybe this indeed\nescaped notice. Still, this is good evidence that the case isn't\nused *much*, and TBH I don't see many applications for it.\nI can't say I'm excited about putting effort into fixing it.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 02 Aug 2021 11:00:49 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" }, { "msg_contents": "Hi,\n\nOn 2021-08-02 11:00:49 -0400, Tom Lane wrote:\n> Robert Haas <robertmhaas@gmail.com> writes:\n> > If you're saying that this code has been 100% broken for 7 years and\n> > nobody's noticed until now, then that suggests that nobody actually\n> > uses non-shmem-connected bgworkers. I sort of hate to give up on that\n> > concept but if we've really gone that many years without anyone\n> > noticing obvious breakage then maybe we should.\n> \n> Well, the problem only exists on Windows so maybe this indeed\n> escaped notice.\n\nRight. I did briefly look around and I didn't find bgworkers without\nshmem attachement...\n\n\n> Still, this is good evidence that the case isn't used *much*, and TBH\n> I don't see many applications for it. I can't say I'm excited about\n> putting effort into fixing it.\n\nYea, I don't think it adds that much - without e.g. sharing a file\ndescriptor with the unconnected bgworker one can't implement something\nlike syslogger.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 2 Aug 2021 08:49:59 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" }, { "msg_contents": "On 2021-Aug-02, Tom Lane wrote:\n\n> Robert Haas <robertmhaas@gmail.com> writes:\n> > If you're saying that this code has been 100% broken for 7 years and\n> > nobody's noticed until now, then that suggests that nobody actually\n> > uses non-shmem-connected bgworkers. I sort of hate to give up on that\n> > concept but if we've really gone that many years without anyone\n> > noticing obvious breakage then maybe we should.\n> \n> Well, the problem only exists on Windows so maybe this indeed\n> escaped notice. Still, this is good evidence that the case isn't\n> used *much*, and TBH I don't see many applications for it.\n> I can't say I'm excited about putting effort into fixing it.\n\nWhen I included this case I was thinking in tasks which would just run\nstuff not directly connected to data. Something like a sub-daemon: say\na connection pooler, which is a bgworker just so that it starts and\nstops together with postmaster, and share facilities like GUC\nconfiguration and SIGHUP handling, etc. It doesn't look like anybody\nhas had an interest in developing such a thing, so if this is\nobstructing your work, I don't object to removing the no-shmem case.\n\n-- \nÁlvaro Herrera 39°49'30\"S 73°17'W — https://www.EnterpriseDB.com/\n\n\n", "msg_date": "Mon, 2 Aug 2021 14:08:41 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" }, { "msg_contents": "Hi,\n\nOn Mon, Aug 2, 2021, at 11:08, Alvaro Herrera wrote:\n> On 2021-Aug-02, Tom Lane wrote:\n> \n> > Robert Haas <robertmhaas@gmail.com> writes:\n> > > If you're saying that this code has been 100% broken for 7 years and\n> > > nobody's noticed until now, then that suggests that nobody actually\n> > > uses non-shmem-connected bgworkers. I sort of hate to give up on that\n> > > concept but if we've really gone that many years without anyone\n> > > noticing obvious breakage then maybe we should.\n> > \n> > Well, the problem only exists on Windows so maybe this indeed\n> > escaped notice. Still, this is good evidence that the case isn't\n> > used *much*, and TBH I don't see many applications for it.\n> > I can't say I'm excited about putting effort into fixing it.\n> \n> When I included this case I was thinking in tasks which would just run\n> stuff not directly connected to data. Something like a sub-daemon: say\n> a connection pooler, which is a bgworker just so that it starts and\n> stops together with postmaster, and share facilities like GUC\n> configuration and SIGHUP handling, etc.\n\nI think nearly all such cases are going to want some monitoring from within the database - which then needs shared memory.\n\nAnd even if not - it's not really that useful to avoid a crash-restart if your worker dies with a segfault. There's no really legitimate reasons for completely unhandled errors even if not connected to shmem.\n\n\n> It doesn't look like anybody\n> has had an interest in developing such a thing, so if this is\n> obstructing your work, I don't object to removing the no-shmem case.\n\nIt's not obstructing me right now. I noticed it'd crash on EXEC_BACKEND when I tried to understand some code (see the nearby thread about straightening out process startup). \n\nI do think there's some potential gains in simplicity and robustness that are made mildly harder by a subprocess that first attaches and detaches from shm (it's the only case where we can't easily unify the place InitProcess() is called between EB and ! EB right now). There's several ways that could be tackled. Removing the need to have that if obviously one of them.\n\nRegards,\n\nAndres\n\n\n", "msg_date": "Mon, 02 Aug 2021 11:40:28 -0700", "msg_from": "\"Andres Freund\" <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" }, { "msg_contents": "On 2021-Aug-02, Andres Freund wrote:\n\n> > When I included this case I was thinking in tasks which would just run\n> > stuff not directly connected to data. Something like a sub-daemon: say\n> > a connection pooler, which is a bgworker just so that it starts and\n> > stops together with postmaster, and share facilities like GUC\n> > configuration and SIGHUP handling, etc.\n> \n> I think nearly all such cases are going to want some monitoring from\n> within the database - which then needs shared memory.\n\nTrue. Observability for such things is critical (pgbouncer goes quite\nsome trouble to offer SQL-queryable views into its metrics), which kills\nthe argument.\n\n> I do think there's some potential gains in simplicity and robustness\n> that are made mildly harder by a subprocess that first attaches and\n> detaches from shm (it's the only case where we can't easily unify the\n> place InitProcess() is called between EB and ! EB right now). There's\n> several ways that could be tackled. Removing the need to have that if\n> obviously one of them.\n\nHmm, I don't remember that an shmem-unconnected bgworker first connected\nto it and then let go. It seems weird to do it that way. My intention,\nas far as I recall, is that they would just never connect to shmem,\nperiod.\n\n-- \nÁlvaro Herrera 39°49'30\"S 73°17'W — https://www.EnterpriseDB.com/\n\"I think my standards have lowered enough that now I think 'good design'\nis when the page doesn't irritate the living f*ck out of me.\" (JWZ)\n\n\n", "msg_date": "Mon, 2 Aug 2021 15:12:49 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" }, { "msg_contents": "Hi,\n\nOn Mon, Aug 2, 2021, at 12:12, Alvaro Herrera wrote:\n> On 2021-Aug-02, Andres Freund wrote:\n> > I do think there's some potential gains in simplicity and robustness\n> > that are made mildly harder by a subprocess that first attaches and\n> > detaches from shm (it's the only case where we can't easily unify the\n> > place InitProcess() is called between EB and ! EB right now). There's\n> > several ways that could be tackled. Removing the need to have that if\n> > obviously one of them.\n> \n> Hmm, I don't remember that an shmem-unconnected bgworker first connected\n> to it and then let go. It seems weird to do it that way. My intention,\n> as far as I recall, is that they would just never connect to shmem,\n> period.\n\nThey currently do for EXEC_BACKEND. See SubPostmasterMain(). There the definition of the worker is passed via shared memory. So it does the full reattach thing, which requires lwlock, which requires PGPROC. We could get away without that by passing more through the variables file (either the worker definition or the address of the bgworker shmem piece).\n\nGreetings,\n\nAndres\n\n\n", "msg_date": "Mon, 02 Aug 2021 12:17:28 -0700", "msg_from": "\"Andres Freund\" <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" }, { "msg_contents": "On 2021-Aug-02, Andres Freund wrote:\n\n> On Mon, Aug 2, 2021, at 12:12, Alvaro Herrera wrote:\n\n> > Hmm, I don't remember that an shmem-unconnected bgworker first connected\n> > to it and then let go. It seems weird to do it that way. My intention,\n> > as far as I recall, is that they would just never connect to shmem,\n> > period.\n> \n> They currently do for EXEC_BACKEND. See SubPostmasterMain(). There the\n> definition of the worker is passed via shared memory. So it does the\n> full reattach thing, which requires lwlock, which requires PGPROC. We\n> could get away without that by passing more through the variables file\n> (either the worker definition or the address of the bgworker shmem\n> piece).\n\nAh, that makes sense. That doesn't sound super fragile, but it is odd\nand it's probably a good argument for removing the feature, particularly\nsince nobody seems to be using it.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"Ninguna manada de bestias tiene una voz tan horrible como la humana\" (Orual)\n\n\n", "msg_date": "Mon, 2 Aug 2021 15:34:07 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" }, { "msg_contents": "Hi,\n\nOn 2021-08-02 15:34:07 -0400, Alvaro Herrera wrote:\n> Ah, that makes sense. That doesn't sound super fragile, but it is odd\n> and it's probably a good argument for removing the feature, particularly\n> since nobody seems to be using it.\n\nISTM we concluded that we should remove unconnected workers. Writing a patch\nto do so left me with two questions:\n\nFirst, what do we want to do with BGWORKER_SHMEM_ACCESS? I'm inclined to treat\nit as a required flag going forward. That way we don't silently start being\nattached to shared memory in case somebody actually has a unattached\nworker. And if we ever wanted to add the ability to have unattached workers\nback, it'll also be easier this way. Perhaps it also has a small amount of\nsignalling value reminding people that they need to be careful...\n\nThe second question is what we want to do in the backbranches. I think the\nreasonable options are to do nothing, or to make !BGWORKER_SHMEM_ACCESS an\nerror in SanityCheckBackgroundWorker() if EXEC_BACKEND is used.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 5 Aug 2021 16:09:02 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> First, what do we want to do with BGWORKER_SHMEM_ACCESS? I'm inclined to treat\n> it as a required flag going forward.\n\n+1\n\n> The second question is what we want to do in the backbranches. I think the\n> reasonable options are to do nothing, or to make !BGWORKER_SHMEM_ACCESS an\n> error in SanityCheckBackgroundWorker() if EXEC_BACKEND is used.\n\nI think doing nothing is fine. Given the lack of complaints, we're\nmore likely to break something than fix anything useful.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 05 Aug 2021 20:02:02 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" }, { "msg_contents": "Hi,\n\nOn 2021-08-05 20:02:02 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > First, what do we want to do with BGWORKER_SHMEM_ACCESS? I'm inclined to treat\n> > it as a required flag going forward.\n> \n> +1\n> \n> > The second question is what we want to do in the backbranches. I think the\n> > reasonable options are to do nothing, or to make !BGWORKER_SHMEM_ACCESS an\n> > error in SanityCheckBackgroundWorker() if EXEC_BACKEND is used.\n> \n> I think doing nothing is fine. Given the lack of complaints, we're\n> more likely to break something than fix anything useful.\n\nDone in the attached patch. I don't think we need to add more to the docs than\nthe flag being required?\n\nGreetings,\n\nAndres Freund", "msg_date": "Thu, 5 Aug 2021 19:56:49 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" }, { "msg_contents": "On Thu, Aug 5, 2021 at 8:02 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> I think doing nothing is fine. Given the lack of complaints, we're\n> more likely to break something than fix anything useful.\n\n+1.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 9 Aug 2021 11:07:14 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" }, { "msg_contents": "On Mon, Aug 09, 2021 at 11:07:14AM -0400, Robert Haas wrote:\n> On Thu, Aug 5, 2021 at 8:02 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> I think doing nothing is fine. Given the lack of complaints, we're\n>> more likely to break something than fix anything useful.\n> \n> +1.\n\nFWIW, the only interesting case I have in my plugin box for a\nbackground worker that does not attach to shared memory is a template\nof worker able to catch signals, to be used as a base for simple\nactions. So that's not really interesting. Making the SHMEM flag be\nsomething mandatory on HEAD while doing nothing in the back-branches\nsounds good to me, so +1.\n--\nMichael", "msg_date": "Tue, 10 Aug 2021 15:35:35 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" }, { "msg_contents": "On 2021-08-05 19:56:49 -0700, Andres Freund wrote:\n> Done in the attached patch. I don't think we need to add more to the docs than\n> the flag being required?\n\nPushed that patch now. If we want further additions to the docs we can\ndo so separately.\n\n\n", "msg_date": "Fri, 13 Aug 2021 05:53:42 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: EXEC_BACKEND vs bgworkers without BGWORKER_SHMEM_ACCESS" } ]
[ { "msg_contents": "Hi Hackers\n\nWhen review and test another patch at [1], I found some comments in existing test code of \" src/test/regress/sql/publication.sql \" is a little bit confused.\nAttached a patch to fix them, please take a check.\n\nHere is the detail:\n\nExisting code:\nCREATE TABLE testpub_tbl2 (id serial primary key, data text);\n-- fail - can't add to for all tables publication\nALTER PUBLICATION testpub_foralltables ADD TABLE testpub_tbl2;\n-- fail - can't drop from all tables publication\nALTER PUBLICATION testpub_foralltables DROP TABLE testpub_tbl2;\n-- fail - can't add to for all tables publication\nALTER PUBLICATION testpub_foralltables SET TABLE pub_test.testpub_nopk;\n\nAfter patch:\nCREATE TABLE testpub_tbl2 (id serial primary key, data text);\n-- fail - tables can't be added to or dropped form FOR ALL TABLES publications\nALTER PUBLICATION testpub_foralltables ADD TABLE testpub_tbl2;\nALTER PUBLICATION testpub_foralltables DROP TABLE testpub_tbl2;\nALTER PUBLICATION testpub_foralltables SET TABLE pub_test.testpub_nopk;\n\nYou see the comment for SET TABLE is not appropriate.\nAnd above three operations(ADD DROP SET) output the same message as below:\n\"DETAIL: Tables cannot be added to or dropped from FOR ALL TABLES publications.\"\n\nSo maybe we can combine the existing three comments to one, thoughts?\n\nBesides, another comment in the same file is not clear enough to me:\n-- fail - already added\nCREATE PUBLICATION testpub_fortbl FOR TABLE testpub_tbl1;\n\nMaybe it will be better if we use 'already exists'. Thoughts?\n\n[1] https://www.postgresql.org/message-id/OS0PR01MB6113CC160D0F134448567FDDFBE99%40OS0PR01MB6113.jpnprd01.prod.outlook.com\n\nRegards\nTang", "msg_date": "Mon, 2 Aug 2021 10:01:24 +0000", "msg_from": "\"tanghy.fnst@fujitsu.com\" <tanghy.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "[PATCH]Comment improvement in publication.sql" }, { "msg_contents": "On Mon, Aug 2, 2021 at 3:31 PM tanghy.fnst@fujitsu.com\n<tanghy.fnst@fujitsu.com> wrote:\n>\n> Hi Hackers\n>\n> When review and test another patch at [1], I found some comments in existing test code of \" src/test/regress/sql/publication.sql \" is a little bit confused.\n> Attached a patch to fix them, please take a check.\n>\n> Here is the detail:\n>\n> Existing code:\n> CREATE TABLE testpub_tbl2 (id serial primary key, data text);\n> -- fail - can't add to for all tables publication\n> ALTER PUBLICATION testpub_foralltables ADD TABLE testpub_tbl2;\n> -- fail - can't drop from all tables publication\n> ALTER PUBLICATION testpub_foralltables DROP TABLE testpub_tbl2;\n> -- fail - can't add to for all tables publication\n> ALTER PUBLICATION testpub_foralltables SET TABLE pub_test.testpub_nopk;\n>\n> After patch:\n> CREATE TABLE testpub_tbl2 (id serial primary key, data text);\n> -- fail - tables can't be added to or dropped form FOR ALL TABLES publications\n> ALTER PUBLICATION testpub_foralltables ADD TABLE testpub_tbl2;\n> ALTER PUBLICATION testpub_foralltables DROP TABLE testpub_tbl2;\n> ALTER PUBLICATION testpub_foralltables SET TABLE pub_test.testpub_nopk;\n>\n> You see the comment for SET TABLE is not appropriate.\n> And above three operations(ADD DROP SET) output the same message as below:\n> \"DETAIL: Tables cannot be added to or dropped from FOR ALL TABLES publications.\"\n>\n> So maybe we can combine the existing three comments to one, thoughts?\n>\n> Besides, another comment in the same file is not clear enough to me:\n> -- fail - already added\n> CREATE PUBLICATION testpub_fortbl FOR TABLE testpub_tbl1;\n>\n> Maybe it will be better if we use 'already exists'. Thoughts?\n>\n> [1] https://www.postgresql.org/message-id/OS0PR01MB6113CC160D0F134448567FDDFBE99%40OS0PR01MB6113.jpnprd01.prod.outlook.com\n\nFew minor suggestions:\n1) Should we change below to \"fail - tables can't be added, dropped or\nset to \"FOR ALL TABLES\" publications\"\n--- fail - can't add to for all tables publication\n+-- fail - tables can't be added to or dropped from FOR ALL TABLES publications\n\n2) Should we change this to \"--fail - already existing publication\"\n--- fail - already added\n+-- fail - already exists\n\nRegards,\nVignesh\n\n\n", "msg_date": "Mon, 2 Aug 2021 21:26:01 +0530", "msg_from": "vignesh C <vignesh21@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH]Comment improvement in publication.sql" }, { "msg_contents": "On Monday, August 2, 2021 11:56 PM vignesh C <vignesh21@gmail.com> wrote:\r\n> \r\n> Few minor suggestions:\r\n> 1) Should we change below to \"fail - tables can't be added, dropped or\r\n> set to \"FOR ALL TABLES\" publications\"\r\n> --- fail - can't add to for all tables publication\r\n> +-- fail - tables can't be added to or dropped from FOR ALL TABLES publications\r\n\r\nThanks for your kindly comments.\r\n\r\nI'm not sure should we ignore that 'drop' should be followed by 'from', but I\r\nthink there's no misunderstandings. So, modified as you described.\r\n\r\nBesides, in other file comments (src/test/subscription/t/100_bugs.pl) I saw FOR ALL TABLES without using quotes. \r\nSo I don't think we need the quotes, too.\r\n\r\n> 2) Should we change this to \"--fail - already existing publication\"\r\n> --- fail - already added\r\n> +-- fail - already exists\r\n\r\nModified.\r\n\r\nA modified patch is attached.\r\n\r\nRegards\r\nTang", "msg_date": "Tue, 3 Aug 2021 03:06:15 +0000", "msg_from": "\"tanghy.fnst@fujitsu.com\" <tanghy.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [PATCH]Comment improvement in publication.sql" }, { "msg_contents": "On Tue, Aug 3, 2021 at 8:36 AM tanghy.fnst@fujitsu.com\n<tanghy.fnst@fujitsu.com> wrote:\n>\n> On Monday, August 2, 2021 11:56 PM vignesh C <vignesh21@gmail.com> wrote:\n> >\n> > Few minor suggestions:\n> > 1) Should we change below to \"fail - tables can't be added, dropped or\n> > set to \"FOR ALL TABLES\" publications\"\n> > --- fail - can't add to for all tables publication\n> > +-- fail - tables can't be added to or dropped from FOR ALL TABLES publications\n>\n> Thanks for your kindly comments.\n>\n> I'm not sure should we ignore that 'drop' should be followed by 'from', but I\n> think there's no misunderstandings. So, modified as you described.\n>\n> Besides, in other file comments (src/test/subscription/t/100_bugs.pl) I saw FOR ALL TABLES without using quotes.\n> So I don't think we need the quotes, too.\n>\n> > 2) Should we change this to \"--fail - already existing publication\"\n> > --- fail - already added\n> > +-- fail - already exists\n>\n> Modified.\n>\n> A modified patch is attached.\n\nThanks for the updated patch, the changes look good to me.\n\nRegards,\nVignesh\n\n\n", "msg_date": "Tue, 3 Aug 2021 21:27:33 +0530", "msg_from": "vignesh C <vignesh21@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH]Comment improvement in publication.sql" }, { "msg_contents": "Hi\r\n\r\nI saw some inaccurate comments for AlterPublicationStmt structure when\r\nreviewing patches related to publication[1].\r\n\r\nThe variable tables are used for 'ALTER PUBLICATION ... ADD/DROP/SET TABLE',\r\nbut the comments only say 'ADD/DROP'. How about add 'SET' to the comments?\r\n\r\ntypedef struct AlterPublicationStmt\r\n{\r\n\tNodeTag\t\ttype;\r\n\tchar\t *pubname;\t\t/* Name of the publication */\r\n\r\n\t/* parameters used for ALTER PUBLICATION ... WITH */\r\n\tList\t *options;\t\t/* List of DefElem nodes */\r\n\r\n\t/* parameters used for ALTER PUBLICATION ... ADD/DROP TABLE */\r\n\tList\t *tables;\t\t\t/* List of tables to add/drop */\r\n\tbool\t\tfor_all_tables; /* Special publication for all tables in db */\r\n\tDefElemAction tableAction;\t/* What action to perform with the tables */\r\n} AlterPublicationStmt;\r\n\r\nIt's also a comment improvement, so I add this change to this patch.\r\nA new version patch is attached, pleases have a look.\r\n\r\n[1] https://www.postgresql.org/message-id/OS0PR01MB61132C2C4E2232258EB192FDFBF19%40OS0PR01MB6113.jpnprd01.prod.outlook.com\r\n\r\nRegards\r\nTang", "msg_date": "Fri, 6 Aug 2021 10:03:33 +0000", "msg_from": "\"tanghy.fnst@fujitsu.com\" <tanghy.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [PATCH]Comment improvement in publication.sql" }, { "msg_contents": "On Fri, Aug 6, 2021 at 3:33 PM tanghy.fnst@fujitsu.com\n<tanghy.fnst@fujitsu.com> wrote:\n>\n> Hi\n>\n> I saw some inaccurate comments for AlterPublicationStmt structure when\n> reviewing patches related to publication[1].\n>\n> The variable tables are used for 'ALTER PUBLICATION ... ADD/DROP/SET TABLE',\n> but the comments only say 'ADD/DROP'. How about add 'SET' to the comments?\n>\n> typedef struct AlterPublicationStmt\n> {\n> NodeTag type;\n> char *pubname; /* Name of the publication */\n>\n> /* parameters used for ALTER PUBLICATION ... WITH */\n> List *options; /* List of DefElem nodes */\n>\n> /* parameters used for ALTER PUBLICATION ... ADD/DROP TABLE */\n> List *tables; /* List of tables to add/drop */\n> bool for_all_tables; /* Special publication for all tables in db */\n> DefElemAction tableAction; /* What action to perform with the tables */\n> } AlterPublicationStmt;\n>\n> It's also a comment improvement, so I add this change to this patch.\n\nThanks for the updated patch, your changes look good to me. You might\nwant to include the commit message in the patch, that will be useful.\n\nRegards,\nVignesh\n\n\n", "msg_date": "Sun, 8 Aug 2021 15:04:09 +0530", "msg_from": "vignesh C <vignesh21@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH]Comment improvement in publication.sql" }, { "msg_contents": "On Sunday, August 8, 2021 6:34 PM, vignesh C <vignesh21@gmail.com> wrote\r\n>Thanks for the updated patch, your changes look good to me. You might\r\n>want to include the commit message in the patch, that will be useful.\r\n\r\nThanks for your kindly suggestion.\r\nUpdated patch attached. Added the patch commit message with no new fix.\r\n\r\nRegards,\r\nTang", "msg_date": "Sun, 8 Aug 2021 10:56:51 +0000", "msg_from": "\"tanghy.fnst@fujitsu.com\" <tanghy.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [PATCH]Comment improvement in publication.sql" }, { "msg_contents": "On Sun, Aug 8, 2021 at 4:26 PM tanghy.fnst@fujitsu.com\n<tanghy.fnst@fujitsu.com> wrote:\n>\n> On Sunday, August 8, 2021 6:34 PM, vignesh C <vignesh21@gmail.com> wrote\n> >Thanks for the updated patch, your changes look good to me. You might\n> >want to include the commit message in the patch, that will be useful.\n>\n> Thanks for your kindly suggestion.\n> Updated patch attached. Added the patch commit message with no new fix.\n\nThe patch no longer applies, could you post a rebased patch.\n\nRegards,\nVignesh\n\n\n", "msg_date": "Wed, 8 Dec 2021 10:19:25 +0530", "msg_from": "vignesh C <vignesh21@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH]Comment improvement in publication.sql" }, { "msg_contents": "On Wednesday, December 8, 2021 1:49 PM, vignesh C <vignesh21@gmail.com> wrote:\r\n\r\n> The patch no longer applies, could you post a rebased patch.\r\n\r\nThanks for your kindly reminder. Attached a rebased patch.\r\nSome changes in v4 patch has been fixed by 5a28324, so I deleted those changes.\r\n\r\nRegards,\r\nTang", "msg_date": "Wed, 8 Dec 2021 05:37:28 +0000", "msg_from": "\"tanghy.fnst@fujitsu.com\" <tanghy.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [PATCH]Comment improvement in publication.sql" }, { "msg_contents": "On Wed, Dec 8, 2021 at 11:07 AM tanghy.fnst@fujitsu.com\n<tanghy.fnst@fujitsu.com> wrote:\n>\n> On Wednesday, December 8, 2021 1:49 PM, vignesh C <vignesh21@gmail.com> wrote:\n>\n> > The patch no longer applies, could you post a rebased patch.\n>\n> Thanks for your kindly reminder. Attached a rebased patch.\n> Some changes in v4 patch has been fixed by 5a28324, so I deleted those changes.\n\nThanks for the updated patch, should we make a similar change in\nAlterPublicationTables Function header to mention Set too:\n/*\n* Add or remove table to/from publication.\n*/\nstatic void\nAlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup,\nList *tables, List *schemaidlist)\n\nRegards,\nVignesh\n\n\n", "msg_date": "Mon, 13 Dec 2021 21:22:57 +0530", "msg_from": "vignesh C <vignesh21@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH]Comment improvement in publication.sql" }, { "msg_contents": "On Monday, December 13, 2021 11:53 PM vignesh C <vignesh21@gmail.com> wrote:\r\n> \r\n> On Wed, Dec 8, 2021 at 11:07 AM tanghy.fnst@fujitsu.com\r\n> <tanghy.fnst@fujitsu.com> wrote:\r\n> >\r\n> > On Wednesday, December 8, 2021 1:49 PM, vignesh C <vignesh21@gmail.com>\r\n> wrote:\r\n> >\r\n> > > The patch no longer applies, could you post a rebased patch.\r\n> >\r\n> > Thanks for your kindly reminder. Attached a rebased patch.\r\n> > Some changes in v4 patch has been fixed by 5a28324, so I deleted those\r\n> changes.\r\n> \r\n> Thanks for the updated patch, should we make a similar change in\r\n> AlterPublicationTables Function header to mention Set too:\r\n> /*\r\n> * Add or remove table to/from publication.\r\n> */\r\n> static void\r\n> AlterPublicationTables(AlterPublicationStmt *stmt, HeapTuple tup,\r\n> List *tables, List *schemaidlist)\r\n> \r\n\r\nSorry for the late reply.\r\n\r\nI am not sure if we need this change because the way to SET the tables in\r\npublication is that drop tables and then add tables, instead of directly\r\nreplacing the list of tables in the publication. (We can see this point in\r\nAlterPublicationTables function.). Thoughts?\r\n\r\nRegards,\r\nTang\r\n", "msg_date": "Fri, 31 Dec 2021 06:13:00 +0000", "msg_from": "\"tanghy.fnst@fujitsu.com\" <tanghy.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [PATCH]Comment improvement in publication.sql" } ]
[ { "msg_contents": "Hi,\n\nI am currently looking into a partition constraint violation that occurs on update of a partition key on a foreign server. To reproduce it you can run:\n\nOn server 1 using port 5432:\n\ncreate extension postgres_fdw;\ncreate table players (id integer, name text) partition by list(name);\ncreate table players_0 partition of players for values in ('name1');\ncreate server neighbor foreign data wrapper postgres_fdw options (host 'localhost', port '5433', dbname 'postgres');\ncreate foreign table players_1 partition of players for values in ('name2') server neighbor ;\ncreate user mapping for current_user server neighbor;\nOn server 2 using port 5433:\n\ncreate extension postgres_fdw;\ncreate server neighbor foreign data wrapper postgres_fdw options (host 'localhost', port '5432', dbname 'postgres');\ncreate table players (id integer, name text) partition by list(name);\ncreate table players_1 partition of players for values in ('name2');\ncreate user mapping for current_user server neighbor;\ncreate foreign table players_0 partition of players for values in ('name1') server neighbor;\n\ninsert into players values (1, 'name1');\nupdate players set name='name2' where name='name1';\nERROR: new row for relation \"players_0\" violates partition constraint\nDETAIL: Failing row contains (1, name2).\nCONTEXT: remote SQL command: UPDATE public.players_0 SET name = 'name2'::text WHERE ((name = 'name1'::text))\n\nFrom what I have read on the mailing list, I understand that this is a known problem, but I haven't found any thread discussing it in particular. Is this something that needs fixing? If it is, I want to try to do it, but I’m wondering if there are any known caveats and looking for any tips on how to implement it. \n\nMy understanding is that this should be implemented in a similar way to how the row is routed from a local partition in ExecCrossPartitionUpdate, so the update should be replaced with a foreign delete + local/foreign insert. In addition, a direct update should be forbidden when the query modifies the partition key. I’m probably missing a lot of details (feel free to point out), but is the general idea correct? I will be grateful for any feedback.\n\nThanks,\nIlya Gladyshev\n\n\n\n\nHi,I am currently looking into a partition constraint violation\n that occurs on update of a partition key on a foreign server. To reproduce it you can run:On server 1 using port 5432:\n\n create extension postgres_fdw;\n create table players (id integer, name text) partition by\n list(name);\n create table players_0 partition of players for values in\n ('name1');\n create server neighbor foreign data wrapper postgres_fdw options\n (host 'localhost', port '5433', dbname 'postgres');\n create foreign table players_1 partition of players for values in\n ('name2') server neighbor ;\n create user mapping for current_user server neighbor;On server 2 using port 5433:\n create extension postgres_fdw;\n create server neighbor foreign data wrapper postgres_fdw options\n (host 'localhost', port '5432', dbname 'postgres');\n create table players (id integer, name text) partition by\n list(name);\n create table players_1 partition of players for values in\n ('name2');\n create user mapping for current_user server neighbor;\n create foreign table players_0 partition of players for values in\n ('name1') server neighbor;\n insert into players values (1, 'name1');\n update players set name='name2' where name='name1';\n ERROR:  new row for relation \"players_0\" violates partition\n constraint\n DETAIL:  Failing row contains (1, name2).\n CONTEXT:  remote SQL command: UPDATE public.players_0 SET name =\n 'name2'::text WHERE ((name = 'name1'::text))From what I have read on the mailing list, I understand that\n this is a known problem, but I haven't found any thread\n discussing it in particular. Is this something that needs\n fixing? If it is, I want to try to do it, but I’m wondering if\n there are any known caveats and looking for any tips on how to\n implement it. \nMy understanding is that this should be implemented in a\n similar way to how the row is routed from a local partition in\n ExecCrossPartitionUpdate, so the update should be replaced with\n a foreign delete + local/foreign insert. In addition, a direct\n update should be forbidden when the query modifies the partition\n key. I’m probably missing a lot of details (feel free to point out), but is the general idea correct? I will be grateful for any feedback.Thanks,Ilya Gladyshev", "msg_date": "Mon, 2 Aug 2021 15:29:57 +0300", "msg_from": "=?utf-8?B?0JjQu9GM0Y8g0JPQu9Cw0LTRi9GI0LXQsg==?=\n <i.gladyshev@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Update of partition key on foreign server" }, { "msg_contents": "> 2 авг. 2021 г., в 15:29, Илья Гладышев <i.gladyshev@postgrespro.ru> написал(а):\n> \n> Hi,\n> \n> I am currently looking into a partition constraint violation that occurs on update of a partition key on a foreign server. To reproduce it you can run:\n> \n> On server 1 using port 5432:\n> \n> create extension postgres_fdw;\n> create table players (id integer, name text) partition by list(name);\n> create table players_0 partition of players for values in ('name1');\n> create server neighbor foreign data wrapper postgres_fdw options (host 'localhost', port '5433', dbname 'postgres');\n> create foreign table players_1 partition of players for values in ('name2') server neighbor ;\n> create user mapping for current_user server neighbor;\n> On server 2 using port 5433:\n> \n> create extension postgres_fdw;\n> create server neighbor foreign data wrapper postgres_fdw options (host 'localhost', port '5432', dbname 'postgres');\n> create table players (id integer, name text) partition by list(name);\n> create table players_1 partition of players for values in ('name2');\n> create user mapping for current_user server neighbor;\n> create foreign table players_0 partition of players for values in ('name1') server neighbor;\n> \n> insert into players values (1, 'name1');\n> update players set name='name2' where name='name1';\n> ERROR: new row for relation \"players_0\" violates partition constraint\n> DETAIL: Failing row contains (1, name2).\n> CONTEXT: remote SQL command: UPDATE public.players_0 SET name = 'name2'::text WHERE ((name = 'name1'::text))\n> \n> From what I have read on the mailing list, I understand that this is a known problem, but I haven't found any thread discussing it in particular. Is this something that needs fixing? If it is, I want to try to do it, but I’m wondering if there are any known caveats and looking for any tips on how to implement it. \n> \n> My understanding is that this should be implemented in a similar way to how the row is routed from a local partition in ExecCrossPartitionUpdate, so the update should be replaced with a foreign delete + local/foreign insert. In addition, a direct update should be forbidden when the query modifies the partition key. I’m probably missing a lot of details (feel free to point out), but is the general idea correct? I will be grateful for any feedback.\n> \n> Thanks,\n> Ilya Gladyshev\n\nI have developed a simple patch to fix this, while I’m not fully satisfied with it, it gets the job done. From what I have read in the docs, partition constraints are currently not checked for foreign tables, because they must be enforced on the remote server anyway (because there might be many other ways to access the data source besides FDW), and thus there’s no point in doing that locally. However, in the case of foreign partition update, checking the constraints locally can be used to allow for routing from remote sources, so I don’t feel like this point is valid in this case. \n\nIn message [1] there’s also mentioned possibility of existence of triggers on the foreign server, and transforming the update to delete+insert will cause these triggers to be omitted. While it is true, I feel like partition pruning already has a similar effect, as it allows to skip scanning foreign partitions. The only way to both fix the update and have the triggers work, that I came up with, is to use parent partitioned table as a target for the foreign update (FDW request would then be \"UPDATE public.players …\"), while this is possible, it requires the foreign server to have the same partitioned table, which seems quite restrictive to me. Please let me know if I’m missing something or there is a better way to do it.\n\nThanks,\nIlya Gladyshev\n\n[1] https://www.postgresql.org/message-id/5A93F487.4080602%40lab.ntt.co.jp <https://www.postgresql.org/message-id/5A93F487.4080602@lab.ntt.co.jp>", "msg_date": "Thu, 26 Aug 2021 17:10:25 +0300", "msg_from": "Ilya Gladyshev <i.gladyshev@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Update of partition key on foreign server" }, { "msg_contents": "On Thu, Aug 26, 2021 at 11:10 PM Ilya Gladyshev\n<i.gladyshev@postgrespro.ru> wrote:\n> I have developed a simple patch to fix this, while I’m not fully satisfied with it, it gets the job done.\n\nThanks for working on this!\n\n> In message [1] there’s also mentioned possibility of existence of triggers on the foreign server, and transforming the update to delete+insert will cause these triggers to be omitted.\n\nYeah, I still think so.\n\n> While it is true, I feel like partition pruning already has a similar effect, as it allows to skip scanning foreign partitions.\n\nI don’t fully understand this part. Could you elaborate a bit more on it?\n\n> The only way to both fix the update and have the triggers work, that I came up with, is to use parent partitioned table as a target for the foreign update (FDW request would then be \"UPDATE public.players …\"), while this is possible, it requires the foreign server to have the same partitioned table, which seems quite restrictive to me.\n\nYeah, that would be too restrictive.\n\nBest regards,\nEtsuro Fujita\n\n\n", "msg_date": "Wed, 1 Sep 2021 20:59:56 +0900", "msg_from": "Etsuro Fujita <etsuro.fujita@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Update of partition key on foreign server" } ]
[ { "msg_contents": "Hi hackers,\n\nWhen testing some other logical replication related patches, I found two\nunexpected behaviours about ALTER SUBSCRIPTION ADD/DROP PUBLICATION.\n\n(1)\nwhen I execute the following sqls[1], the data of tables that registered to\n'pub' wasn't copied to the subscriber side which means tablesync worker didn't\nstart.\n\n-----sub originally had 2 pub nodes(pub,pub2)\nALTER SUBSCRIPTION sub drop PUBLICATION pub;\nALTER SUBSCRIPTION sub add PUBLICATION pub;\n-----\n\n(2)\nAnd when I execute the following sqls, the data of table registered to 'pub2'\nare synced again.\n\n-----sub originally had 2 pub nodes(pub,pub2)\nALTER SUBSCRIPTION sub drop PUBLICATION pub;\nALTER SUBSCRIPTION sub REFRESH PUBLICATION;\n-----\n\nAfter looking into this problem, I think the reason is the\n[alter sub add/drop publication] misused the function\nAlterSubscription_refresh().\n\nFor DROP cases:\n\nCurrently, in function AlterSubscription_refresh(), it will first fetch the\ntarget tables from the target publication, and also fetch the tables in\nsubscriber side from pg_subscription_rel. Then it will check each table from\nlocal pg_subscription_rel, if the table does not exists in the tables fetched\nfrom the target publication then drop it.\n\nThe logic above only works for SET PUBLICATION. However, When DROP PUBLICATION,\nthe tables fetched from target publication is actually the tables that need to\nbe dropped. If reuse the above logic, it will drop the wrong table which result\nin unexpected behavioud in (1) and (2).(ADD PUBLICATION have similar problem).\n\nSo, I think we'd better fix this problem. I tried add some additional check in\nAlterSubscription_refresh() which can avoid the problem like the attached\npatch. Not sure do we need to further refactor.\n\nBest regards,\nhouzj", "msg_date": "Mon, 2 Aug 2021 13:52:09 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "[BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "Hi,\n\nOn Mon, Aug 2, 2021 at 10:52 PM houzj.fnst@fujitsu.com\n<houzj.fnst@fujitsu.com> wrote:\n>\n>\n> Hi hackers,\n>\n> When testing some other logical replication related patches, I found two\n> unexpected behaviours about ALTER SUBSCRIPTION ADD/DROP PUBLICATION.\n>\n> (1)\n> when I execute the following sqls[1], the data of tables that registered to\n> 'pub' wasn't copied to the subscriber side which means tablesync worker didn't\n> start.\n>\n> -----sub originally had 2 pub nodes(pub,pub2)\n> ALTER SUBSCRIPTION sub drop PUBLICATION pub;\n> ALTER SUBSCRIPTION sub add PUBLICATION pub;\n> -----\n>\n> (2)\n> And when I execute the following sqls, the data of table registered to 'pub2'\n> are synced again.\n>\n> -----sub originally had 2 pub nodes(pub,pub2)\n> ALTER SUBSCRIPTION sub drop PUBLICATION pub;\n> ALTER SUBSCRIPTION sub REFRESH PUBLICATION;\n> -----\n\nI could reproduce this issue by the above steps.\n\n>\n> After looking into this problem, I think the reason is the\n> [alter sub add/drop publication] misused the function\n> AlterSubscription_refresh().\n>\n> For DROP cases:\n>\n> Currently, in function AlterSubscription_refresh(), it will first fetch the\n> target tables from the target publication, and also fetch the tables in\n> subscriber side from pg_subscription_rel. Then it will check each table from\n> local pg_subscription_rel, if the table does not exists in the tables fetched\n> from the target publication then drop it.\n>\n> The logic above only works for SET PUBLICATION. However, When DROP PUBLICATION,\n> the tables fetched from target publication is actually the tables that need to\n> be dropped. If reuse the above logic, it will drop the wrong table which result\n> in unexpected behavioud in (1) and (2).(ADD PUBLICATION have similar problem).\n\nYes. For example, suppose that the publisher has two publications pub1\nand pub2 for table1 and table2, respecitively. And we create a\nsubscription subscribing to those two publications.\n\npostgres(1:74454)=# \\dRs sub\n List of subscriptions\n Name | Owner | Enabled | Publication\n------+----------+---------+-------------\n sub | masahiko | t | {pub1,pub2}\n(1 row)\n\npostgres(1:74454)=# select srsubid, srrelid::regclass::text,\nsrsubstate, srsublsn from pg_subscription_rel;\n srsubid | srrelid | srsubstate | srsublsn\n---------+---------+------------+-----------\n 16394 | table1 | r | 0/170F388\n 16394 | table2 | r | 0/170F388\n(2 rows)\n\nAfter dropping pub1 from the subscription, 'table2' associated with\n'pub2' is removed:\n\npostgres(1:74454)=# alter subscription sub drop publication pub1;\nALTER SUBSCRIPTION\npostgres(1:74454)=# select srsubid, srrelid::regclass::text,\nsrsubstate, srsublsn from pg_subscription_rel;\n srsubid | srrelid | srsubstate | srsublsn\n---------+---------+------------+-----------\n 16394 | table1 | r | 0/170F388\n(1 row)\n\n> So, I think we'd better fix this problem. I tried add some additional check in\n> AlterSubscription_refresh() which can avoid the problem like the attached\n> patch. Not sure do we need to further refactor.\n\nI've not looked at the patch deeply yet but I think that the following\none line change seems to fix the cases you reported, although I migit\nbe missing something:\n\ndiff --git a/src/backend/commands/subscriptioncmds.c\nb/src/backend/commands/subscriptioncmds.c\nindex 22ae982328..c74d6d51d6 100644\n--- a/src/backend/commands/subscriptioncmds.c\n+++ b/src/backend/commands/subscriptioncmds.c\n@@ -1068,7 +1068,7 @@ AlterSubscription(ParseState *pstate,\nAlterSubscriptionStmt *stmt,\n PreventInTransactionBlock(isTopLevel, \"ALTER\nSUBSCRIPTION with refresh\");\n\n /* Only refresh the added/dropped list of publications. */\n- sub->publications = stmt->publication;\n+ sub->publications = publist;\n\n AlterSubscription_refresh(sub, opts.copy_data);\n }\n\nAlso, I think we need to add some regression tests for this.\nCurrently, subscription.sql has tests for ADD/DROP PUBLICATION but\nthey don't check pg_subscription_rel.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Wed, 4 Aug 2021 14:47:05 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Wednesday, August 4, 2021 1:47 PM Masahiko Sawada <sawada.mshk@gmail.com>\r\n> On Mon, Aug 2, 2021 at 10:52 PM houzj.fnst@fujitsu.com\r\n> <houzj.fnst@fujitsu.com> wrote:\r\n> >\r\n> >\r\n> > Hi hackers,\r\n> >\r\n> > When testing some other logical replication related patches, I found\r\n> > two unexpected behaviours about ALTER SUBSCRIPTION ADD/DROP\r\n> PUBLICATION.\r\n> >\r\n> > (1)\r\n> > when I execute the following sqls[1], the data of tables that\r\n> > registered to 'pub' wasn't copied to the subscriber side which means\r\n> > tablesync worker didn't start.\r\n> >\r\n> > -----sub originally had 2 pub nodes(pub,pub2) ALTER SUBSCRIPTION sub\r\n> > drop PUBLICATION pub; ALTER SUBSCRIPTION sub add PUBLICATION pub;\r\n> > -----\r\n> >\r\n> > (2)\r\n> > And when I execute the following sqls, the data of table registered to 'pub2'\r\n> > are synced again.\r\n> >\r\n> > -----sub originally had 2 pub nodes(pub,pub2) ALTER SUBSCRIPTION sub\r\n> > drop PUBLICATION pub; ALTER SUBSCRIPTION sub REFRESH PUBLICATION;\r\n> > -----\r\n> \r\n> I could reproduce this issue by the above steps.\r\n\r\nThanks for looking into this problem.\r\n\r\n> \r\n> I've not looked at the patch deeply yet but I think that the following one line\r\n> change seems to fix the cases you reported, although I migit be missing\r\n> something:\r\n> \r\n> diff --git a/src/backend/commands/subscriptioncmds.c\r\n> b/src/backend/commands/subscriptioncmds.c\r\n> index 22ae982328..c74d6d51d6 100644\r\n> --- a/src/backend/commands/subscriptioncmds.c\r\n> +++ b/src/backend/commands/subscriptioncmds.c\r\n> @@ -1068,7 +1068,7 @@ AlterSubscription(ParseState *pstate,\r\n> AlterSubscriptionStmt *stmt,\r\n> PreventInTransactionBlock(isTopLevel, \"ALTER\r\n> SUBSCRIPTION with refresh\");\r\n> \r\n> /* Only refresh the added/dropped list of publications. */\r\n> - sub->publications = stmt->publication;\r\n> + sub->publications = publist;\r\n> \r\n> AlterSubscription_refresh(sub, opts.copy_data);\r\n> }\r\n\r\nI considered the same fix before, but with the above fix, it seems refresh both\r\nexistsing publications and new publication, which most of people didn't like in\r\nprevious discussion[1]. From the doc[2], IIRC, Currently, the ADD/DROP\r\nPUBLICATION is supposed to only refresh the new publication.\r\n\r\n[1] https://www.postgresql.org/message-id/MEYP282MB166921C8622675A5C0701C31B6BB0%40MEYP282MB1669.AUSP282.PROD.OUTLOOK.COM\r\n\r\n[2] https://www.postgresql.org/docs/14/sql-altersubscription.html\r\nBy default, this command will also act like REFRESH PUBLICATION, except that in\r\ncase of ADD or DROP, only the added or dropped publications are refreshed.\r\n\r\n> Also, I think we need to add some regression tests for this.\r\n> Currently, subscription.sql has tests for ADD/DROP PUBLICATION but they don't\r\n> check pg_subscription_rel.\r\n\r\nCurrently, the subscription.sql doesn't have actual tables to\r\nbe subscribed which means the pg_subscription_rel is empty. I am not sure where\r\nto place the testcases, temporarily placed in 001_rep_changes.pl.\r\n\r\nBest regards,\r\nhouzj", "msg_date": "Wed, 4 Aug 2021 08:06:53 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Wed, Aug 4, 2021 at 5:06 PM houzj.fnst@fujitsu.com\n<houzj.fnst@fujitsu.com> wrote:\n>\n> On Wednesday, August 4, 2021 1:47 PM Masahiko Sawada <sawada.mshk@gmail.com>\n> > On Mon, Aug 2, 2021 at 10:52 PM houzj.fnst@fujitsu.com\n> > <houzj.fnst@fujitsu.com> wrote:\n> > >\n> > >\n> > > Hi hackers,\n> > >\n> > > When testing some other logical replication related patches, I found\n> > > two unexpected behaviours about ALTER SUBSCRIPTION ADD/DROP\n> > PUBLICATION.\n> > >\n> > > (1)\n> > > when I execute the following sqls[1], the data of tables that\n> > > registered to 'pub' wasn't copied to the subscriber side which means\n> > > tablesync worker didn't start.\n> > >\n> > > -----sub originally had 2 pub nodes(pub,pub2) ALTER SUBSCRIPTION sub\n> > > drop PUBLICATION pub; ALTER SUBSCRIPTION sub add PUBLICATION pub;\n> > > -----\n> > >\n> > > (2)\n> > > And when I execute the following sqls, the data of table registered to 'pub2'\n> > > are synced again.\n> > >\n> > > -----sub originally had 2 pub nodes(pub,pub2) ALTER SUBSCRIPTION sub\n> > > drop PUBLICATION pub; ALTER SUBSCRIPTION sub REFRESH PUBLICATION;\n> > > -----\n> >\n> > I could reproduce this issue by the above steps.\n>\n> Thanks for looking into this problem.\n>\n> >\n> > I've not looked at the patch deeply yet but I think that the following one line\n> > change seems to fix the cases you reported, although I migit be missing\n> > something:\n> >\n> > diff --git a/src/backend/commands/subscriptioncmds.c\n> > b/src/backend/commands/subscriptioncmds.c\n> > index 22ae982328..c74d6d51d6 100644\n> > --- a/src/backend/commands/subscriptioncmds.c\n> > +++ b/src/backend/commands/subscriptioncmds.c\n> > @@ -1068,7 +1068,7 @@ AlterSubscription(ParseState *pstate,\n> > AlterSubscriptionStmt *stmt,\n> > PreventInTransactionBlock(isTopLevel, \"ALTER\n> > SUBSCRIPTION with refresh\");\n> >\n> > /* Only refresh the added/dropped list of publications. */\n> > - sub->publications = stmt->publication;\n> > + sub->publications = publist;\n> >\n> > AlterSubscription_refresh(sub, opts.copy_data);\n> > }\n>\n> I considered the same fix before, but with the above fix, it seems refresh both\n> existsing publications and new publication, which most of people didn't like in\n> previous discussion[1]. From the doc[2], IIRC, Currently, the ADD/DROP\n> PUBLICATION is supposed to only refresh the new publication.\n\nWhat do you mean by refreshing both existing and new publications? I\ndropped and created one publication out of three publications that the\nsubscription is subscribing to but the corresponding entries in\npg_subscription_rel for tables associated with the other two\npublications were not changed and the table sync workers also were not\nstarted for them.\n\n>\n> > Also, I think we need to add some regression tests for this.\n> > Currently, subscription.sql has tests for ADD/DROP PUBLICATION but they don't\n> > check pg_subscription_rel.\n>\n> Currently, the subscription.sql doesn't have actual tables to\n> be subscribed which means the pg_subscription_rel is empty. I am not sure where\n> to place the testcases, temporarily placed in 001_rep_changes.pl.\n\nRight. Adding tests to 001_rep_changes.pl seems good to me.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Wed, 4 Aug 2021 19:59:55 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Wednesday, August 4, 2021 7:00 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote\r\n> On Wed, Aug 4, 2021 at 5:06 PM houzj.fnst@fujitsu.com <houzj.fnst@fujitsu.com> wrote:\r\n> >\r\n> > On Wednesday, August 4, 2021 1:47 PM Masahiko Sawada <sawada.mshk@gmail.com>\r\n> > >\r\n> > > I've not looked at the patch deeply yet but I think that the\r\n> > > following one line change seems to fix the cases you reported,\r\n> > > although I migit be missing\r\n> > > something:\r\n> > >\r\n> > > diff --git a/src/backend/commands/subscriptioncmds.c\r\n> > > b/src/backend/commands/subscriptioncmds.c\r\n> > > index 22ae982328..c74d6d51d6 100644\r\n> > > --- a/src/backend/commands/subscriptioncmds.c\r\n> > > +++ b/src/backend/commands/subscriptioncmds.c\r\n> > > @@ -1068,7 +1068,7 @@ AlterSubscription(ParseState *pstate,\r\n> > > AlterSubscriptionStmt *stmt,\r\n> > > PreventInTransactionBlock(isTopLevel, \"ALTER\r\n> > > SUBSCRIPTION with refresh\");\r\n> > >\r\n> > > /* Only refresh the added/dropped list of publications.\r\n> */\r\n> > > - sub->publications = stmt->publication;\r\n> > > + sub->publications = publist;\r\n> > >\r\n> > > AlterSubscription_refresh(sub, opts.copy_data);\r\n> > > }\r\n> >\r\n> > I considered the same fix before, but with the above fix, it seems\r\n> > refresh both existsing publications and new publication, which most of\r\n> > people didn't like in previous discussion[1]. From the doc[2], IIRC,\r\n> > Currently, the ADD/DROP PUBLICATION is supposed to only refresh the new\r\n> publication.\r\n> \r\n> What do you mean by refreshing both existing and new publications? I dropped\r\n> and created one publication out of three publications that the subscription is\r\n> subscribing to but the corresponding entries in pg_subscription_rel for tables\r\n> associated with the other two publications were not changed and the table sync\r\n> workers also were not started for them.\r\n> \r\n\r\n+ sub->publications = publist;\r\n- sub->publications = stmt->publication;\r\nWith the above fix, When ADD/DROP PUBLICATION, I meant the table that doesn't\r\nbelong to the dropped or added publication could be updated in\r\npg_subscription_rel.\r\n\r\nI can see the effect in the following example:\r\n\r\n1)-publisher-\r\nCREATE TABLE test,test2,test3\r\nCREATE PUBLICATION pub FOR TABLE test;\r\nCREATE PUBLICATION pub2 FOR TABLE test2;\r\n2)-subscriber-\r\nCREATE TABLE test,test2,test3\r\nCREATE SUBSCRIPTION sub CONNECTION 'dbname=postgres port=10000' PUBLICATION pub,pub2;\r\nselect * from pg_subscription_rel;\r\n-[ RECORD 1 ]---------\r\nsrsubid | 16393\r\nsrrelid | 16387\r\nsrsubstate | r\r\nsrsublsn | 0/150A2D8\r\n-[ RECORD 2 ]---------\r\nsrsubid | 16393\r\nsrrelid | 16384\r\nsrsubstate | r\r\nsrsublsn | 0/150A310\r\n\r\n3)-publisher-\r\nalter publication pub add table test3;\r\n4)-subscriber-\r\nALTER SUBSCRIPTION sub drop PUBLICATION pub2;\r\nselect * from pg_subscription_rel;\r\n-[ RECORD 1 ]---------\r\nsrsubid | 16393\r\nsrrelid | 16384\r\nsrsubstate | r\r\nsrsublsn | 0/150A310\r\n-[ RECORD 2 ]---------\r\nsrsubid | 16393\r\nsrrelid | 16390\r\nsrsubstate | r\r\nsrsublsn |\r\n\r\nI can see the [RECORD 2] which is the new registered table in 'pub2' (see step 3)\r\nhas been added to the pg_subscription_rel. Based pervious discussion and\r\ndocument, that table seems shouldn't be refreshed when drop another\r\npublication.\r\n\r\nBest regards,\r\nhouzj\r\n", "msg_date": "Wed, 4 Aug 2021 12:19:54 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Wed, Aug 4, 2021 at 9:19 PM houzj.fnst@fujitsu.com\n<houzj.fnst@fujitsu.com> wrote:\n>\n> On Wednesday, August 4, 2021 7:00 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote\n> > On Wed, Aug 4, 2021 at 5:06 PM houzj.fnst@fujitsu.com <houzj.fnst@fujitsu.com> wrote:\n> > >\n> > > On Wednesday, August 4, 2021 1:47 PM Masahiko Sawada <sawada.mshk@gmail.com>\n> > > >\n> > > > I've not looked at the patch deeply yet but I think that the\n> > > > following one line change seems to fix the cases you reported,\n> > > > although I migit be missing\n> > > > something:\n> > > >\n> > > > diff --git a/src/backend/commands/subscriptioncmds.c\n> > > > b/src/backend/commands/subscriptioncmds.c\n> > > > index 22ae982328..c74d6d51d6 100644\n> > > > --- a/src/backend/commands/subscriptioncmds.c\n> > > > +++ b/src/backend/commands/subscriptioncmds.c\n> > > > @@ -1068,7 +1068,7 @@ AlterSubscription(ParseState *pstate,\n> > > > AlterSubscriptionStmt *stmt,\n> > > > PreventInTransactionBlock(isTopLevel, \"ALTER\n> > > > SUBSCRIPTION with refresh\");\n> > > >\n> > > > /* Only refresh the added/dropped list of publications.\n> > */\n> > > > - sub->publications = stmt->publication;\n> > > > + sub->publications = publist;\n> > > >\n> > > > AlterSubscription_refresh(sub, opts.copy_data);\n> > > > }\n> > >\n> > > I considered the same fix before, but with the above fix, it seems\n> > > refresh both existsing publications and new publication, which most of\n> > > people didn't like in previous discussion[1]. From the doc[2], IIRC,\n> > > Currently, the ADD/DROP PUBLICATION is supposed to only refresh the new\n> > publication.\n> >\n> > What do you mean by refreshing both existing and new publications? I dropped\n> > and created one publication out of three publications that the subscription is\n> > subscribing to but the corresponding entries in pg_subscription_rel for tables\n> > associated with the other two publications were not changed and the table sync\n> > workers also were not started for them.\n> >\n>\n> + sub->publications = publist;\n> - sub->publications = stmt->publication;\n> With the above fix, When ADD/DROP PUBLICATION, I meant the table that doesn't\n> belong to the dropped or added publication could be updated in\n> pg_subscription_rel.\n>\n> I can see the effect in the following example:\n>\n> 1)-publisher-\n> CREATE TABLE test,test2,test3\n> CREATE PUBLICATION pub FOR TABLE test;\n> CREATE PUBLICATION pub2 FOR TABLE test2;\n> 2)-subscriber-\n> CREATE TABLE test,test2,test3\n> CREATE SUBSCRIPTION sub CONNECTION 'dbname=postgres port=10000' PUBLICATION pub,pub2;\n> select * from pg_subscription_rel;\n> -[ RECORD 1 ]---------\n> srsubid | 16393\n> srrelid | 16387\n> srsubstate | r\n> srsublsn | 0/150A2D8\n> -[ RECORD 2 ]---------\n> srsubid | 16393\n> srrelid | 16384\n> srsubstate | r\n> srsublsn | 0/150A310\n>\n> 3)-publisher-\n> alter publication pub add table test3;\n> 4)-subscriber-\n> ALTER SUBSCRIPTION sub drop PUBLICATION pub2;\n> select * from pg_subscription_rel;\n> -[ RECORD 1 ]---------\n> srsubid | 16393\n> srrelid | 16384\n> srsubstate | r\n> srsublsn | 0/150A310\n> -[ RECORD 2 ]---------\n> srsubid | 16393\n> srrelid | 16390\n> srsubstate | r\n> srsublsn |\n>\n> I can see the [RECORD 2] which is the new registered table in 'pub2' (see step 3)\n> has been added to the pg_subscription_rel. Based pervious discussion and\n> document, that table seems shouldn't be refreshed when drop another\n> publication.\n\nThanks for the explanation! I understood the problem.\n\nI've reviewed v2 patch. Here are some comments:\n\n+ if (type == ALTER_SUBSCRIPTION_SET_PUBLICATION ||\n+ type == ALTER_SUBSCRIPTION_REFRESH)\n+ drop_table = !bsearch(&relid, pubrel_local_oids,\n+ list_length(pubrel_names),\n+ sizeof(Oid), oid_cmp);\n+ else if (type == ALTER_SUBSCRIPTION_DROP_PUBLICATION)\n+ drop_table = bsearch(&relid, pubrel_local_oids,\n+ list_length(pubrel_names),\n+ sizeof(Oid), oid_cmp);\n\nIIUC, in DROP PUBLICATION cases, we don't need to refer to the tables\nin the publication on the publisher that we're dropping in order to\ncheck whether to remove the relation. If we drop a table from the\npublication on the publisher before dropping the publication from the\nsubscription on the subscriber, the pg_subscription_rel entry for the\ntable remains. For example, please consider the following case:\n\nOn publisher and subscriber:\ncreate table t1 (a int);\ncreate table t2 (a int);\ncreate table t3 (a int);\n\nOn publisher:\ncreate publication pub12 for table t1, t2;\ncreate publication pub3 for table t3;\n\nOn subscriber:\ncreate subscription sub connection 'dbname=postgres' publication pub12, pub3;\n\nOn publisher:\nalter publication pub12 drop table t2;\n\nOn subscriber:\nalter subscription sub drop publication pub12;\nselect srsubid, srrelid::regclass::text, srsubstate, srsublsn from\npg_subscription_rel;\n\n srsubid | srrelid | srsubstate | srsublsn\n---------+---------+------------+-----------\n 16393 | t3 | r | 0/1707CE0\n 16393 | t2 | r | 0/1707CE0\n\nWith v2 patch, the pg_subscription_rel has the entry for 't2' but it\nshould not exist.\n\nBut that doesn't mean that drop_table should always be true in DROP\nPULIBCATION cases. Since the tables associated with two publications\ncan overlap, we cannot remove the relation from pg_subscription_rel if\nit is also associated with the remaining publication. For example:\n\nOn publisher and subscriber:\ncreate table t1 (a int);\ncreate table t2 (a int);\ncreate table t3 (a int);\n\nOn publisher:\ncreate publication pub12 for table t1, t2;\ncreate publication pub13 for table t1, t3;\n\nOn subscriber:\ncreate subscription sub connection 'dbname=postgres' publication pub12, pub13;\n\nOn subscriber:\nalter subscription sub drop publication pub12;\nselect srsubid, srrelid::regclass::text, srsubstate, srsublsn from\npg_subscription_rel;\n srsubid | srrelid | srsubstate | srsublsn\n---------+---------+------------+-----------\n 16393 | t3 | r | 0/17080B0\n(1 row)\n\nWith v2 patch, the pg_subscription_rel has only one entry for t3 but\nit should have also the one for t1 since it's still subscribing to\npub13.\n\nTo summary, I think that what we want to do in DROP SUBSCRIPTION cases\nis to drop relations from pg_subscription_rel that are no longer\nincluded in the set of after-calculated publications. In the latter\nexample, when ALTER SUBSCRIPTION ... DROP PUBLICATION pub12, we should\ncompare the current set of relations associated with {pub12, pub13} to\nthe set of relcations associated with pub13, not pub12. Then we can\nfind out t2 is no longer associated with the after-calculated\npublication (i.g., pub13) so remove it.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Thu, 5 Aug 2021 14:08:57 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Thu, Aug 5, 2021 at 2:08 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Wed, Aug 4, 2021 at 9:19 PM houzj.fnst@fujitsu.com\n> <houzj.fnst@fujitsu.com> wrote:\n> >\n> > On Wednesday, August 4, 2021 7:00 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote\n> > > On Wed, Aug 4, 2021 at 5:06 PM houzj.fnst@fujitsu.com <houzj.fnst@fujitsu.com> wrote:\n> > > >\n> > > > On Wednesday, August 4, 2021 1:47 PM Masahiko Sawada <sawada.mshk@gmail.com>\n> > > > >\n> > > > > I've not looked at the patch deeply yet but I think that the\n> > > > > following one line change seems to fix the cases you reported,\n> > > > > although I migit be missing\n> > > > > something:\n> > > > >\n> > > > > diff --git a/src/backend/commands/subscriptioncmds.c\n> > > > > b/src/backend/commands/subscriptioncmds.c\n> > > > > index 22ae982328..c74d6d51d6 100644\n> > > > > --- a/src/backend/commands/subscriptioncmds.c\n> > > > > +++ b/src/backend/commands/subscriptioncmds.c\n> > > > > @@ -1068,7 +1068,7 @@ AlterSubscription(ParseState *pstate,\n> > > > > AlterSubscriptionStmt *stmt,\n> > > > > PreventInTransactionBlock(isTopLevel, \"ALTER\n> > > > > SUBSCRIPTION with refresh\");\n> > > > >\n> > > > > /* Only refresh the added/dropped list of publications.\n> > > */\n> > > > > - sub->publications = stmt->publication;\n> > > > > + sub->publications = publist;\n> > > > >\n> > > > > AlterSubscription_refresh(sub, opts.copy_data);\n> > > > > }\n> > > >\n> > > > I considered the same fix before, but with the above fix, it seems\n> > > > refresh both existsing publications and new publication, which most of\n> > > > people didn't like in previous discussion[1]. From the doc[2], IIRC,\n> > > > Currently, the ADD/DROP PUBLICATION is supposed to only refresh the new\n> > > publication.\n> > >\n> > > What do you mean by refreshing both existing and new publications? I dropped\n> > > and created one publication out of three publications that the subscription is\n> > > subscribing to but the corresponding entries in pg_subscription_rel for tables\n> > > associated with the other two publications were not changed and the table sync\n> > > workers also were not started for them.\n> > >\n> >\n> > + sub->publications = publist;\n> > - sub->publications = stmt->publication;\n> > With the above fix, When ADD/DROP PUBLICATION, I meant the table that doesn't\n> > belong to the dropped or added publication could be updated in\n> > pg_subscription_rel.\n> >\n> > I can see the effect in the following example:\n> >\n> > 1)-publisher-\n> > CREATE TABLE test,test2,test3\n> > CREATE PUBLICATION pub FOR TABLE test;\n> > CREATE PUBLICATION pub2 FOR TABLE test2;\n> > 2)-subscriber-\n> > CREATE TABLE test,test2,test3\n> > CREATE SUBSCRIPTION sub CONNECTION 'dbname=postgres port=10000' PUBLICATION pub,pub2;\n> > select * from pg_subscription_rel;\n> > -[ RECORD 1 ]---------\n> > srsubid | 16393\n> > srrelid | 16387\n> > srsubstate | r\n> > srsublsn | 0/150A2D8\n> > -[ RECORD 2 ]---------\n> > srsubid | 16393\n> > srrelid | 16384\n> > srsubstate | r\n> > srsublsn | 0/150A310\n> >\n> > 3)-publisher-\n> > alter publication pub add table test3;\n> > 4)-subscriber-\n> > ALTER SUBSCRIPTION sub drop PUBLICATION pub2;\n> > select * from pg_subscription_rel;\n> > -[ RECORD 1 ]---------\n> > srsubid | 16393\n> > srrelid | 16384\n> > srsubstate | r\n> > srsublsn | 0/150A310\n> > -[ RECORD 2 ]---------\n> > srsubid | 16393\n> > srrelid | 16390\n> > srsubstate | r\n> > srsublsn |\n> >\n> > I can see the [RECORD 2] which is the new registered table in 'pub2' (see step 3)\n> > has been added to the pg_subscription_rel. Based pervious discussion and\n> > document, that table seems shouldn't be refreshed when drop another\n> > publication.\n>\n> Thanks for the explanation! I understood the problem.\n>\n> I've reviewed v2 patch. Here are some comments:\n\nRegarding regression tests, since ADD/DROP PUBLICATION logic could be\ncomplicated it seems to me that we can add tests to a new file, say\nalter_sub_pub.pl, that includes some scenarios as I mentioned in the\nprevious message.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Thu, 5 Aug 2021 14:23:09 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Thursday, August 5, 2021 1:09 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote\r\n> I've reviewed v2 patch. Here are some comments:\r\n> \r\n> + if (type == ALTER_SUBSCRIPTION_SET_PUBLICATION ||\r\n> + type == ALTER_SUBSCRIPTION_REFRESH)\r\n> + drop_table = !bsearch(&relid, pubrel_local_oids,\r\n> + list_length(pubrel_names),\r\n> + sizeof(Oid), oid_cmp);\r\n> + else if (type == ALTER_SUBSCRIPTION_DROP_PUBLICATION)\r\n> + drop_table = bsearch(&relid, pubrel_local_oids,\r\n> + list_length(pubrel_names),\r\n> + sizeof(Oid), oid_cmp);\r\n> \r\n> IIUC, in DROP PUBLICATION cases, we don't need to refer to the tables in the\r\n> publication on the publisher that we're dropping in order to check whether to\r\n> remove the relation. If we drop a table from the publication on the publisher\r\n> before dropping the publication from the subscription on the subscriber, the\r\n> pg_subscription_rel entry for the table remains. For example, please consider the\r\n> following case:\r\n> \r\n> On publisher and subscriber:\r\n> create table t1 (a int);\r\n> create table t2 (a int);\r\n> create table t3 (a int);\r\n> \r\n> On publisher:\r\n> create publication pub12 for table t1, t2; create publication pub3 for table t3;\r\n> \r\n> On subscriber:\r\n> create subscription sub connection 'dbname=postgres' publication pub12, pub3;\r\n> \r\n> On publisher:\r\n> alter publication pub12 drop table t2;\r\n> \r\n> On subscriber:\r\n> alter subscription sub drop publication pub12; select srsubid,\r\n> srrelid::regclass::text, srsubstate, srsublsn from pg_subscription_rel;\r\n> \r\n> srsubid | srrelid | srsubstate | srsublsn\r\n> ---------+---------+------------+-----------\r\n> 16393 | t3 | r | 0/1707CE0\r\n> 16393 | t2 | r | 0/1707CE0\r\n> \r\n> With v2 patch, the pg_subscription_rel has the entry for 't2' but it should not\r\n> exist.\r\n> \r\n> But that doesn't mean that drop_table should always be true in DROP\r\n> PULIBCATION cases. Since the tables associated with two publications can\r\n> overlap, we cannot remove the relation from pg_subscription_rel if it is also\r\n> associated with the remaining publication. For example:\r\n> \r\n> On publisher and subscriber:\r\n> create table t1 (a int);\r\n> create table t2 (a int);\r\n> create table t3 (a int);\r\n> \r\n> On publisher:\r\n> create publication pub12 for table t1, t2; create publication pub13 for table t1, t3;\r\n> \r\n> On subscriber:\r\n> create subscription sub connection 'dbname=postgres' publication pub12,\r\n> pub13;\r\n> \r\n> On subscriber:\r\n> alter subscription sub drop publication pub12; select srsubid,\r\n> srrelid::regclass::text, srsubstate, srsublsn from pg_subscription_rel; srsubid |\r\n> srrelid | srsubstate | srsublsn\r\n> ---------+---------+------------+-----------\r\n> 16393 | t3 | r | 0/17080B0\r\n> (1 row)\r\n> \r\n> With v2 patch, the pg_subscription_rel has only one entry for t3 but it should\r\n> have also the one for t1 since it's still subscribing to pub13.\r\n> \r\n> To summary, I think that what we want to do in DROP SUBSCRIPTION cases is to\r\n> drop relations from pg_subscription_rel that are no longer included in the set of\r\n> after-calculated publications. In the latter example, when ALTER\r\n> SUBSCRIPTION ... DROP PUBLICATION pub12, we should compare the current\r\n> set of relations associated with {pub12, pub13} to the set of relcations associated\r\n> with pub13, not pub12. Then we can find out t2 is no longer associated with the\r\n> after-calculated publication (i.g., pub13) so remove it.\r\n\r\nThanks for the review. You are right, I missed this point.\r\nAttach new version patch which fix these problems(Also add a new pl-test).\r\n\r\nBest regards,\r\nHouzj", "msg_date": "Thu, 5 Aug 2021 14:40:14 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Thu, Aug 5, 2021 at 11:40 PM houzj.fnst@fujitsu.com\n<houzj.fnst@fujitsu.com> wrote:\n>\n> On Thursday, August 5, 2021 1:09 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote\n> > I've reviewed v2 patch. Here are some comments:\n> >\n> > + if (type == ALTER_SUBSCRIPTION_SET_PUBLICATION ||\n> > + type == ALTER_SUBSCRIPTION_REFRESH)\n> > + drop_table = !bsearch(&relid, pubrel_local_oids,\n> > + list_length(pubrel_names),\n> > + sizeof(Oid), oid_cmp);\n> > + else if (type == ALTER_SUBSCRIPTION_DROP_PUBLICATION)\n> > + drop_table = bsearch(&relid, pubrel_local_oids,\n> > + list_length(pubrel_names),\n> > + sizeof(Oid), oid_cmp);\n> >\n> > IIUC, in DROP PUBLICATION cases, we don't need to refer to the tables in the\n> > publication on the publisher that we're dropping in order to check whether to\n> > remove the relation. If we drop a table from the publication on the publisher\n> > before dropping the publication from the subscription on the subscriber, the\n> > pg_subscription_rel entry for the table remains. For example, please consider the\n> > following case:\n> >\n> > On publisher and subscriber:\n> > create table t1 (a int);\n> > create table t2 (a int);\n> > create table t3 (a int);\n> >\n> > On publisher:\n> > create publication pub12 for table t1, t2; create publication pub3 for table t3;\n> >\n> > On subscriber:\n> > create subscription sub connection 'dbname=postgres' publication pub12, pub3;\n> >\n> > On publisher:\n> > alter publication pub12 drop table t2;\n> >\n> > On subscriber:\n> > alter subscription sub drop publication pub12; select srsubid,\n> > srrelid::regclass::text, srsubstate, srsublsn from pg_subscription_rel;\n> >\n> > srsubid | srrelid | srsubstate | srsublsn\n> > ---------+---------+------------+-----------\n> > 16393 | t3 | r | 0/1707CE0\n> > 16393 | t2 | r | 0/1707CE0\n> >\n> > With v2 patch, the pg_subscription_rel has the entry for 't2' but it should not\n> > exist.\n> >\n> > But that doesn't mean that drop_table should always be true in DROP\n> > PULIBCATION cases. Since the tables associated with two publications can\n> > overlap, we cannot remove the relation from pg_subscription_rel if it is also\n> > associated with the remaining publication. For example:\n> >\n> > On publisher and subscriber:\n> > create table t1 (a int);\n> > create table t2 (a int);\n> > create table t3 (a int);\n> >\n> > On publisher:\n> > create publication pub12 for table t1, t2; create publication pub13 for table t1, t3;\n> >\n> > On subscriber:\n> > create subscription sub connection 'dbname=postgres' publication pub12,\n> > pub13;\n> >\n> > On subscriber:\n> > alter subscription sub drop publication pub12; select srsubid,\n> > srrelid::regclass::text, srsubstate, srsublsn from pg_subscription_rel; srsubid |\n> > srrelid | srsubstate | srsublsn\n> > ---------+---------+------------+-----------\n> > 16393 | t3 | r | 0/17080B0\n> > (1 row)\n> >\n> > With v2 patch, the pg_subscription_rel has only one entry for t3 but it should\n> > have also the one for t1 since it's still subscribing to pub13.\n> >\n> > To summary, I think that what we want to do in DROP SUBSCRIPTION cases is to\n> > drop relations from pg_subscription_rel that are no longer included in the set of\n> > after-calculated publications. In the latter example, when ALTER\n> > SUBSCRIPTION ... DROP PUBLICATION pub12, we should compare the current\n> > set of relations associated with {pub12, pub13} to the set of relcations associated\n> > with pub13, not pub12. Then we can find out t2 is no longer associated with the\n> > after-calculated publication (i.g., pub13) so remove it.\n>\n> Thanks for the review. You are right, I missed this point.\n> Attach new version patch which fix these problems(Also add a new pl-test).\n>\n\nThank you for updating the patch!\n\nHere are some comments:\n\nI think that it still could happen that DROP PULIBCATION misses\ndropping relations. Please consider the following case:\n\nOn publisher and subscriber:\ncreate table t1 (a int);\ncreate table t2 (a int);\ncreate table t3 (a int);\n\nOn publisher:\ncreate publication pub12 for table t1, t2;\ncreate publication pub3 for table t3;\n\nOn subscriber:\ncreate subscription sub connection 'dbname=postgres' publication pub12, pub3;\n\nOn publisher:\nalter publication pub3 add table t1;\n\nOn subscriber:\nalter subscription sub drop publication pub12;\nselect srsubid, srrelid::regclass::text, srsubstate, srsublsn from\npg_subscription_rel;\n srsubid | srrelid | srsubstate | srsublsn\n---------+---------+------------+-----------\n 16393 | t3 | r | 0/1707CE0\n 16393 | t1 | r | 0/1707D18\n\nWith v3 patch, pg_subscription_rel has entries for t3 and t1. But if\nALTER SUBSCRIPTION ... DROP PUBLICATION pub12 refreshes only relations\nassociated with pub12, t1 should be removed and be added when we\nrefresh pub3.\n\n---\n-AlterSubscription_refresh(Subscription *sub, bool copy_data)\n+AlterSubscription_refresh(Subscription *sub, bool copy_data,\n+ AlterSubscriptionType type)\n\nI think it's better to add comments to this function. The meaning of\n*sub varies depending on 'type'. For example, only in ADD PUBLICATION\ncases, 'sub' has only newly-added publications to this function. In\nother cases, 'sub' has a new set of publications.\n\n---\n+ if (type != ALTER_SUBSCRIPTION_DROP_PUBLICATION)\n {\n- AddSubscriptionRelState(sub->oid, relid,\n- copy_data ? SUBREL_STATE_INIT\n: SUBREL_STATE_READY,\n- InvalidXLogRecPtr);\n- ereport(DEBUG1,\n- (errmsg_internal(\"table \\\"%s.%s\\\" added to\nsubscription \\\"%s\\\"\",\n- rv->schemaname, rv->relname,\nsub->name)));\n+ /* Check for supported relkind. */\n+ CheckSubscriptionRelkind(get_rel_relkind(relid),\n+ rv->schemaname, rv->relname);\n\nI think CheckSubscriptionRelkind() is necessary even in\nnon-DROP-PUBLICATION cases.\n\n---\n+ if (type != ALTER_SUBSCRIPTION_ADD_PUBLICATION)\n+ {\n+ qsort(pubrel_local_oids, list_length(pubrel_names),\n+ sizeof(Oid), oid_cmp);\n+ ntables_to_drop = list_length(subrel_states);\n+ }\n\nI think we can break here in ADD PUBLICATION cases, which seems more\nreadable to me. That way, we don't need ntables_to_drop. Also, we\npalloc the memory for sub_remove_rels even in ADD PUBLICATION cases\nbut I think we don't need to do that.\n\n---\n+# Create tables on publisher\n+$node_publisher->safe_psql('postgres', \"CREATE TABLE temp1 (a int)\");\n+$node_publisher->safe_psql('postgres', \"CREATE TABLE temp2 (a int)\");\n+$node_publisher->safe_psql('postgres', \"CREATE TABLE temp3 (a int)\");\n+\n+# Create tables on subscriber\n+$node_subscriber->safe_psql('postgres', \"CREATE TABLE temp1 (a int)\");\n+$node_subscriber->safe_psql('postgres', \"CREATE TABLE temp2 (a int)\");\n+$node_subscriber->safe_psql('postgres', \"CREATE TABLE temp3 (a int)\");\n\nCan we execute multiple statements in one safe_psql?\n\n---\n+# check initial pg_subscription_rel\n+my $result = $node_subscriber->safe_psql('postgres',\n+ \"SELECT count(*) FROM pg_subscription_rel\");\n+is($result, qq(3),\n+ 'three relation was subscribed');\n\ns/three relation/three relations/\n\n---\n+$result = $node_subscriber->safe_psql('postgres',\n+ \"SELECT count(*) FROM pg_subscription_rel\");\n+\n+is($result, qq(2),\n+ 'check one relation was removed from subscribed list');\n+\n+$result = $node_subscriber->safe_psql('postgres',\n+ \"SELECT count(*) FROM pg_subscription_rel where\nsrrelid::regclass::text = 'temp1'\");\n+is($result, qq(0),\n+ 'check relation temp1 was removed from subscribed list');\n\nAt some places, the test checks the number of total tuples and then\ndoes an existence check. I think we can check the contents of\npg_subscription_rel instead. For example, in the above checks, we can\ncheck if pg_subscription_rel has entries for temp2 and temp3.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Fri, 6 Aug 2021 08:38:28 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Fri, Aug 6, 2021 at 5:09 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Thu, Aug 5, 2021 at 11:40 PM houzj.fnst@fujitsu.com\n> <houzj.fnst@fujitsu.com> wrote:\n> >\n> > > To summary, I think that what we want to do in DROP SUBSCRIPTION cases is to\n> > > drop relations from pg_subscription_rel that are no longer included in the set of\n> > > after-calculated publications. In the latter example, when ALTER\n> > > SUBSCRIPTION ... DROP PUBLICATION pub12, we should compare the current\n> > > set of relations associated with {pub12, pub13} to the set of relcations associated\n> > > with pub13, not pub12. Then we can find out t2 is no longer associated with the\n> > > after-calculated publication (i.g., pub13) so remove it.\n> >\n> > Thanks for the review. You are right, I missed this point.\n> > Attach new version patch which fix these problems(Also add a new pl-test).\n> >\n>\n> Thank you for updating the patch!\n>\n> Here are some comments:\n>\n> I think that it still could happen that DROP PULIBCATION misses\n> dropping relations. Please consider the following case:\n>\n> On publisher and subscriber:\n> create table t1 (a int);\n> create table t2 (a int);\n> create table t3 (a int);\n>\n> On publisher:\n> create publication pub12 for table t1, t2;\n> create publication pub3 for table t3;\n>\n> On subscriber:\n> create subscription sub connection 'dbname=postgres' publication pub12, pub3;\n>\n> On publisher:\n> alter publication pub3 add table t1;\n>\n> On subscriber:\n> alter subscription sub drop publication pub12;\n> select srsubid, srrelid::regclass::text, srsubstate, srsublsn from\n> pg_subscription_rel;\n> srsubid | srrelid | srsubstate | srsublsn\n> ---------+---------+------------+-----------\n> 16393 | t3 | r | 0/1707CE0\n> 16393 | t1 | r | 0/1707D18\n>\n> With v3 patch, pg_subscription_rel has entries for t3 and t1. But if\n> ALTER SUBSCRIPTION ... DROP PUBLICATION pub12 refreshes only relations\n> associated with pub12, t1 should be removed and be added when we\n> refresh pub3.\n>\n\nBut, isn't this happening because of your suggestion to compare the\ncurrent set of relations with relations from publications that doesn't\nneed to be removed? Do we have better ideas to fix or shall we just\nsay that we will refresh based on whatever current set of relations\nare present in publication to be dropped?\n\nOne more thing, I think it would be better to write a separate refresh\nfunction for add/drop rather than adding checks in the current refresh\nfunctionality. We can extract common functionality code which can be\ncalled from the different refresh functions.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Fri, 6 Aug 2021 10:09:37 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Fri, Aug 6, 2021 at 10:09 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Fri, Aug 6, 2021 at 5:09 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n>\n> But, isn't this happening because of your suggestion to compare the\n> current set of relations with relations from publications that doesn't\n> need to be removed? Do we have better ideas to fix or shall we just\n> say that we will refresh based on whatever current set of relations\n> are present in publication to be dropped?\n>\n\nThe other options could be that (a) for drop publication, we refresh\nall the publications, (b) for both add/drop publication, we refresh\nall the publications.\n\nAny better ideas?\n\nAs this is introduced in PG-14 via the below commit, I am adding\nauthors and committer to see if they have any better ideas.\n\ncommit 82ed7748b710e3ddce3f7ebc74af80fe4869492f\nAuthor: Peter Eisentraut <peter@eisentraut.org>\nDate: Tue Apr 6 10:44:26 2021 +0200\n\n ALTER SUBSCRIPTION ... ADD/DROP PUBLICATION\n\n Author: Japin Li <japinli@hotmail.com>\n Author: Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>\n\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Fri, 6 Aug 2021 11:20:38 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Fri, Aug 6, 2021 at 1:39 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Fri, Aug 6, 2021 at 5:09 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > On Thu, Aug 5, 2021 at 11:40 PM houzj.fnst@fujitsu.com\n> > <houzj.fnst@fujitsu.com> wrote:\n> > >\n> > > > To summary, I think that what we want to do in DROP SUBSCRIPTION cases is to\n> > > > drop relations from pg_subscription_rel that are no longer included in the set of\n> > > > after-calculated publications. In the latter example, when ALTER\n> > > > SUBSCRIPTION ... DROP PUBLICATION pub12, we should compare the current\n> > > > set of relations associated with {pub12, pub13} to the set of relcations associated\n> > > > with pub13, not pub12. Then we can find out t2 is no longer associated with the\n> > > > after-calculated publication (i.g., pub13) so remove it.\n> > >\n> > > Thanks for the review. You are right, I missed this point.\n> > > Attach new version patch which fix these problems(Also add a new pl-test).\n> > >\n> >\n> > Thank you for updating the patch!\n> >\n> > Here are some comments:\n> >\n> > I think that it still could happen that DROP PULIBCATION misses\n> > dropping relations. Please consider the following case:\n> >\n> > On publisher and subscriber:\n> > create table t1 (a int);\n> > create table t2 (a int);\n> > create table t3 (a int);\n> >\n> > On publisher:\n> > create publication pub12 for table t1, t2;\n> > create publication pub3 for table t3;\n> >\n> > On subscriber:\n> > create subscription sub connection 'dbname=postgres' publication pub12, pub3;\n> >\n> > On publisher:\n> > alter publication pub3 add table t1;\n> >\n> > On subscriber:\n> > alter subscription sub drop publication pub12;\n> > select srsubid, srrelid::regclass::text, srsubstate, srsublsn from\n> > pg_subscription_rel;\n> > srsubid | srrelid | srsubstate | srsublsn\n> > ---------+---------+------------+-----------\n> > 16393 | t3 | r | 0/1707CE0\n> > 16393 | t1 | r | 0/1707D18\n> >\n> > With v3 patch, pg_subscription_rel has entries for t3 and t1. But if\n> > ALTER SUBSCRIPTION ... DROP PUBLICATION pub12 refreshes only relations\n> > associated with pub12, t1 should be removed and be added when we\n> > refresh pub3.\n> >\n>\n> But, isn't this happening because of your suggestion to compare the\n> current set of relations with relations from publications that doesn't\n> need to be removed?\n\nHmm yes, it cannot cover all cases. I had somehow misunderstood that\nthe subscriber knows which relations are associated with which\npublications. Given that the subscriber doesn’t know which relations\nare associated with which publications (and the set of subscribed\nrelations on the subscriber becomes out of date once the publication\nis updated), I think it's impossible to achieve that DROP PUBLICATION\ndrops relations that are associated with only the publication being\ndropped.\n\n> Do we have better ideas to fix or shall we just\n> say that we will refresh based on whatever current set of relations\n> are present in publication to be dropped?\n\nI don't have better ideas. It seems to me that it's prudent that we\naccept the approach in v3 patch and refresh all publications in DROP\nPUBLICATION cases.\n\n>\n> One more thing, I think it would be better to write a separate refresh\n> function for add/drop rather than adding checks in the current refresh\n> functionality. We can extract common functionality code which can be\n> called from the different refresh functions.\n\n+1\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Fri, 6 Aug 2021 15:12:01 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "\n\nHi,\n\nSorry for the late reply. Having read this thread, the problem is caused by\nmisunderstanding the AlterSubscription_refresh(). My apologies.\n\nOn Fri, 06 Aug 2021 at 14:12, Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> On Fri, Aug 6, 2021 at 1:39 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>\n>> On Fri, Aug 6, 2021 at 5:09 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>> >\n>> > On Thu, Aug 5, 2021 at 11:40 PM houzj.fnst@fujitsu.com\n>> > <houzj.fnst@fujitsu.com> wrote:\n>> > >\n>> > > > To summary, I think that what we want to do in DROP SUBSCRIPTION cases is to\n>> > > > drop relations from pg_subscription_rel that are no longer included in the set of\n>> > > > after-calculated publications. In the latter example, when ALTER\n>> > > > SUBSCRIPTION ... DROP PUBLICATION pub12, we should compare the current\n>> > > > set of relations associated with {pub12, pub13} to the set of relcations associated\n>> > > > with pub13, not pub12. Then we can find out t2 is no longer associated with the\n>> > > > after-calculated publication (i.g., pub13) so remove it.\n>> > >\n>> > > Thanks for the review. You are right, I missed this point.\n>> > > Attach new version patch which fix these problems(Also add a new pl-test).\n>> > >\n>> >\n>> > Thank you for updating the patch!\n>> >\n>> > Here are some comments:\n>> >\n>> > I think that it still could happen that DROP PULIBCATION misses\n>> > dropping relations. Please consider the following case:\n>> >\n>> > On publisher and subscriber:\n>> > create table t1 (a int);\n>> > create table t2 (a int);\n>> > create table t3 (a int);\n>> >\n>> > On publisher:\n>> > create publication pub12 for table t1, t2;\n>> > create publication pub3 for table t3;\n>> >\n>> > On subscriber:\n>> > create subscription sub connection 'dbname=postgres' publication pub12, pub3;\n>> >\n>> > On publisher:\n>> > alter publication pub3 add table t1;\n>> >\n>> > On subscriber:\n>> > alter subscription sub drop publication pub12;\n>> > select srsubid, srrelid::regclass::text, srsubstate, srsublsn from\n>> > pg_subscription_rel;\n>> > srsubid | srrelid | srsubstate | srsublsn\n>> > ---------+---------+------------+-----------\n>> > 16393 | t3 | r | 0/1707CE0\n>> > 16393 | t1 | r | 0/1707D18\n>> >\n>> > With v3 patch, pg_subscription_rel has entries for t3 and t1. But if\n>> > ALTER SUBSCRIPTION ... DROP PUBLICATION pub12 refreshes only relations\n>> > associated with pub12, t1 should be removed and be added when we\n>> > refresh pub3.\n>> >\n>>\n>> But, isn't this happening because of your suggestion to compare the\n>> current set of relations with relations from publications that doesn't\n>> need to be removed?\n>\n> Hmm yes, it cannot cover all cases. I had somehow misunderstood that\n> the subscriber knows which relations are associated with which\n> publications. Given that the subscriber doesn’t know which relations\n> are associated with which publications (and the set of subscribed\n> relations on the subscriber becomes out of date once the publication\n> is updated), I think it's impossible to achieve that DROP PUBLICATION\n> drops relations that are associated with only the publication being\n> dropped.\n>\n>> Do we have better ideas to fix or shall we just\n>> say that we will refresh based on whatever current set of relations\n>> are present in publication to be dropped?\n>\n> I don't have better ideas. It seems to me that it's prudent that we\n> accept the approach in v3 patch and refresh all publications in DROP\n> PUBLICATION cases.\n>\n\nMaybe refreshing all publications in PUBLICATION cases is simple way to\nfix the problem.\n\n>>\n>> One more thing, I think it would be better to write a separate refresh\n>> function for add/drop rather than adding checks in the current refresh\n>> functionality. We can extract common functionality code which can be\n>> called from the different refresh functions.\n>\n> +1\n>\n\nAgreed.\n\n> Regards,\n\n\n--\nRegrads,\nJapin Li.\nChengDu WenWu Information Technology Co.,Ltd.\n\n\n", "msg_date": "Sat, 07 Aug 2021 00:27:36 +0800", "msg_from": "Japin Li <japinli@hotmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Fri, Aug 6, 2021 at 2:50 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Fri, Aug 6, 2021 at 10:09 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > On Fri, Aug 6, 2021 at 5:09 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> > >\n> >\n> > But, isn't this happening because of your suggestion to compare the\n> > current set of relations with relations from publications that doesn't\n> > need to be removed? Do we have better ideas to fix or shall we just\n> > say that we will refresh based on whatever current set of relations\n> > are present in publication to be dropped?\n> >\n>\n> The other options could be that (a) for drop publication, we refresh\n> all the publications, (b) for both add/drop publication, we refresh\n> all the publications.\n>\n> Any better ideas?\n>\n> As this is introduced in PG-14 via the below commit, I am adding\n> authors and committer to see if they have any better ideas.\n>\n> commit 82ed7748b710e3ddce3f7ebc74af80fe4869492f\n> Author: Peter Eisentraut <peter@eisentraut.org>\n> Date: Tue Apr 6 10:44:26 2021 +0200\n>\n> ALTER SUBSCRIPTION ... ADD/DROP PUBLICATION\n>\n> Author: Japin Li <japinli@hotmail.com>\n> Author: Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>\n>\n\nI've added this to Open Items.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Sat, 7 Aug 2021 08:50:19 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Fri, Aug 6, 2021 at 9:57 PM Japin Li <japinli@hotmail.com> wrote:\n>\n> >\n> > Hmm yes, it cannot cover all cases. I had somehow misunderstood that\n> > the subscriber knows which relations are associated with which\n> > publications. Given that the subscriber doesn’t know which relations\n> > are associated with which publications (and the set of subscribed\n> > relations on the subscriber becomes out of date once the publication\n> > is updated), I think it's impossible to achieve that DROP PUBLICATION\n> > drops relations that are associated with only the publication being\n> > dropped.\n> >\n> >> Do we have better ideas to fix or shall we just\n> >> say that we will refresh based on whatever current set of relations\n> >> are present in publication to be dropped?\n> >\n> > I don't have better ideas. It seems to me that it's prudent that we\n> > accept the approach in v3 patch and refresh all publications in DROP\n> > PUBLICATION cases.\n> >\n>\n> Maybe refreshing all publications in PUBLICATION cases is simple way to\n> fix the problem.\n>\n\nDo you mean to say that do it for both Add and Drop or just for Drop?\nActually, doing it both will make the behavior consistent but doing it\njust for Drop might be preferable by some users. I think it is better\nto be consistent here but I am fine if you and others feel it is\nbetter to refresh all publications only in Drop case.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Sat, 7 Aug 2021 11:05:55 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "\r\n\r\n> On Aug 7, 2021, at 1:35 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:\r\n> \r\n> On Fri, Aug 6, 2021 at 9:57 PM Japin Li <japinli@hotmail.com> wrote:\r\n>> \r\n>>> \r\n>>> Hmm yes, it cannot cover all cases. I had somehow misunderstood that\r\n>>> the subscriber knows which relations are associated with which\r\n>>> publications. Given that the subscriber doesn’t know which relations\r\n>>> are associated with which publications (and the set of subscribed\r\n>>> relations on the subscriber becomes out of date once the publication\r\n>>> is updated), I think it's impossible to achieve that DROP PUBLICATION\r\n>>> drops relations that are associated with only the publication being\r\n>>> dropped.\r\n>>> \r\n>>>> Do we have better ideas to fix or shall we just\r\n>>>> say that we will refresh based on whatever current set of relations\r\n>>>> are present in publication to be dropped?\r\n>>> \r\n>>> I don't have better ideas. It seems to me that it's prudent that we\r\n>>> accept the approach in v3 patch and refresh all publications in DROP\r\n>>> PUBLICATION cases.\r\n>>> \r\n>> \r\n>> Maybe refreshing all publications in PUBLICATION cases is simple way to\r\n>> fix the problem.\r\n>> \r\n> \r\n> Do you mean to say that do it for both Add and Drop or just for Drop?\r\n> Actually, doing it both will make the behavior consistent but doing it\r\n> just for Drop might be preferable by some users. I think it is better\r\n> to be consistent here but I am fine if you and others feel it is\r\n> better to refresh all publications only in Drop case.\r\n> \r\n\r\nI prefer to refresh all PUBLICATIONS for both ADD and DROP operations, I think\r\nthis is more consistent and makes the code simple.\r\n\r\n--\r\nBest regards\r\nJapin Li\r\n\r\n\r\n\r\n", "msg_date": "Sat, 7 Aug 2021 13:19:49 +0000", "msg_from": "Li Japin <japinli@hotmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Sat, Aug 7, 2021 1:36 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\r\n> On Fri, Aug 6, 2021 at 9:57 PM Japin Li <japinli@hotmail.com> wrote:\r\n> >\r\n> > >\r\n> > > Hmm yes, it cannot cover all cases. I had somehow misunderstood that\r\n> > > the subscriber knows which relations are associated with which\r\n> > > publications. Given that the subscriber doesn’t know which relations\r\n> > > are associated with which publications (and the set of subscribed\r\n> > > relations on the subscriber becomes out of date once the publication\r\n> > > is updated), I think it's impossible to achieve that DROP\r\n> > > PUBLICATION drops relations that are associated with only the\r\n> > > publication being dropped.\r\n> > >\r\n> > >> Do we have better ideas to fix or shall we just say that we will\r\n> > >> refresh based on whatever current set of relations are present in\r\n> > >> publication to be dropped?\r\n> > >\r\n> > > I don't have better ideas. It seems to me that it's prudent that we\r\n> > > accept the approach in v3 patch and refresh all publications in DROP\r\n> > > PUBLICATION cases.\r\n> > >\r\n> >\r\n> > Maybe refreshing all publications in PUBLICATION cases is simple way\r\n> > to fix the problem.\r\n> >\r\n> \r\n> Do you mean to say that do it for both Add and Drop or just for Drop?\r\n> Actually, doing it both will make the behavior consistent but doing it just for\r\n> Drop might be preferable by some users. I think it is better to be consistent here\r\n> but I am fine if you and others feel it is better to refresh all publications only in\r\n> Drop case.\r\n\r\nPersonally, I also think it will be better to make the behavior consistent.\r\nAttach the new version patch make both ADD and DROP behave the same as SET PUBLICATION\r\nwhich refresh all the publications.\r\n\r\nBest regards,\r\nhouzj", "msg_date": "Sat, 7 Aug 2021 13:23:11 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Sat, Aug 7, 2021 at 6:53 PM houzj.fnst@fujitsu.com\n<houzj.fnst@fujitsu.com> wrote:\n>\n> On Sat, Aug 7, 2021 1:36 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > On Fri, Aug 6, 2021 at 9:57 PM Japin Li <japinli@hotmail.com> wrote:\n> >\n> > Do you mean to say that do it for both Add and Drop or just for Drop?\n> > Actually, doing it both will make the behavior consistent but doing it just for\n> > Drop might be preferable by some users. I think it is better to be consistent here\n> > but I am fine if you and others feel it is better to refresh all publications only in\n> > Drop case.\n>\n> Personally, I also think it will be better to make the behavior consistent.\n> Attach the new version patch make both ADD and DROP behave the same as SET PUBLICATION\n> which refresh all the publications.\n>\n\nThere is a bug reported on pgsql-bugs [1] which seems to be happening\ndue to the same reason. Can you please test that the other bug is also\nfixed with your patch?\n\n[1] - https://www.postgresql.org/message-id/17132-6a702189086c6243%40postgresql.org\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Mon, 9 Aug 2021 08:39:44 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Monday, August 9, 2021 11:10 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\r\n> \r\n> On Sat, Aug 7, 2021 at 6:53 PM houzj.fnst@fujitsu.com <houzj.fnst@fujitsu.com>\r\n> wrote:\r\n> >\r\n> > On Sat, Aug 7, 2021 1:36 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\r\n> > > On Fri, Aug 6, 2021 at 9:57 PM Japin Li <japinli@hotmail.com> wrote:\r\n> > >\r\n> > > Do you mean to say that do it for both Add and Drop or just for Drop?\r\n> > > Actually, doing it both will make the behavior consistent but doing\r\n> > > it just for Drop might be preferable by some users. I think it is\r\n> > > better to be consistent here but I am fine if you and others feel it\r\n> > > is better to refresh all publications only in Drop case.\r\n> >\r\n> > Personally, I also think it will be better to make the behavior consistent.\r\n> > Attach the new version patch make both ADD and DROP behave the same as\r\n> > SET PUBLICATION which refresh all the publications.\r\n> >\r\n> \r\n> There is a bug reported on pgsql-bugs [1] which seems to be happening due to\r\n> the same reason. Can you please test that the other bug is also fixed with your\r\n> patch?\r\n> \r\n> [1] -\r\n> https://www.postgresql.org/message-id/17132-6a702189086c6243%40postgres\r\n> ql.org\r\n\r\nThanks for the reminder, I have checked and tested the reported bug.\r\nThe reported bug is that when drop and then re-add a publication on subscriber side,\r\nthe table in the publication wasn't synced. And after applying the patch here, the table\r\nwill be synced as expected if re-added(behaves the same as SET PUBLICATION).\r\n\r\nBest regards,\r\nHou zj\r\n", "msg_date": "Mon, 9 Aug 2021 10:33:46 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Sat, Aug 7, 2021 at 2:36 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Fri, Aug 6, 2021 at 9:57 PM Japin Li <japinli@hotmail.com> wrote:\n> >\n> > >\n> > > Hmm yes, it cannot cover all cases. I had somehow misunderstood that\n> > > the subscriber knows which relations are associated with which\n> > > publications. Given that the subscriber doesn’t know which relations\n> > > are associated with which publications (and the set of subscribed\n> > > relations on the subscriber becomes out of date once the publication\n> > > is updated), I think it's impossible to achieve that DROP PUBLICATION\n> > > drops relations that are associated with only the publication being\n> > > dropped.\n> > >\n> > >> Do we have better ideas to fix or shall we just\n> > >> say that we will refresh based on whatever current set of relations\n> > >> are present in publication to be dropped?\n> > >\n> > > I don't have better ideas. It seems to me that it's prudent that we\n> > > accept the approach in v3 patch and refresh all publications in DROP\n> > > PUBLICATION cases.\n> > >\n> >\n> > Maybe refreshing all publications in PUBLICATION cases is simple way to\n> > fix the problem.\n> >\n>\n> Actually, doing it both will make the behavior consistent but doing it\n> just for Drop might be preferable by some users.\n\nI agree that ADD/DROP PUBLICATION is convenient to just add/drop\npublications instead of providing the complete publication list. But\nI'm concerned that during developing this feature most people didn't\nlike the behavior of refreshing new and existing publications. Also,\nthere was pointing out that there will be an overhead of a SQL with\nmore publications when AlterSubscription_refresh() is called with all\nthe existing publications. If we feel this behavior is unnatural, the\nusers will feel the same. I personally think there is a benefit only\nin terms of syntax. And we can work on the part of refreshing only\npublications being added/dropped on v15 development. But it might be\nbetter to consider also if there will be use cases for users to\nadd/remove publications in the subscription even with such downsides.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Tue, 10 Aug 2021 11:35:17 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Tue, Aug 10, 2021 at 8:05 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Sat, Aug 7, 2021 at 2:36 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > On Fri, Aug 6, 2021 at 9:57 PM Japin Li <japinli@hotmail.com> wrote:\n> > >\n> > > >\n> > > > Hmm yes, it cannot cover all cases. I had somehow misunderstood that\n> > > > the subscriber knows which relations are associated with which\n> > > > publications. Given that the subscriber doesn’t know which relations\n> > > > are associated with which publications (and the set of subscribed\n> > > > relations on the subscriber becomes out of date once the publication\n> > > > is updated), I think it's impossible to achieve that DROP PUBLICATION\n> > > > drops relations that are associated with only the publication being\n> > > > dropped.\n> > > >\n> > > >> Do we have better ideas to fix or shall we just\n> > > >> say that we will refresh based on whatever current set of relations\n> > > >> are present in publication to be dropped?\n> > > >\n> > > > I don't have better ideas. It seems to me that it's prudent that we\n> > > > accept the approach in v3 patch and refresh all publications in DROP\n> > > > PUBLICATION cases.\n> > > >\n> > >\n> > > Maybe refreshing all publications in PUBLICATION cases is simple way to\n> > > fix the problem.\n> > >\n> >\n> > Actually, doing it both will make the behavior consistent but doing it\n> > just for Drop might be preferable by some users.\n>\n> I agree that ADD/DROP PUBLICATION is convenient to just add/drop\n> publications instead of providing the complete publication list. But\n> I'm concerned that during developing this feature most people didn't\n> like the behavior of refreshing new and existing publications. Also,\n> there was pointing out that there will be an overhead of a SQL with\n> more publications when AlterSubscription_refresh() is called with all\n> the existing publications.\n>\n\nTrue, but I think at that time we didn't know this design problem with\n'drop publication'.\n\n> If we feel this behavior is unnatural, the\n> users will feel the same. I personally think there is a benefit only\n> in terms of syntax.\n>\n\nRight, and I think in this particular case, the new syntax is much\neasier to use for users.\n\n> And we can work on the part of refreshing only\n> publications being added/dropped on v15 development.\n>\n\nYeah, unless we change design drastically we might not be able to do a\nrefresh for dropped publications, for add it is possible. It seems\nmost of the people responded on this thread that we can be consistent\nin terms of refreshing for add/drop at this stage but we can still go\nwith another option where we can refresh only newly added publications\nfor add but for drop refresh all publications.\n\nPeter E., do you have any opinion on this matter?\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 10 Aug 2021 08:52:13 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On 10.08.21 05:22, Amit Kapila wrote:\n> Yeah, unless we change design drastically we might not be able to do a\n> refresh for dropped publications, for add it is possible. It seems\n> most of the people responded on this thread that we can be consistent\n> in terms of refreshing for add/drop at this stage but we can still go\n> with another option where we can refresh only newly added publications\n> for add but for drop refresh all publications.\n> \n> Peter E., do you have any opinion on this matter?\n\nRefresh everything for both ADD and DROP makes sense to me.\n\n\n\n", "msg_date": "Wed, 18 Aug 2021 16:24:09 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Sat, Aug 7, 2021 at 6:53 PM houzj.fnst@fujitsu.com\n<houzj.fnst@fujitsu.com> wrote:\n>\n> Personally, I also think it will be better to make the behavior consistent.\n> Attach the new version patch make both ADD and DROP behave the same as SET PUBLICATION\n> which refresh all the publications.\n>\n\nI think we can have tests in the separate test file (alter_sub_pub.pl)\nlike you earlier had in one of the versions. Use some meaningful names\nfor tables instead of temp1, temp2 as you had in the previous version.\nOtherwise, the code changes look good to me.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Mon, 23 Aug 2021 10:29:14 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Wed, Aug 18, 2021 at 7:54 PM Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n>\n> On 10.08.21 05:22, Amit Kapila wrote:\n> > Yeah, unless we change design drastically we might not be able to do a\n> > refresh for dropped publications, for add it is possible. It seems\n> > most of the people responded on this thread that we can be consistent\n> > in terms of refreshing for add/drop at this stage but we can still go\n> > with another option where we can refresh only newly added publications\n> > for add but for drop refresh all publications.\n> >\n> > Peter E., do you have any opinion on this matter?\n>\n> Refresh everything for both ADD and DROP makes sense to me.\n>\n\nThanks for your suggestion.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Mon, 23 Aug 2021 10:31:11 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Mon, Aug 23, 2021 at 1:59 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Sat, Aug 7, 2021 at 6:53 PM houzj.fnst@fujitsu.com\n> <houzj.fnst@fujitsu.com> wrote:\n> >\n> > Personally, I also think it will be better to make the behavior consistent.\n> > Attach the new version patch make both ADD and DROP behave the same as SET PUBLICATION\n> > which refresh all the publications.\n> >\n>\n> I think we can have tests in the separate test file (alter_sub_pub.pl)\n> like you earlier had in one of the versions. Use some meaningful names\n> for tables instead of temp1, temp2 as you had in the previous version.\n> Otherwise, the code changes look good to me.\n\n- supported_opts = SUBOPT_REFRESH;\n- if (isadd)\n- supported_opts |= SUBOPT_COPY_DATA;\n+ supported_opts = SUBOPT_REFRESH | SUBOPT_COPY_DATA;\n\nI think that the currently the doc says copy_data option can be\nspecified except in DROP PUBLICATION case, which needs to be fixed\ncorresponding the above change.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Mon, 23 Aug 2021 14:17:44 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Mon, Aug 23, 2021 12:59 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\r\n> \r\n> On Sat, Aug 7, 2021 at 6:53 PM houzj.fnst@fujitsu.com <houzj.fnst@fujitsu.com> wrote:\r\n> >\r\n> > Personally, I also think it will be better to make the behavior consistent.\r\n> > Attach the new version patch make both ADD and DROP behave the same as\r\n> > SET PUBLICATION which refresh all the publications.\r\n> >\r\n> \r\n> I think we can have tests in the separate test file (alter_sub_pub.pl) like you\r\n> earlier had in one of the versions. Use some meaningful names for tables\r\n> instead of temp1, temp2 as you had in the previous version.\r\n> Otherwise, the code changes look good to me.\r\n\r\nThanks for the comment.\r\nAttach new version patch which did the following changes.\r\n\r\n* move the tests to a separate test file (024_alter_sub_pub.pl)\r\n* adjust the document of copy_data option\r\n* add tab-complete for copy_data option when ALTER DROP publication.\r\n\r\nBest regards,\r\nHou zj", "msg_date": "Mon, 23 Aug 2021 09:15:13 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Mon, Aug 23, 2021 1:18 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\r\n> On Mon, Aug 23, 2021 at 1:59 PM Amit Kapila <amit.kapila16@gmail.com>\r\n> wrote:\r\n> >\r\n> > On Sat, Aug 7, 2021 at 6:53 PM houzj.fnst@fujitsu.com\r\n> > <houzj.fnst@fujitsu.com> wrote:\r\n> > >\r\n> > > Personally, I also think it will be better to make the behavior consistent.\r\n> > > Attach the new version patch make both ADD and DROP behave the same\r\n> > > as SET PUBLICATION which refresh all the publications.\r\n> > >\r\n> >\r\n> > I think we can have tests in the separate test file (alter_sub_pub.pl)\r\n> > like you earlier had in one of the versions. Use some meaningful names\r\n> > for tables instead of temp1, temp2 as you had in the previous version.\r\n> > Otherwise, the code changes look good to me.\r\n> \r\n> - supported_opts = SUBOPT_REFRESH;\r\n> - if (isadd)\r\n> - supported_opts |= SUBOPT_COPY_DATA;\r\n> + supported_opts = SUBOPT_REFRESH | SUBOPT_COPY_DATA;\r\n> \r\n> I think that the currently the doc says copy_data option can be specified except\r\n> in DROP PUBLICATION case, which needs to be fixed corresponding the above\r\n> change.\r\n\r\nThanks for the comment.\r\nFixed in the new version patch.\r\n\r\nBest regards,\r\nHou zj\r\n", "msg_date": "Mon, 23 Aug 2021 09:15:25 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Mon, Aug 23, 2021 at 2:45 PM houzj.fnst@fujitsu.com\n<houzj.fnst@fujitsu.com> wrote:\n>\n> On Mon, Aug 23, 2021 12:59 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > On Sat, Aug 7, 2021 at 6:53 PM houzj.fnst@fujitsu.com <houzj.fnst@fujitsu.com> wrote:\n> > >\n> > > Personally, I also think it will be better to make the behavior consistent.\n> > > Attach the new version patch make both ADD and DROP behave the same as\n> > > SET PUBLICATION which refresh all the publications.\n> > >\n> >\n> > I think we can have tests in the separate test file (alter_sub_pub.pl) like you\n> > earlier had in one of the versions. Use some meaningful names for tables\n> > instead of temp1, temp2 as you had in the previous version.\n> > Otherwise, the code changes look good to me.\n>\n> Thanks for the comment.\n> Attach new version patch which did the following changes.\n>\n> * move the tests to a separate test file (024_alter_sub_pub.pl)\n> * adjust the document of copy_data option\n> * add tab-complete for copy_data option when ALTER DROP publication.\n>\n\nThanks, the patch looks good to me. I have made some cosmetic changes\nin the attached version. It makes the test cases easier to understand.\nI am planning to push this tomorrow unless there are more comments or\nsuggestions.\n\n-- \nWith Regards,\nAmit Kapila.", "msg_date": "Mon, 23 Aug 2021 17:31:17 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Mon, Aug 23, 2021 8:01 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\r\n> On Mon, Aug 23, 2021 at 2:45 PM houzj.fnst@fujitsu.com<houzj.fnst@fujitsu.com> wrote:\r\n> >\r\n> > On Mon, Aug 23, 2021 12:59 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\r\n> > >\r\n> > > On Sat, Aug 7, 2021 at 6:53 PM houzj.fnst@fujitsu.com <houzj.fnst@fujitsu.com> wrote:\r\n> > > >\r\n> > > > Personally, I also think it will be better to make the behavior consistent.\r\n> > > > Attach the new version patch make both ADD and DROP behave the\r\n> > > > same as SET PUBLICATION which refresh all the publications.\r\n> > > >\r\n> > >\r\n> > > I think we can have tests in the separate test file\r\n> > > (alter_sub_pub.pl) like you earlier had in one of the versions. Use\r\n> > > some meaningful names for tables instead of temp1, temp2 as you had in the\r\n> previous version.\r\n> > > Otherwise, the code changes look good to me.\r\n> >\r\n> > Thanks for the comment.\r\n> > Attach new version patch which did the following changes.\r\n> >\r\n> > * move the tests to a separate test file (024_alter_sub_pub.pl)\r\n> > * adjust the document of copy_data option\r\n> > * add tab-complete for copy_data option when ALTER DROP publication.\r\n> >\r\n> \r\n> Thanks, the patch looks good to me. I have made some cosmetic changes in the\r\n> attached version. It makes the test cases easier to understand.\r\n> I am planning to push this tomorrow unless there are more comments or\r\n> suggestions.\r\n\r\nThanks ! The patch looks good to me.\r\n\r\nI noticed that the patch cannot be applied to PG14-stable,\r\nso I attach a separate patch for back-patch(I didn’t change the patch for HEAD branch).\r\n\r\nBest regards,\r\nHou zj", "msg_date": "Mon, 23 Aug 2021 14:05:23 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Mon, Aug 23, 2021 at 11:05 PM houzj.fnst@fujitsu.com\n<houzj.fnst@fujitsu.com> wrote:\n>\n> On Mon, Aug 23, 2021 8:01 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > On Mon, Aug 23, 2021 at 2:45 PM houzj.fnst@fujitsu.com<houzj.fnst@fujitsu.com> wrote:\n> > >\n> > > On Mon, Aug 23, 2021 12:59 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > > >\n> > > > On Sat, Aug 7, 2021 at 6:53 PM houzj.fnst@fujitsu.com <houzj.fnst@fujitsu.com> wrote:\n> > > > >\n> > > > > Personally, I also think it will be better to make the behavior consistent.\n> > > > > Attach the new version patch make both ADD and DROP behave the\n> > > > > same as SET PUBLICATION which refresh all the publications.\n> > > > >\n> > > >\n> > > > I think we can have tests in the separate test file\n> > > > (alter_sub_pub.pl) like you earlier had in one of the versions. Use\n> > > > some meaningful names for tables instead of temp1, temp2 as you had in the\n> > previous version.\n> > > > Otherwise, the code changes look good to me.\n> > >\n> > > Thanks for the comment.\n> > > Attach new version patch which did the following changes.\n> > >\n> > > * move the tests to a separate test file (024_alter_sub_pub.pl)\n> > > * adjust the document of copy_data option\n> > > * add tab-complete for copy_data option when ALTER DROP publication.\n> > >\n> >\n> > Thanks, the patch looks good to me. I have made some cosmetic changes in the\n> > attached version. It makes the test cases easier to understand.\n> > I am planning to push this tomorrow unless there are more comments or\n> > suggestions.\n>\n> Thanks ! The patch looks good to me.\n>\n> I noticed that the patch cannot be applied to PG14-stable,\n> so I attach a separate patch for back-patch(I didn’t change the patch for HEAD branch).\n\nThanks. The patch for HEAD looks good to me. Regarding the patch for\nPG14, I think we need to update the comment as well:\n\n@@ -987,7 +986,7 @@ AlterSubscription(AlterSubscriptionStmt *stmt,\nbool isTopLevel)\n PreventInTransactionBlock(isTopLevel, \"ALTER SUBSCRIPTION with refresh\");\n\n /* Only refresh the added/dropped list of publications. */\n- sub->publications = stmt->publication;\n+ sub->publications = publist;\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Tue, 24 Aug 2021 09:51:43 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "> -----Original Message-----\r\n> From: Masahiko Sawada <sawada.mshk@gmail.com>\r\n> Sent: Tuesday, August 24, 2021 8:52 AM\r\n> \r\n> Thanks. The patch for HEAD looks good to me. Regarding the patch for PG14, I\r\n> think we need to update the comment as well:\r\n> \r\n> @@ -987,7 +986,7 @@ AlterSubscription(AlterSubscriptionStmt *stmt, bool\r\n> isTopLevel)\r\n> PreventInTransactionBlock(isTopLevel, \"ALTER SUBSCRIPTION with\r\n> refresh\");\r\n> \r\n> /* Only refresh the added/dropped list of publications. */\r\n> - sub->publications = stmt->publication;\r\n> + sub->publications = publist;\r\n> \r\n\r\nThanks for the comment, attach new version patch which fixed it.\r\n\r\nBest regards,\r\nHou zj", "msg_date": "Tue, 24 Aug 2021 01:01:51 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Tue, Aug 24, 2021 at 10:01 AM houzj.fnst@fujitsu.com\n<houzj.fnst@fujitsu.com> wrote:\n>\n>\n>\n> > -----Original Message-----\n> > From: Masahiko Sawada <sawada.mshk@gmail.com>\n> > Sent: Tuesday, August 24, 2021 8:52 AM\n> >\n> > Thanks. The patch for HEAD looks good to me. Regarding the patch for PG14, I\n> > think we need to update the comment as well:\n> >\n> > @@ -987,7 +986,7 @@ AlterSubscription(AlterSubscriptionStmt *stmt, bool\n> > isTopLevel)\n> > PreventInTransactionBlock(isTopLevel, \"ALTER SUBSCRIPTION with\n> > refresh\");\n> >\n> > /* Only refresh the added/dropped list of publications. */\n> > - sub->publications = stmt->publication;\n> > + sub->publications = publist;\n> >\n>\n> Thanks for the comment, attach new version patch which fixed it.\n\nThank you for updating the patch! Looks good to me.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Tue, 24 Aug 2021 10:42:26 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Tue, Aug 24, 2021 at 7:13 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Tue, Aug 24, 2021 at 10:01 AM houzj.fnst@fujitsu.com\n> <houzj.fnst@fujitsu.com> wrote:\n> >\n> >\n> >\n> > > -----Original Message-----\n> > > From: Masahiko Sawada <sawada.mshk@gmail.com>\n> > > Sent: Tuesday, August 24, 2021 8:52 AM\n> > >\n> > > Thanks. The patch for HEAD looks good to me. Regarding the patch for PG14, I\n> > > think we need to update the comment as well:\n> > >\n> > > @@ -987,7 +986,7 @@ AlterSubscription(AlterSubscriptionStmt *stmt, bool\n> > > isTopLevel)\n> > > PreventInTransactionBlock(isTopLevel, \"ALTER SUBSCRIPTION with\n> > > refresh\");\n> > >\n> > > /* Only refresh the added/dropped list of publications. */\n> > > - sub->publications = stmt->publication;\n> > > + sub->publications = publist;\n> > >\n> >\n> > Thanks for the comment, attach new version patch which fixed it.\n>\n> Thank you for updating the patch! Looks good to me.\n>\n\nPushed!\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 24 Aug 2021 14:07:59 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" }, { "msg_contents": "On Tue, Aug 24, 2021 at 5:38 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Tue, Aug 24, 2021 at 7:13 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > On Tue, Aug 24, 2021 at 10:01 AM houzj.fnst@fujitsu.com\n> > <houzj.fnst@fujitsu.com> wrote:\n> > >\n> > >\n> > >\n> > > > -----Original Message-----\n> > > > From: Masahiko Sawada <sawada.mshk@gmail.com>\n> > > > Sent: Tuesday, August 24, 2021 8:52 AM\n> > > >\n> > > > Thanks. The patch for HEAD looks good to me. Regarding the patch for PG14, I\n> > > > think we need to update the comment as well:\n> > > >\n> > > > @@ -987,7 +986,7 @@ AlterSubscription(AlterSubscriptionStmt *stmt, bool\n> > > > isTopLevel)\n> > > > PreventInTransactionBlock(isTopLevel, \"ALTER SUBSCRIPTION with\n> > > > refresh\");\n> > > >\n> > > > /* Only refresh the added/dropped list of publications. */\n> > > > - sub->publications = stmt->publication;\n> > > > + sub->publications = publist;\n> > > >\n> > >\n> > > Thanks for the comment, attach new version patch which fixed it.\n> >\n> > Thank you for updating the patch! Looks good to me.\n> >\n>\n> Pushed!\n\nThanks! I've marked this open item as resolved.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Wed, 25 Aug 2021 13:30:53 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] wrong refresh when ALTER SUBSCRIPTION ADD/DROP PUBLICATION" } ]
[ { "msg_contents": "Hi,\n\nI've previously complained ([1]) that process initialization has gotten\nvery complicated. I hit this once more last week when trying to commit\none of the shared memory stats pieces...\n\nI think there's quite a few different issues around this - here I'm just\ntrying to tackle a few of the most glaring (to me):\n\n- AuxiliaryProcessMain() is used for two independent tasks: Start bootstrap /\n checker mode and starting auxiliary processes. In HEAD there's maybe 5 lines\n out 250 that are actually common to both uses.\n\n A related oddity is that we reserve shared memory resources for bootstrap &\n checker aux processes, despite those never existing.\n\n This is addressed in patches 1-7\n\n- The order of invocation of InitProcess()/InitAuxiliaryProcess() and\n BaseInit() depends on EXEC_BACKEND. Due to that there often is no single\n place initialization code can be put if it needs any locks.\n\n This is addressed in patches 8-9\n\n- PostgresMain() has code for single user and multi user interleaved, making\n it unnecessarily hard to understand what's going on.\n\n This is addressed in patches 10\n\n\nThis isn't a patch series ready to commit, there's a bunch of polishing that\nneeds to be done if there's agreement.\n\n\nQuestions I have:\n\n- What exactly to do with checker mode: Keep it as part of bootstrap, separate\n it out completely? What commandline flags?\n\n- I used a separate argv entry to pass the aux proc type - do we rather want\n to go for the approach that e.g. bgworker went for? Adding code for string\n splitting seems a bit unnecessary to me.\n\n- PostgresMainSingle() should probably not be in postgres.c. We could put it\n into postinit.c or ..?\n\n- My first attempt at PostgresMainSingle() separated the single/multi user\n cases a bit more than the code right now, by having a PostgresMainCommon()\n which was called by PostgresMainSingle(), PostgresMain(). *Common only\n started with the MessageContext allocation, which did have the advantage of\n splitting out a few of the remaining conditional actions in PostgresMain()\n (PostmasterContext, welcome banner, Log_disconnections). But lead to a bit\n more duplication. I don't really have an opinion on what's better.\n\n- I had to move the PgStartTime computation to a bit earlier for single user\n mode. That seems to make sense to me anyway, given that postmaster does so\n fairly early too.\n\n Any reason that'd be a bad idea?\n\n Arguably it should even be a tad earlier to be symmetric.\n\n\nThere's one further issue that I think is big enough to be worth\ntackling in the near future: Too many things depend on BackendIds.\n\nAux processes need procsignal and backend status reporting, which use\nBackendId for indexing. But they don't use sinval, so they don't have a\nBackendId - so we have hacks to work around that in a few places. If we\ninstead make those places use pgprocno for indexing the whole issue\nvanishes.\n\nIn fact, I think there's a good argument to be made that we should\nentirely remove the concept of BackendIds and just use pgprocnos. We\nhave a fair number of places like SignalVirtualTransaction() that need\nto search the procarray just to find the proc to signal based on the\nBackendId. If we used pgprocno instead, that'd not be needed.\n\nBut perhaps that's a separate thread.\n\nGreetings,\n\nAndres Freund\n\n[1] https://postgr.es/m/20210402002240.56cuz3uo3alnqwae%40alap3.anarazel.de", "msg_date": "Mon, 2 Aug 2021 09:41:24 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "straightening out backend process startup" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> I think there's quite a few different issues around this - here I'm just\n> trying to tackle a few of the most glaring (to me):\n\nNo opinion yet about most of this, but I did want to react to\n\n> In fact, I think there's a good argument to be made that we should\n> entirely remove the concept of BackendIds and just use pgprocnos. We\n> have a fair number of places like SignalVirtualTransaction() that need\n> to search the procarray just to find the proc to signal based on the\n> BackendId. If we used pgprocno instead, that'd not be needed.\n\nIf I understand what you're suggesting, it'd result in unused slots\nin sinvaladt.c's procState[] array, which could create an annoying\ndrag on performance. However, I think it might be reasonable to\nswitch other things over to using pgprocnos, with an eye to\neventually making BackendIds private to the sinval mechanism.\nThere's certainly no strong reason why sinval's array indexes\nneed to be used as identifiers by other modules.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 02 Aug 2021 12:57:36 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: straightening out backend process startup" }, { "msg_contents": "Hi,\n\nOn 2021-08-02 12:57:36 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > I think there's quite a few different issues around this - here I'm just\n> > trying to tackle a few of the most glaring (to me):\n> \n> No opinion yet about most of this, but I did want to react to\n> \n> > In fact, I think there's a good argument to be made that we should\n> > entirely remove the concept of BackendIds and just use pgprocnos. We\n> > have a fair number of places like SignalVirtualTransaction() that need\n> > to search the procarray just to find the proc to signal based on the\n> > BackendId. If we used pgprocno instead, that'd not be needed.\n> \n> If I understand what you're suggesting, it'd result in unused slots\n> in sinvaladt.c's procState[] array, which could create an annoying\n> drag on performance.\n\nYea, I was looking into that, which is why I don't yet have a patch. I think\nit might be reasonable to address this by making pgprocnos more dense. We\nright now actually have a kind of maximally bad allocation pattern for\npgprocnos - InitProcGlobal puts them onto the free lists in reverse\norder. Which means that ProcArrayAdd() will have to move all procs...\n\n\nBut, as you say:\n\n> However, I think it might be reasonable to switch other things over to\n> using pgprocnos, with an eye to eventually making BackendIds private\n> to the sinval mechanism. There's certainly no strong reason why\n> sinval's array indexes need to be used as identifiers by other\n> modules.\n\nI think it'd entirely be reasonable to switch over at least backend_status.c,\nprocsignal.c to pgprocnos without doing anything about the density of\nallocation. We'd likely would want to do that as independent steps anyway,\neven if we were to switch over sinval as well.\n\n\nAnother approach to deal with this could be to simply not do the O(n) work in\nSIInsertDataEntries(). It's not obvious that ->hasMessages is actually\nnecessary - we could atomically read maxMsgNum without acquiring a lock\ninstead of needing the per-backend ->hasMessages. I don't the density would\nbe a relevant factor in SICleanupQueue().\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 2 Aug 2021 10:12:55 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: straightening out backend process startup" }, { "msg_contents": "At Mon, 2 Aug 2021 09:41:24 -0700, Andres Freund <andres@anarazel.de> wrote in \n> Hi,\n> \n> I've previously complained ([1]) that process initialization has gotten\n> very complicated. I hit this once more last week when trying to commit\n> one of the shared memory stats pieces...\n> \n> I think there's quite a few different issues around this - here I'm just\n> trying to tackle a few of the most glaring (to me):\n> \n> - AuxiliaryProcessMain() is used for two independent tasks: Start bootstrap /\n> checker mode and starting auxiliary processes. In HEAD there's maybe 5 lines\n> out 250 that are actually common to both uses.\n> \n> A related oddity is that we reserve shared memory resources for bootstrap &\n> checker aux processes, despite those never existing.\n> \n> This is addressed in patches 1-7\n> \n> - The order of invocation of InitProcess()/InitAuxiliaryProcess() and\n> BaseInit() depends on EXEC_BACKEND. Due to that there often is no single\n> place initialization code can be put if it needs any locks.\n> \n> This is addressed in patches 8-9\n> \n> - PostgresMain() has code for single user and multi user interleaved, making\n> it unnecessarily hard to understand what's going on.\n> \n> This is addressed in patches 10\n> \n> \n> This isn't a patch series ready to commit, there's a bunch of polishing that\n> needs to be done if there's agreement.\n> \n> \n> Questions I have:\n> \n> - What exactly to do with checker mode: Keep it as part of bootstrap, separate\n> it out completely? What commandline flags?\n\nChecker tries to attach shared memory just to make sure it is actually\nattachable with a set of parameters. It is similar to bootstrap as it\nis not run under postmaster but similar to auxiliary process as it\nneeds to attach shared memory. If we are going to get rid of\nshared-memory access by bootstrap, or get rid of the bootstrap itself,\nchecker should be separated out from bootstrap.\n\n> - I used a separate argv entry to pass the aux proc type - do we rather want\n> to go for the approach that e.g. bgworker went for? Adding code for string\n> splitting seems a bit unnecessary to me.\n\nIt seems to me separate entry is cleaner and robust.\n\n> - PostgresMainSingle() should probably not be in postgres.c. We could put it\n> into postinit.c or ..?\n\nPostgresMainSingle() looks like the single-process version of\nPostgresMain so it is natural that they are placed together in\npostgres.c. If PostgresMainSingle is constructed as initializing\nstandalone first then calling PostgresMain, it might be right that\nPostgresMain calls the initialization function resides in postinit.c\nif !IsUnderPostmaster.\n\nPostgresMain()\n{\n if (!IsUnderPostmaster)\n \tInitSinglePostgres(argv[0]);\n ...\n\n> - My first attempt at PostgresMainSingle() separated the single/multi user\n> cases a bit more than the code right now, by having a PostgresMainCommon()\n> which was called by PostgresMainSingle(), PostgresMain(). *Common only\n> started with the MessageContext allocation, which did have the advantage of\n> splitting out a few of the remaining conditional actions in PostgresMain()\n> (PostmasterContext, welcome banner, Log_disconnections). But lead to a bit\n> more duplication. I don't really have an opinion on what's better.\n\nI'm not sure how it looked like, but isn't it reasonable that quickdie\nand log_disconnections(). handle IsUnderPostmaster instead? Or for\nlog_disconnections, Log_disconnections should be turned off at\nstandalone-initialization?\n\n> - I had to move the PgStartTime computation to a bit earlier for single user\n> mode. That seems to make sense to me anyway, given that postmaster does so\n> fairly early too.\n> \n> Any reason that'd be a bad idea?\n> \n> Arguably it should even be a tad earlier to be symmetric.\n\nWhy don't you move the code for multiuser as earlier as standalone does?\n\n> There's one further issue that I think is big enough to be worth\n> tackling in the near future: Too many things depend on BackendIds.\n> \n> Aux processes need procsignal and backend status reporting, which use\n> BackendId for indexing. But they don't use sinval, so they don't have a\n> BackendId - so we have hacks to work around that in a few places. If we\n> instead make those places use pgprocno for indexing the whole issue\n> vanishes.\n> \n> In fact, I think there's a good argument to be made that we should\n> entirely remove the concept of BackendIds and just use pgprocnos. We\n> have a fair number of places like SignalVirtualTransaction() that need\n> to search the procarray just to find the proc to signal based on the\n> BackendId. If we used pgprocno instead, that'd not be needed.\n> \n> But perhaps that's a separate thread.\n> \n> Greetings,\n> \n> Andres Freund\n> \n> [1] https://postgr.es/m/20210402002240.56cuz3uo3alnqwae%40alap3.anarazel.de\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Tue, 03 Aug 2021 16:50:24 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: straightening out backend process startup" }, { "msg_contents": "On Mon, Aug 2, 2021 at 12:41 PM Andres Freund <andres@anarazel.de> wrote:\n> - AuxiliaryProcessMain() is used for two independent tasks: Start bootstrap /\n> checker mode and starting auxiliary processes. In HEAD there's maybe 5 lines\n> out 250 that are actually common to both uses.\n>\n> A related oddity is that we reserve shared memory resources for bootstrap &\n> checker aux processes, despite those never existing.\n>\n> This is addressed in patches 1-7\n\nThis all looks pretty mechanical and, I would guess, not very controversial.\n\n> - The order of invocation of InitProcess()/InitAuxiliaryProcess() and\n> BaseInit() depends on EXEC_BACKEND. Due to that there often is no single\n> place initialization code can be put if it needs any locks.\n>\n> This is addressed in patches 8-9\n>\n> - PostgresMain() has code for single user and multi user interleaved, making\n> it unnecessarily hard to understand what's going on.\n>\n> This is addressed in patches 10\n\nThis stuff I'd need to study more in order to have an intelligent opinion.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 4 Aug 2021 16:34:52 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: straightening out backend process startup" }, { "msg_contents": "Hi,\n\nThanks Robert, Horiguchi-san for looking.\n\nOn 2021-08-04 16:34:52 -0400, Robert Haas wrote:\n> On Mon, Aug 2, 2021 at 12:41 PM Andres Freund <andres@anarazel.de> wrote:\n> > - AuxiliaryProcessMain() is used for two independent tasks: Start bootstrap /\n> > checker mode and starting auxiliary processes. In HEAD there's maybe 5 lines\n> > out 250 that are actually common to both uses.\n> >\n> > A related oddity is that we reserve shared memory resources for bootstrap &\n> > checker aux processes, despite those never existing.\n> >\n> > This is addressed in patches 1-7\n>\n> This all looks pretty mechanical and, I would guess, not very controversial.\n\nPushed these patches.\n\n\n> > - The order of invocation of InitProcess()/InitAuxiliaryProcess() and\n> > BaseInit() depends on EXEC_BACKEND. Due to that there often is no single\n> > place initialization code can be put if it needs any locks.\n> >\n> > This is addressed in patches 8-9\n> >\n> > - PostgresMain() has code for single user and multi user interleaved, making\n> > it unnecessarily hard to understand what's going on.\n> >\n> > This is addressed in patches 10\n>\n> This stuff I'd need to study more in order to have an intelligent opinion.\n\nUnless somebody protests soon I plan to push at least the\n\"process startup: Always call Init[Auxiliary]Process() before BaseInit().\"\nportion, as the inconsistent order between EXEC_BACKEND/!EB is making life\nhard for me in other patches.\n\nI don't have a dependency on\n\"process startup: Split single user code out of PostgresMain().\"\nbut it does make the code a good bit more readable imo...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 5 Aug 2021 12:39:17 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: straightening out backend process startup" }, { "msg_contents": "Hi,\n\nOn 2021-08-03 16:50:24 +0900, Kyotaro Horiguchi wrote:\n> At Mon, 2 Aug 2021 09:41:24 -0700, Andres Freund <andres@anarazel.de> wrote in\n> > - PostgresMainSingle() should probably not be in postgres.c. We could put it\n> > into postinit.c or ..?\n>\n> PostgresMainSingle() looks like the single-process version of\n> PostgresMain so it is natural that they are placed together in\n> postgres.c. If PostgresMainSingle is constructed as initializing\n> standalone first then calling PostgresMain, it might be right that\n> PostgresMain calls the initialization function resides in postinit.c\n> if !IsUnderPostmaster.\n>\n> PostgresMain()\n> {\n> if (!IsUnderPostmaster)\n> \tInitSinglePostgres(argv[0]);\n> ...\n\nI find passing argc/argv to functions that don't actually need them, like\nPostgresMain during normal operation, confusing. Especially when the argc/argv\nvalues are just manufactured stuff like in the case of PostgresMain(). So I\nthink it's better to have have the order work the other way round.\n\n\n> > - My first attempt at PostgresMainSingle() separated the single/multi user\n> > cases a bit more than the code right now, by having a PostgresMainCommon()\n> > which was called by PostgresMainSingle(), PostgresMain(). *Common only\n> > started with the MessageContext allocation, which did have the advantage of\n> > splitting out a few of the remaining conditional actions in PostgresMain()\n> > (PostmasterContext, welcome banner, Log_disconnections). But lead to a bit\n> > more duplication. I don't really have an opinion on what's better.\n>\n> I'm not sure how it looked like, but isn't it reasonable that quickdie\n> and log_disconnections(). handle IsUnderPostmaster instead? Or for\n> log_disconnections, Log_disconnections should be turned off at\n> standalone-initialization?\n\nI was wondering about log_disconnections too. The conditional addition of the\ncallback is all that forces log_disconnections to be PGC_SU_BACKEND rather\nthan PGC_SUSET too. So I agree that moving a check for Log_disconnections and\nIsUnderPostmaster into log_disconnections is a good idea.\n\nI don't understand your reference to quickdie() though?\n\n\n> > - I had to move the PgStartTime computation to a bit earlier for single user\n> > mode. That seems to make sense to me anyway, given that postmaster does so\n> > fairly early too.\n> >\n> > Any reason that'd be a bad idea?\n> >\n> > Arguably it should even be a tad earlier to be symmetric.\n>\n> Why don't you move the code for multiuser as earlier as standalone does?\n\nI think it's the other way round - right now the standalone case is much later\nthan the multiuser case. Postmaster determines PgStartTime after creating\nshared memory, just before starting checkpointer / startup process - whereas\nsingle user mode in HEAD does it just before accepting input for the first\ntime.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 5 Aug 2021 12:50:15 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: straightening out backend process startup" }, { "msg_contents": "Hi,\n\nOn 2021-08-05 12:50:15 -0700, Andres Freund wrote:\n> On 2021-08-03 16:50:24 +0900, Kyotaro Horiguchi wrote:\n> > > - My first attempt at PostgresMainSingle() separated the single/multi user\n> > > cases a bit more than the code right now, by having a PostgresMainCommon()\n> > > which was called by PostgresMainSingle(), PostgresMain(). *Common only\n> > > started with the MessageContext allocation, which did have the advantage of\n> > > splitting out a few of the remaining conditional actions in PostgresMain()\n> > > (PostmasterContext, welcome banner, Log_disconnections). But lead to a bit\n> > > more duplication. I don't really have an opinion on what's better.\n> >\n> > I'm not sure how it looked like, but isn't it reasonable that quickdie\n> > and log_disconnections(). handle IsUnderPostmaster instead? Or for\n> > log_disconnections, Log_disconnections should be turned off at\n> > standalone-initialization?\n> \n> I was wondering about log_disconnections too. The conditional addition of the\n> callback is all that forces log_disconnections to be PGC_SU_BACKEND rather\n> than PGC_SUSET too. So I agree that moving a check for Log_disconnections and\n> IsUnderPostmaster into log_disconnections is a good idea.\n\nI did that, and it didn't seem a clear improvement..\n\n\n> > > - I had to move the PgStartTime computation to a bit earlier for single user\n> > > mode. That seems to make sense to me anyway, given that postmaster does so\n> > > fairly early too.\n> > >\n> > > Any reason that'd be a bad idea?\n> > >\n> > > Arguably it should even be a tad earlier to be symmetric.\n> >\n> > Why don't you move the code for multiuser as earlier as standalone does?\n> \n> I think it's the other way round - right now the standalone case is much later\n> than the multiuser case. Postmaster determines PgStartTime after creating\n> shared memory, just before starting checkpointer / startup process - whereas\n> single user mode in HEAD does it just before accepting input for the first\n> time.\n\nDid that in the attached.\n\n\nI've attached the three remaining patches, after some more polish. Unless\nsomebody argues against I plan to commit these soon-ish.\n\nGreetings,\n\nAndres Freund", "msg_date": "Mon, 13 Sep 2021 20:11:29 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: straightening out backend process startup" }, { "msg_contents": "At Mon, 13 Sep 2021 20:11:29 -0700, Andres Freund <andres@anarazel.de> wrote in \n> Hi,\n> \n> On 2021-08-05 12:50:15 -0700, Andres Freund wrote:\n> > On 2021-08-03 16:50:24 +0900, Kyotaro Horiguchi wrote:\n> > > > - My first attempt at PostgresMainSingle() separated the single/multi user\n> > > > cases a bit more than the code right now, by having a PostgresMainCommon()\n> > > > which was called by PostgresMainSingle(), PostgresMain(). *Common only\n> > > > started with the MessageContext allocation, which did have the advantage of\n> > > > splitting out a few of the remaining conditional actions in PostgresMain()\n> > > > (PostmasterContext, welcome banner, Log_disconnections). But lead to a bit\n> > > > more duplication. I don't really have an opinion on what's better.\n> > >\n> > > I'm not sure how it looked like, but isn't it reasonable that quickdie\n> > > and log_disconnections(). handle IsUnderPostmaster instead? Or for\n> > > log_disconnections, Log_disconnections should be turned off at\n> > > standalone-initialization?\n> > \n> > I was wondering about log_disconnections too. The conditional addition of the\n> > callback is all that forces log_disconnections to be PGC_SU_BACKEND rather\n> > than PGC_SUSET too. So I agree that moving a check for Log_disconnections and\n> > IsUnderPostmaster into log_disconnections is a good idea.\n> \n> I did that, and it didn't seem a clear improvement..\n\nSorry for bothering you about that..\n\n> > > > - I had to move the PgStartTime computation to a bit earlier for single user\n> > > > mode. That seems to make sense to me anyway, given that postmaster does so\n> > > > fairly early too.\n> > > >\n> > > > Any reason that'd be a bad idea?\n> > > >\n> > > > Arguably it should even be a tad earlier to be symmetric.\n> > >\n> > > Why don't you move the code for multiuser as earlier as standalone does?\n> > \n> > I think it's the other way round - right now the standalone case is much later\n> > than the multiuser case. Postmaster determines PgStartTime after creating\n> > shared memory, just before starting checkpointer / startup process - whereas\n> > single user mode in HEAD does it just before accepting input for the first\n> > time.\n> \n> Did that in the attached.\n> \n> \n> I've attached the three remaining patches, after some more polish. Unless\n> somebody argues against I plan to commit these soon-ish.\n\n0001 looks fine.\n\n0002: Looks fine in conjunction with 0003.\n\n0003:\n\nPostgresSingleUserMain doesn't set processing mode. It is fine as it\nis initialied to InitProcessing at process start. On the other hand,\nPostgresMain sets it to InitProcessing but it seems to me it is always\nInitProcessing when entering the function. In the first place isn't\nInitProcessing the initial state and won't be transitioned from other\nstates? However, it would be another issue even if it is right.\n\nSo, everything looks fine to me.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Tue, 14 Sep 2021 13:56:52 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: straightening out backend process startup" }, { "msg_contents": "Hi, \n\nOn September 13, 2021 9:56:52 PM PDT, Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote:\n>At Mon, 13 Sep 2021 20:11:29 -0700, Andres Freund <andres@anarazel.de> wrote in \n>> Hi,\n>> \n>> On 2021-08-05 12:50:15 -0700, Andres Freund wrote:\n>> > On 2021-08-03 16:50:24 +0900, Kyotaro Horiguchi wrote:\n>> > > > - My first attempt at PostgresMainSingle() separated the single/multi user\n>> > > > cases a bit more than the code right now, by having a PostgresMainCommon()\n>> > > > which was called by PostgresMainSingle(), PostgresMain(). *Common only\n>> > > > started with the MessageContext allocation, which did have the advantage of\n>> > > > splitting out a few of the remaining conditional actions in PostgresMain()\n>> > > > (PostmasterContext, welcome banner, Log_disconnections). But lead to a bit\n>> > > > more duplication. I don't really have an opinion on what's better.\n>> > >\n>> > > I'm not sure how it looked like, but isn't it reasonable that quickdie\n>> > > and log_disconnections(). handle IsUnderPostmaster instead? Or for\n>> > > log_disconnections, Log_disconnections should be turned off at\n>> > > standalone-initialization?\n>> > \n>> > I was wondering about log_disconnections too. The conditional addition of the\n>> > callback is all that forces log_disconnections to be PGC_SU_BACKEND rather\n>> > than PGC_SUSET too. So I agree that moving a check for Log_disconnections and\n>> > IsUnderPostmaster into log_disconnections is a good idea.\n>> \n>> I did that, and it didn't seem a clear improvement..\n>\n>Sorry for bothering you about that..\n\nI thought it might look better too. Might still be worth later, just to make the guc SUSET.\n\n\n>> > > > - I had to move the PgStartTime computation to a bit earlier for single user\n>> > > > mode. That seems to make sense to me anyway, given that postmaster does so\n>> > > > fairly early too.\n>> > > >\n>> > > > Any reason that'd be a bad idea?\n>> > > >\n>> > > > Arguably it should even be a tad earlier to be symmetric.\n>> > >\n>> > > Why don't you move the code for multiuser as earlier as standalone does?\n>> > \n>> > I think it's the other way round - right now the standalone case is much later\n>> > than the multiuser case. Postmaster determines PgStartTime after creating\n>> > shared memory, just before starting checkpointer / startup process - whereas\n>> > single user mode in HEAD does it just before accepting input for the first\n>> > time.\n>> \n>> Did that in the attached.\n>> \n>> \n>> I've attached the three remaining patches, after some more polish. Unless\n>> somebody argues against I plan to commit these soon-ish.\n>\n>0001 looks fine.\n>\n>0002: Looks fine in conjunction with 0003.\n>\n>0003:\n>\n>PostgresSingleUserMain doesn't set processing mode. It is fine as it\n>is initialied to InitProcessing at process start. On the other hand,\n>PostgresMain sets it to InitProcessing but it seems to me it is always\n>InitProcessing when entering the function. In the first place isn't\n>InitProcessing the initial state and won't be transitioned from other\n>states? However, it would be another issue even if it is right.\n\nI don't think it should be accessed during the stuff that PostgresSingleUserMain() does. The catalog access / cache initialization continues to happen below PostgresMain(). I guess a comment wouldn't me amiss.\n\nI think we have way too many different process type & state variables :(\n\nAndres\n\n\n\n-- \nSent from my Android device with K-9 Mail. Please excuse my brevity.\n\n\n", "msg_date": "Mon, 13 Sep 2021 22:19:14 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: straightening out backend process startup" } ]
[ { "msg_contents": "Hi,\n\nI'm attempting to develop a new type of full-text index. I've started\nbuilding a new index access method.\n\nIs it possible to calculate values during the index scan and then make\nthem available for display in a select clause? For example,\n\nSELECT title, score, total_hits\nFROM mytable\nWHERE (some search expression here)\nORDER BY score DESC\nLIMIT 10\n\nIn this case, the index access method would calculate a score for each\nrow and attach it to the row for display. It would also calculate the\ntotal number of hits, that is, rows that would be returned if there\nwere no LIMIT clause, and attach it only to the first row.\n\nIs this possible?\n\nIs it possible to do it with a table access method, as opposed to an\nindex access method?\n\n-- \nChris Cleveland\n312-339-2677 mobile\n\n\n", "msg_date": "Mon, 2 Aug 2021 11:41:51 -0500", "msg_from": "Chris Cleveland <ccleveland@dieselpoint.com>", "msg_from_op": true, "msg_subject": "Passing data out of indexam or tableam" } ]
[ { "msg_contents": "\nI have pushed Release 13 of the PostgreSQL BuildFarm client.\n\n\nChange highlights:\n\n * add tests for a few cases that were previously missing\n * more fine-grained control over which TAP test sets run\n * --no-keepall can be specified on the command line\n * repair a repo if it crashed during a copy operation\n * make sure the repo is really clean (including free of ignored files)\n * generate stack traces on CYGWIN\n * collect stack traces for TAP tests\n * Extract MSVC settings at runtime rather than had coding them in the\n config file (see below)\n * cross version upgrade tests now run on Windows, both for msys2 and\n MSVC builds\n * add support for inhibit-runs and force-one-run trigger files( see below)\n * add experimental module for running arbitrary out of tree TAP tests\n * Adjust if an upstream repo changes the default branch name (see below)\n * add use_discard_caches caches setting (see below)\n\n\nMSVC animals are now very much simpler to set up, and to upgrade to a\nnew compiler. Using the new mechanism, as shown in the sample config\nfile, all that's needed is to specify a location where the standard\nscript vcvarsall.bat can be found. The script will then run that script\nand extract the settings and apply them. Tha means that upgrading to a\nnew version of Visual Studio would entail just a one line change in the\nconfig file.\n\nIf you put a file called <animalname>.inhibit-runs in the build root,\nall runs will be stopped until the file is removed. If you put a file\ncalled <animalname>.force-one-run in the build root, each configured\nbranch will forced to run once, and the file will be removed. These only\napply if you use the run_branches.pl script.\n\nThe client should transparently deal with any change that is made in the\nupstream repository's default branch name. This avoids the need for a\nflag day when we eventually change the default branch name for\npostgresql, as I assume we will do before long. The branch bf_HEAD which\nthe client creates now refers to the upstream default whatever it might\nbe, rather than the hardcoded name 'master'. The code of the SCM module\nunderwent quite a lot of change in order to make this happen; the\ncheckout code had become quite long and convoluted and I had to refactor\nit somewhat before I was able to make and test this change. The changes\nhave been fairly extensively tested, but I'm still slightly nervous\nabout them. Owners are asked to report any issues promptly.\n\nthe `use_discard_caches` setting reflects a change in the way postgres\nhandles this - it's now a runtime setting rather than a compile time\nsetting. On older branches it sets \"-DCLOBBER_CACHE_ALWAYS\". If you use\nthis setting don't use that define.\n\n\nDownloads are available at\n<https://github.com/PGBuildFarm/client-code/releases> and\n<https://buildfarm.postgresql.org/downloads>\n\n\ncheers\n\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Mon, 2 Aug 2021 16:50:13 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": true, "msg_subject": "Release 13 of the PostgreSQL BuildFarm client" }, { "msg_contents": "Andrew Dunstan <andrew@dunslane.net> writes:\n> I have pushed Release 13 of the PostgreSQL BuildFarm client.\n\nFYI, this seems to have broken compatibility with ancient versions\nof git. prairiedog and gaur/pademelon are both using\ngit version 1.7.9.6, and they both choked on the --prune-tags\noption. I tried removing that, as it seemed possibly unnecessary,\nbut it didn't improve matters.\n\nI suppose I'm overdue to update git on these machines, but anyone\nelse running dinosaur versions may want to be cautious.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 02 Aug 2021 19:11:10 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Release 13 of the PostgreSQL BuildFarm client" }, { "msg_contents": "\nOn 8/2/21 7:11 PM, Tom Lane wrote:\n> Andrew Dunstan <andrew@dunslane.net> writes:\n>> I have pushed Release 13 of the PostgreSQL BuildFarm client.\n> FYI, this seems to have broken compatibility with ancient versions\n> of git. prairiedog and gaur/pademelon are both using\n> git version 1.7.9.6, and they both choked on the --prune-tags\n> option. I tried removing that, as it seemed possibly unnecessary,\n> but it didn't improve matters.\n\n\n\nOuch.\n\n\n--prune-tags possibly is unnecessary. What happens when you remove it\nfrom the code?\n\n\nI will test tomorrow or Wednesday on a Centos5 docker  - there is an\nimage on dockerhub with git 1.6.\n\n\ncheers\n\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Mon, 2 Aug 2021 21:50:19 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": true, "msg_subject": "Re: Release 13 of the PostgreSQL BuildFarm client" }, { "msg_contents": "Andrew Dunstan <andrew@dunslane.net> writes:\n> --prune-tags possibly is unnecessary. What happens when you remove it\n> from the code?\n\nThis:\n\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=gaur&dt=2021-08-03%2002%3A07%3A56\n\nwhich I can't make much sense of.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 02 Aug 2021 22:12:22 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Release 13 of the PostgreSQL BuildFarm client" }, { "msg_contents": "\n\n\n> On Aug 2, 2021, at 10:12 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Andrew Dunstan <andrew@dunslane.net> writes:\n>> --prune-tags possibly is unnecessary. What happens when you remove it\n>> from the code?\n> \n> This:\n> \n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=gaur&dt=2021-08-03%2002%3A07%3A56\n> \n> which I can't make much sense of.\n\nI guess it’s failing on the ls-remote or symbolic-ref command.\n\nCheers\n\nAndrew\n\n\n\n\n", "msg_date": "Mon, 2 Aug 2021 22:56:40 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": true, "msg_subject": "Re: Release 13 of the PostgreSQL BuildFarm client" }, { "msg_contents": "\nOn 8/2/21 7:11 PM, Tom Lane wrote:\n> Andrew Dunstan <andrew@dunslane.net> writes:\n>> I have pushed Release 13 of the PostgreSQL BuildFarm client.\n> FYI, this seems to have broken compatibility with ancient versions\n> of git. prairiedog and gaur/pademelon are both using\n> git version 1.7.9.6, and they both choked on the --prune-tags\n> option. I tried removing that, as it seemed possibly unnecessary,\n> but it didn't improve matters.\n>\n> I suppose I'm overdue to update git on these machines, but anyone\n> else running dinosaur versions may want to be cautious.\n\n\nNot so much dinosaurs either. I just tried on Centos 7 which isn't that\nold, and got a failure. Not just from the prune-tags but from 'git\nls-remote' not supporting symref. I will come up with a solution in a\ncouple of days, but for now please don't deploy unless you have a fairly\nmodern git. If you do deploy, be prepared to roll back.\n\n\ncheers\n\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Tue, 3 Aug 2021 08:47:04 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": true, "msg_subject": "Re: Release 13 of the PostgreSQL BuildFarm client" }, { "msg_contents": "Andrew Dunstan <andrew@dunslane.net> writes:\n> I have pushed Release 13 of the PostgreSQL BuildFarm client.\n> ...\n> the `use_discard_caches` setting reflects a change in the way postgres\n> handles this - it's now a runtime setting rather than a compile time\n> setting. On older branches it sets \"-DCLOBBER_CACHE_ALWAYS\". If you use\n> this setting don't use that define.\n\nI'd just like to take a moment to recommend that owners of\nCLOBBER_CACHE_ALWAYS animals adopt this new way of doing things.\n\nFor PG 13 and earlier branches, this makes no difference --- it's\njust an indirect way of adding \"-DCLOBBER_CACHE_ALWAYS\". However,\nfor v14 and up, it does not do that but builds the binaries normally.\nThen, cache-clobber testing is performed by adding \"use_discard_caches=1\"\nas a GUC setting. The reason this is useful is that we can skip running\nindividual tests in cache-clobber mode when we choose to. As of\nthe new buildfarm client, this is exploited by skipping clobber mode\nfor initdb runs that are part of other tests. (We still run initdb in\nclobber mode in the initdb-LOCALE steps, so we aren't losing coverage.)\nThat makes a noticeable difference in the standard set of tests, but\nwhere it really shines is if you enable TAP testing --- those tests\notherwise spend nearly half their time running initdb :-(.\n\nThe last I checked, no buildfarm animals were running with both\n--enable-tap-tests and CLOBBER_CACHE_ALWAYS, which was reasonable\nbecause it just took insanely long. However, if you've got a fast\nmachine you may find that --enable-tap-tests plus use_discard_caches\nis tolerable now ... at least in v14 and later branches.\n\nI don't normally run my animal \"sifaka\" in cache-clobber mode, but\nI did do a couple of runs that way while testing the new buildfarm\nclient. Here's a run with buildfarm client v13, --enable-tap-tests,\nand use_discard_caches:\n\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=sifaka&dt=2021-08-02%2022%3A09%3A03\n\nTotal time 9:21:52. That compares well to this previous run with the\nv12 client:\n\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=sifaka&dt=2021-07-03%2004%3A02%3A16\n\n... total time 16:15:43.\n\nAlso of interest is that a month ago, it took twice as long (32:53:24):\n\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=sifaka&dt=2021-07-01%2018%3A06%3A09\n\nI don't have comparable runs from sifaka before that, but extrapolating\nfrom avocet's times, it would have taken ~ 58.5 hours a year ago.\nThose reductions are from various other changes we've implemented to\nreduce the cost of cache-clobber testing. Hopefully, these fixes\nmake it practical to be more ambitious about how much testing can\nbe done by cache-clobber animals.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 03 Aug 2021 11:01:37 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "CLOBBER_CACHE_ALWAYS testing (was Re: Release 13 of the PostgreSQL\n BuildFarm client)" }, { "msg_contents": "On 8/3/21 8:47 AM, Andrew Dunstan wrote:\n> On 8/2/21 7:11 PM, Tom Lane wrote:\n>> Andrew Dunstan <andrew@dunslane.net> writes:\n>>> I have pushed Release 13 of the PostgreSQL BuildFarm client.\n>> FYI, this seems to have broken compatibility with ancient versions\n>> of git. prairiedog and gaur/pademelon are both using\n>> git version 1.7.9.6, and they both choked on the --prune-tags\n>> option. I tried removing that, as it seemed possibly unnecessary,\n>> but it didn't improve matters.\n>>\n>> I suppose I'm overdue to update git on these machines, but anyone\n>> else running dinosaur versions may want to be cautious.\n>\n> Not so much dinosaurs either. I just tried on Centos 7 which isn't that\n> old, and got a failure. Not just from the prune-tags but from 'git\n> ls-remote' not supporting symref. I will come up with a solution in a\n> couple of days, but for now please don't deploy unless you have a fairly\n> modern git. If you do deploy, be prepared to roll back.\n>\n>\n\nOK, I have come up with this fix. Essentially the code detects if the\ngit version can run `git ls-remote --symref` and refuses to run branch\nname checking code if it fails. It also outputs a warning message unless\nthe config setting skip_git_default_check has been explicitly set. In\neither case the owner will have to update their git installation or face\na flag day event when the default branch name changes.\n\n\nI have tested this on Centos 7 which has a git that's plenty old enough\nto exhibit the problems Tom encountered.\n\n\nI'm planning on issuing a 12.1 release fairly soon with this patch, but\nas I developed it fairly quickly and through the fog of some painkillers\nI'd appreciate more eyes on it first :-)\n\n\ncheers\n\n\nandrew\n\n\n-- \n\nAndrew Dunstan\nEDB: https://www.enterprisedb.com", "msg_date": "Tue, 3 Aug 2021 15:14:41 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": true, "msg_subject": "Re: Release 13 of the PostgreSQL BuildFarm client" }, { "msg_contents": "Andrew Dunstan <andrew@dunslane.net> writes:\n> I'm planning on issuing a 12.1 release fairly soon with this patch, but\n> as I developed it fairly quickly and through the fog of some painkillers\n> I'd appreciate more eyes on it first :-)\n\nI tested this on gaur, and it seems to work --- at least, it gets\nthrough the git checkout step now. (It'll be a few hours before\nthe run finishes.)\n\nOne nit is that personally I could do without this:\n\n+\t\t\tmy $gversion = `git --version`;\n+\t\t\tchomp $gversion;\n+\t\t\tprint \"$gversion too old to for automatic default branch update\\n\";\n\nAside from the message typo, that'll produce useless every-run chatter in\naffected owners' cron logs. I'd probably soon set skip_git_default_check\nto silence it, at which point it might as well not be there.\n\nThanks for fixing it, though. I wasted a couple of hours last night\ntrying to build current git on prairiedog and gaur, with no luck so far.\nI think just blowing away their git repos when the master-branch rename\nhappens will be a much more appropriate amount of effort.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 03 Aug 2021 16:00:00 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Release 13 of the PostgreSQL BuildFarm client" }, { "msg_contents": "\nOn 8/3/21 4:00 PM, Tom Lane wrote:\n> Andrew Dunstan <andrew@dunslane.net> writes:\n>> I'm planning on issuing a 12.1 release fairly soon with this patch, but\n>> as I developed it fairly quickly and through the fog of some painkillers\n>> I'd appreciate more eyes on it first :-)\n> I tested this on gaur, and it seems to work --- at least, it gets\n> through the git checkout step now. (It'll be a few hours before\n> the run finishes.)\n>\n> One nit is that personally I could do without this:\n>\n> +\t\t\tmy $gversion = `git --version`;\n> +\t\t\tchomp $gversion;\n> +\t\t\tprint \"$gversion too old to for automatic default branch update\\n\";\n>\n> Aside from the message typo, that'll produce useless every-run chatter in\n> affected owners' cron logs. I'd probably soon set skip_git_default_check\n> to silence it, at which point it might as well not be there.\n\n\nI'll fix the typo and make it only print the warning in verbose mode, I\nhope that will suit. On those machines where you can't update git you\nshould just set skip_git_default_check.\n\n\n>\n> Thanks for fixing it, though. I wasted a couple of hours last night\n> trying to build current git on prairiedog and gaur, with no luck so far.\n> I think just blowing away their git repos when the master-branch rename\n> happens will be a much more appropriate amount of effort.\n>\n> \t\t\t\n\n\nIndeed. I've been down that path before, with similar success.\n\n\ncheers\n\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Tue, 3 Aug 2021 19:18:31 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": true, "msg_subject": "Re: Release 13 of the PostgreSQL BuildFarm client" }, { "msg_contents": "Andrew Dunstan <andrew@dunslane.net> writes:\n> On 8/3/21 4:00 PM, Tom Lane wrote:\n>> Aside from the message typo, that'll produce useless every-run chatter in\n>> affected owners' cron logs. I'd probably soon set skip_git_default_check\n>> to silence it, at which point it might as well not be there.\n\n> I'll fix the typo and make it only print the warning in verbose mode, I\n> hope that will suit.\n\nSure, works for me.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 03 Aug 2021 19:32:29 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Release 13 of the PostgreSQL BuildFarm client" } ]
[ { "msg_contents": "Hi!\n\nIn the discussion of [1], the option ASENSITIVE was added to DECLARE.\nI have improved its tab completion and attached a patch.\n\nDo you think?\n\n[1] https://www.postgresql.org/message-id/flat/96ee8b30-9889-9e1b-b053-90e10c050e85%40enterprisedb.com\n\nRegards,\nShinya Kato", "msg_date": "Tue, 3 Aug 2021 01:58:44 +0000", "msg_from": "<Shinya11.Kato@nttdata.com>", "msg_from_op": true, "msg_subject": "fix DECLARE tab completion" }, { "msg_contents": "On Tue, Aug 03, 2021 at 01:58:44AM +0000, Shinya11.Kato@nttdata.com wrote:\n> In the discussion of [1], the option ASENSITIVE was added to DECLARE.\n> I have improved its tab completion and attached a patch.\n> \n> Do you think?\n\nThanks, fixed.\n--\nMichael", "msg_date": "Tue, 10 Aug 2021 16:03:18 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: fix DECLARE tab completion" } ]
[ { "msg_contents": "Hi,\n\nI don't think I really understand what decides what should use\nbefore_shmem_exit() and what into on_shmem_exit(). The existing comments say:\n\n/* ----------------------------------------------------------------\n *\t\tbefore_shmem_exit\n *\n *\t\tRegister early callback to perform user-level cleanup,\n *\t\te.g. transaction abort, before we begin shutting down\n *\t\tlow-level subsystems.\n * ----------------------------------------------------------------\n */\n\n/* ----------------------------------------------------------------\n *\t\ton_shmem_exit\n *\n *\t\tRegister ordinary callback to perform low-level shutdown\n *\t\t(e.g. releasing our PGPROC); run after before_shmem_exit\n *\t\tcallbacks and before on_proc_exit callbacks.\n * ----------------------------------------------------------------\n */\n\nbut I don't find it super obvious when a subsystem is \"low-level\" or\n\"user-level\". Which is not helped by a fairly inconsistent use of the\nmechanism. E.g. ParallelWorkerShutdown() is on_*, ShutdownPostgres,\nShutdownAuxiliaryProcess are before_* and I can't really make sense of that.\n\nNor do I really understand why dsm_backend_shutdown() is scheduled to be\nexactly between those phases? That seems to indicate that no \"low-level\"\nsubsystem could ever use DSM, but I don't really understand that either. I\nrealize it has to be reliably be re-invoked in case of errors as the comment\nin shmem_exit() explains - but does not really explain why that's the right\nmoment to shut down DSM.\n\nI suspect it's mostly pragmatic, because it has to happen before we tear down\n\"really fundamental\" subsystems, but there's no easy way to call\ndsm_backend_shutdown() repeatedly at that point?\n\n\nThe concrete reason I am asking is that for the shared memory stats patch I\nneeded to adjust a few on/before determinations. The fundamental reason for\nthat is that the shared memory stats patch uses DSM (since stats are variably\nsized), which means that anything that could report stats needs to happen in\nbefore_shmem_exit().\n\nTo make things work in a halfway reasonable fashion I needed to adjust:\n\n1) Single user mode using on_shmem_exit(ShutdownXLOG()) to before*. From the\n stats side that makes sense - clearly checkpoints can produce stat worthy\n stuff, so it has to happen before the stats subsystem is inactive. I don't\n know if it's \"low-level\" in the sense referenced in the comments above\n though.\n\n2) Change ParallelWorkerShutdown to before*. That seems consistent with other\n *Shutdown* routines, so ...\n\n3) Have ParallelWorkerShutdown() also trigger detaching from its dsm\n segment. Some on_dsm_detach() callbacks trigger stats (e.g. sharedfileset.c\n causes fd.c to do ReportTemporaryFileUsage()), which still need to be\n reported.\n\n Unfortunately ordering on_dsm_detach() callbacks is *not* sufficient,\n because dsa.c needs to be able to create new dsm segments if the amount of\n stats grow - and those will be put at the head of dsm_segment_list, which\n in turn will lead to dsm_backend_shutdown() to detach from that newly added\n segment last. Oops.\n\nPragmatically I can live with all of these changes and I don't think they\nshould be blockers for the shmem stats patch.\n\n\nHowever, this situation feels deeply unsatisfying. We have to be very careful\nabout nesting initialization of subsystems correctly (see e.g. comments for\nShutdownPostgres's registration), there's no way to order dsm callbacks in a\nproper order, on_shmem_exit is used for things ranging from\npgss_shmem_shutdown over ProcKill to IpcMemoryDelete, ...\n\nIOW, the reason that I am (and I think others) are struggling with\nbefore/on_shmem_exit is that the division is not really good enough.\n\nI'm not even convinced that dynamic registration of such callbacks is a good\nidea. At least for the important in core stuff it might be better to have a\ncentrally maintained ordering of callbacks, plus a bit of state describing how\nfar teardown has progressed (to deal with failing callback issues).\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 2 Aug 2021 19:36:12 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Dividing line between before_shmem_exit and on_shmem_exit?" } ]
[ { "msg_contents": "Hi all,\n\nWhile working on a patch adding new stats, houzj pointed out that\n'len' function arguments of all pgstat_recv_* functions are not used\nat all. Looking at git history, pgstat_recv_* functions have been\nhaving ‘len’ since the stats collector was introduced by commit\n140ddb78fe 20 years ago but it was not used at all even in the first\ncommit. It seems like the improvements so far for the stats collector\nhad pgstat_recv_* function have ‘len’ for consistency with the\nexisting pgstat_recv_* functions. Is there any historical reason for\nhaving 'len' argument? Or can we remove them?\n\nI've attached the patch that removes 'len' from all pgstat_recv_* functions.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/", "msg_date": "Tue, 3 Aug 2021 12:40:23 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": true, "msg_subject": "Remove unused 'len' from pg_stat_recv_* functions" }, { "msg_contents": "At Tue, 3 Aug 2021 12:40:23 +0900, Masahiko Sawada <sawada.mshk@gmail.com> wrote in \r\n> Hi all,\r\n> \r\n> While working on a patch adding new stats, houzj pointed out that\r\n> 'len' function arguments of all pgstat_recv_* functions are not used\r\n> at all. Looking at git history, pgstat_recv_* functions have been\r\n> having ‘len’ since the stats collector was introduced by commit\r\n> 140ddb78fe 20 years ago but it was not used at all even in the first\r\n> commit. It seems like the improvements so far for the stats collector\r\n> had pgstat_recv_* function have ‘len’ for consistency with the\r\n> existing pgstat_recv_* functions. Is there any historical reason for\r\n> having 'len' argument? Or can we remove them?\r\n> \r\n> I've attached the patch that removes 'len' from all pgstat_recv_* functions.\r\n\r\nI at the first look thought that giving \"len\" as a parameter is\r\nreasonable as message-processing functions, but the given message\r\nstruct contains the same value and the functions can refer to the\r\nmessage length without the parameter if they want. So I'm +-0 for the\r\nremoval.\r\n\r\nIt applies cleanly on the master and compiled without an error.\r\n\r\nThat being said, I'm not sure it is worthwhile to change parameters of\r\ngoing-to-be-removed functions (if shared-memory stats collector is\r\nsuccessfully introduced).\r\n\r\nregards.\r\n\r\n-- \r\nKyotaro Horiguchi\r\nNTT Open Source Software Center\r\n", "msg_date": "Tue, 03 Aug 2021 15:17:10 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Remove unused 'len' from pg_stat_recv_* functions" }, { "msg_contents": "On Tue, Aug 3, 2021 at 3:17 PM Kyotaro Horiguchi\n<horikyota.ntt@gmail.com> wrote:\n>\n> At Tue, 3 Aug 2021 12:40:23 +0900, Masahiko Sawada <sawada.mshk@gmail.com> wrote in\n> > Hi all,\n> >\n> > While working on a patch adding new stats, houzj pointed out that\n> > 'len' function arguments of all pgstat_recv_* functions are not used\n> > at all. Looking at git history, pgstat_recv_* functions have been\n> > having ‘len’ since the stats collector was introduced by commit\n> > 140ddb78fe 20 years ago but it was not used at all even in the first\n> > commit. It seems like the improvements so far for the stats collector\n> > had pgstat_recv_* function have ‘len’ for consistency with the\n> > existing pgstat_recv_* functions. Is there any historical reason for\n> > having 'len' argument? Or can we remove them?\n> >\n> > I've attached the patch that removes 'len' from all pgstat_recv_* functions.\n>\n> I at the first look thought that giving \"len\" as a parameter is\n> reasonable as message-processing functions, but the given message\n> struct contains the same value and the functions can refer to the\n> message length without the parameter if they want. So I'm +-0 for the\n> removal.\n>\n> It applies cleanly on the master and compiled without an error.\n>\n> That being said, I'm not sure it is worthwhile to change parameters of\n> going-to-be-removed functions (if shared-memory stats collector is\n> successfully introduced).\n\nGood point.\n\nI'm not going to insist on removing them but I got confused a bit\nwhether or not I should add 'len' when writing a new pgstat_recv_*\nfunction.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Tue, 3 Aug 2021 16:56:12 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Remove unused 'len' from pg_stat_recv_* functions" }, { "msg_contents": "On 2021-08-03 16:56:12 +0900, Masahiko Sawada wrote:\n> On Tue, Aug 3, 2021 at 3:17 PM Kyotaro Horiguchi\n> <horikyota.ntt@gmail.com> wrote:\n> >\n> > At Tue, 3 Aug 2021 12:40:23 +0900, Masahiko Sawada <sawada.mshk@gmail.com> wrote in\n> > > Hi all,\n> > >\n> > > While working on a patch adding new stats, houzj pointed out that\n> > > 'len' function arguments of all pgstat_recv_* functions are not used\n> > > at all. Looking at git history, pgstat_recv_* functions have been\n> > > having ‘len’ since the stats collector was introduced by commit\n> > > 140ddb78fe 20 years ago but it was not used at all even in the first\n> > > commit. It seems like the improvements so far for the stats collector\n> > > had pgstat_recv_* function have ‘len’ for consistency with the\n> > > existing pgstat_recv_* functions. Is there any historical reason for\n> > > having 'len' argument? Or can we remove them?\n> > >\n> > > I've attached the patch that removes 'len' from all pgstat_recv_* functions.\n> >\n> > I at the first look thought that giving \"len\" as a parameter is\n> > reasonable as message-processing functions, but the given message\n> > struct contains the same value and the functions can refer to the\n> > message length without the parameter if they want. So I'm +-0 for the\n> > removal.\n> >\n> > It applies cleanly on the master and compiled without an error.\n> >\n> > That being said, I'm not sure it is worthwhile to change parameters of\n> > going-to-be-removed functions (if shared-memory stats collector is\n> > successfully introduced).\n> \n> Good point.\n\nIndeed. It's already kinda painful to maintain the shared memory stats patch,\nno need to make it harder...\n\n\n> I'm not going to insist on removing them but I got confused a bit\n> whether or not I should add 'len' when writing a new pgstat_recv_*\n> function.\n\nI'd keep it in sync with what's there right now.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 3 Aug 2021 11:27:40 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Remove unused 'len' from pg_stat_recv_* functions" } ]
[ { "msg_contents": "Hi hackers,\n\nIn each PathKey we have an EC representing the value being sorted on.\nThis works correctly and efficiently in scan/join planning since the\nmembers in an EC are always equal to each other.\n\nHowever, after applying GROUP BY grouping sets, the members in an EC may\nnot be that equivalent any more, because NULLS may be emitted by\ngrouping sets. As a result, we may lose some sort keys incorrectly.\n\n# explain (costs off) select a, b from foo where a = b group by cube(a, b)\norder by a, b;\n QUERY PLAN\n-------------------------------\n Sort\n Sort Key: a\n -> MixedAggregate\n Hash Key: a, b\n Hash Key: a\n Hash Key: b\n Group Key: ()\n -> Seq Scan on foo\n Filter: (a = b)\n(9 rows)\n\nI believe we should not ignore sort key 'b' in the query above.\n\nIs this a problem we should be worried about?\n\nThanks\nRichard\n\nHi hackers,In each PathKey we have an EC representing the value being sorted on.This works correctly and efficiently in scan/join planning since themembers in an EC are always equal to each other.However, after applying GROUP BY grouping sets, the members in an EC maynot be that equivalent any more, because NULLS may be emitted bygrouping sets. As a result, we may lose some sort keys incorrectly.# explain (costs off) select a, b from foo where a = b group by cube(a, b) order by a, b;          QUERY PLAN------------------------------- Sort   Sort Key: a   ->  MixedAggregate         Hash Key: a, b         Hash Key: a         Hash Key: b         Group Key: ()         ->  Seq Scan on foo               Filter: (a = b)(9 rows)I believe we should not ignore sort key 'b' in the query above.Is this a problem we should be worried about?ThanksRichard", "msg_date": "Tue, 3 Aug 2021 12:03:29 +0800", "msg_from": "Richard Guo <guofenglinux@gmail.com>", "msg_from_op": true, "msg_subject": "Sort keys are omitted incorrectly after grouping sets" }, { "msg_contents": "On Tue, 3 Aug 2021 at 00:04, Richard Guo <guofenglinux@gmail.com> wrote:\n>\n> Is this a problem we should be worried about?\n\nIt's easy to see this produce output in the wrong order:\n\npostgres=# select a, b from (values (1,1),(2,2)) as foo(a,b) where a =\nb group by cube(a, b) order by a, b nulls first;\n a | b\n---+---\n 1 |\n 1 | 1\n 2 | 2\n 2 |\n |\n | 1\n | 2\n(7 rows)\n\npostgres=# select a, b from (values (1,1),(2,2)) as foo(a,b) where a =\nb group by cube(a, b) order by a, b nulls last;\n a | b\n---+---\n 1 |\n 1 | 1\n 2 | 2\n 2 |\n |\n | 1\n | 2\n(7 rows)\n\nI know we had a hack to deal with outer joins \"placeholder vars\" or\nsomething like that. I imagine the same thing needs to happen here.\n\nIncidentally, the same thing doesn't happen for a VALUES clause with a\nsingle row value. There it seems we inline the row value and the plan\nends up ordering on both -- though it's hard to tell because the way\nthe explain plan is formatted makes it hard to see what's going on:\n\npostgres=# select a, b from (values (1,1)) as foo(a,b) where a = b\ngroup by cube(a, b) order by a, b nulls first;\n a | b\n---+---\n 1 |\n 1 | 1\n |\n | 1\n(4 rows)\n\n\npostgres=# explain select a, b from (values (1,1)) as foo(a,b) where a\n= b group by cube(a, b) order by a, b nulls first;\n QUERY PLAN\n--------------------------------------------------------\n Sort (cost=0.10..0.11 rows=4 width=8)\n Sort Key: (1), (1) NULLS FIRST\n -> MixedAggregate (cost=0.00..0.06 rows=4 width=8)\n Hash Key: 1, 1\n Hash Key: 1\n Hash Key: 1\n Group Key: ()\n -> Result (cost=0.00..0.01 rows=1 width=8)\n One-Time Filter: (1 = 1)\n(9 rows)\n\nWith two rows we're clearly not inlining it and clearly ordering on\nonly the first column:\n\npostgres=# explain select a, b from (values (1,1),(2,2)) as foo(a,b)\nwhere a = b group by cube(a, b) order by a, b nulls first;\n QUERY PLAN\n-------------------------------------------------------------------------\n Sort (cost=0.12..0.13 rows=4 width=8)\n Sort Key: \"*VALUES*\".column1\n -> MixedAggregate (cost=0.00..0.08 rows=4 width=8)\n Hash Key: \"*VALUES*\".column1, \"*VALUES*\".column2\n Hash Key: \"*VALUES*\".column1\n Hash Key: \"*VALUES*\".column2\n Group Key: ()\n -> Values Scan on \"*VALUES*\" (cost=0.00..0.03 rows=1 width=8)\n Filter: (column1 = column2)\n(9 rows)\n\n\n-- \ngreg\n\n\n", "msg_date": "Thu, 5 Aug 2021 00:18:51 -0400", "msg_from": "Greg Stark <stark@mit.edu>", "msg_from_op": false, "msg_subject": "Re: Sort keys are omitted incorrectly after grouping sets" } ]
[ { "msg_contents": "Hello,\n\nI came across this issue while I was tweaking a TAP test with Ashwin for\nthis thread [1].\n\nWe noticed that while the startup process waits for a recovery delay, it does\nnot respect changes to the recovery_min_apply_delay GUC. So:\n\n// Standby is waiting on recoveryWakeupLatch with a large\nrecovery_min_apply_delay value\nnode_standby->safe_psql('postgres', 'ALTER SYSTEM SET\nrecovery_min_apply_delay TO 0;');\nnode_standby->reload;\n// Standby is still waiting, it does not proceed until the old timeout\nis elapsed.\n\nI attached a small patch to fix this. It makes it so that\nrecovery_min_apply_delay is reconsulted in the loop to redetermine the wait\ninterval. This makes it similar to the loop in CheckpointerMain, where\nCheckPointTimeout is consulted after interrupts are handled:\n\nif (elapsed_secs >= CheckPointTimeout)\ncontinue; /* no sleep for us ... */\n\nI have also added a test to 005_replay_delay.pl.\n\nRegards,\nSoumyadeep(VMware)\n\n[1] https://www.postgresql.org/message-id/flat/CANXE4Tc3FNvZ_xAimempJWv_RH9pCvsZH7Yq93o1VuNLjUT-mQ%40mail.gmail.com", "msg_date": "Mon, 2 Aug 2021 22:21:56 -0700", "msg_from": "Soumyadeep Chakraborty <soumyadeep2007@gmail.com>", "msg_from_op": true, "msg_subject": "Changes to recovery_min_apply_delay are ignored while waiting for\n delay" }, { "msg_contents": "At Mon, 2 Aug 2021 22:21:56 -0700, Soumyadeep Chakraborty <soumyadeep2007@gmail.com> wrote in \n> Hello,\n> \n> I came across this issue while I was tweaking a TAP test with Ashwin for\n> this thread [1].\n> \n> We noticed that while the startup process waits for a recovery delay, it does\n> not respect changes to the recovery_min_apply_delay GUC. So:\n> \n> // Standby is waiting on recoveryWakeupLatch with a large\n> recovery_min_apply_delay value\n> node_standby->safe_psql('postgres', 'ALTER SYSTEM SET\n> recovery_min_apply_delay TO 0;');\n> node_standby->reload;\n> // Standby is still waiting, it does not proceed until the old timeout\n> is elapsed.\n> \n> I attached a small patch to fix this. It makes it so that\n> recovery_min_apply_delay is reconsulted in the loop to redetermine the wait\n> interval. This makes it similar to the loop in CheckpointerMain, where\n> CheckPointTimeout is consulted after interrupts are handled:\n> \n> if (elapsed_secs >= CheckPointTimeout)\n> continue; /* no sleep for us ... */\n> \n> I have also added a test to 005_replay_delay.pl.\n> \n> Regards,\n> Soumyadeep(VMware)\n> \n> [1] https://www.postgresql.org/message-id/flat/CANXE4Tc3FNvZ_xAimempJWv_RH9pCvsZH7Yq93o1VuNLjUT-mQ%40mail.gmail.com\n\nSounds reasonable and the patch looks fine as a whole. Applied cleanly\nand works as expected. The added test properly catches the issue.\n\nOne comment from me.\n\n+$node_standby->safe_psql('postgres', \"ALTER SYSTEM SET recovery_min_apply_delay TO 0;\");\n\nIt might be better do \"SET reco.. TO DEFAULT\" instead.\n\nAnd how about adding the new test at the end of existing tests. We can\nget rid of the extra lines in the diff.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Tue, 03 Aug 2021 15:42:48 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Changes to recovery_min_apply_delay are ignored while waiting\n for delay" }, { "msg_contents": "Hi Kyotaro,\n\nThanks for the review!\n\nOn Mon, Aug 2, 2021 at 11:42 PM Kyotaro Horiguchi\n<horikyota.ntt@gmail.com> wrote:\n\n> One comment from me.\n>\n> +$node_standby->safe_psql('postgres', \"ALTER SYSTEM SET recovery_min_apply_delay TO 0;\");\n>\n> It might be better do \"SET reco.. TO DEFAULT\" instead.\n>\n\nSure.\n\n> And how about adding the new test at the end of existing tests. We can\n> get rid of the extra lines in the diff.\n\nNo problem. See attached v2. I didn't do that initially as the test file\nlooks as though it is split into two halves: one for testing\nrecovery_min_apply_delay and the other for testing recovery pause. So while\nmaking this change, I added a header comment for the newly added test case.\nPlease take a look.\n\nRegards,\nSoumyadeep (VMware)", "msg_date": "Tue, 3 Aug 2021 00:06:34 -0700", "msg_from": "Soumyadeep Chakraborty <soumyadeep2007@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Changes to recovery_min_apply_delay are ignored while waiting for\n delay" }, { "msg_contents": "Rebased. Also added a stronger check to see if the standby is stuck in\nrecovery_min_apply_delay:\n\n$node_standby->poll_query_until('postgres', qq{\nSELECT wait_event = 'RecoveryApplyDelay' FROM pg_stat_activity\nWHERE backend_type='startup';\n}) or die \"Timed out checking if startup is in recovery_min_apply_delay\";\n\nAttached v3.\n\nRegards,\nSoumyadeep (VMware)", "msg_date": "Fri, 6 Aug 2021 16:59:55 -0700", "msg_from": "Soumyadeep Chakraborty <soumyadeep2007@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Changes to recovery_min_apply_delay are ignored while waiting for\n delay" }, { "msg_contents": "On Fri, Aug 06, 2021 at 04:59:55PM -0700, Soumyadeep Chakraborty wrote:\n> Rebased. Also added a stronger check to see if the standby is stuck in\n> recovery_min_apply_delay:\n> \n> $node_standby->poll_query_until('postgres', qq{\n> SELECT wait_event = 'RecoveryApplyDelay' FROM pg_stat_activity\n> WHERE backend_type='startup';\n> }) or die \"Timed out checking if startup is in recovery_min_apply_delay\";\n\nRelying on wait events is a good idea here. This makes the test more\nreliable to make sure that the startup process is stuck in the\nWaitLatch phase.\n\n> Attached v3.\n\nAgreed that the current behavior is confusing. As you are using the\ncommit timestamp for the comparison, this is right. One small-ish\ncomment I have about the code is that we should mention\nrecovery_min_apply_delay for HandleStartupProcInterrupts(), and not\nonly the trigger file location.\n\n+# First, set the delay for the next commit to some obscenely high value.\nIt has no need to be obscenely high, just high enough to give the time\nto slow machines to catch the wait event lookup done. So this could\nuse better words to explain this choice.\n\nAnyway, it seems to me that something is incorrect in this new test\n(manual tests pass here, the TAP test is off). One thing we need to\nmake sure for any new test added is that it correctly breaks if the\nfix proposed is *not* in place. And as far as I can see, the test\npasses even if the recalculation of delayUntil is done within the loop\nthat reloads the configuration. The thing may be a bit tricky to make\nreliable as the parameter reloading may cause wait_event to not be\nRecoveryApplyDelay, so we should have at least a check based on a scan\nof pg_stat_replication.replay_lsn on the primary. Perhaps you have\nan other idea?\n\nWhen using wait_for_catchup(), I would recommend to list \"replay\" for\nthis test, even if that's the default mode, to make clear what the\nintention is.\n--\nMichael", "msg_date": "Wed, 11 Aug 2021 16:40:39 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Changes to recovery_min_apply_delay are ignored while waiting\n for delay" }, { "msg_contents": "Hey Michael,\n\nReally appreciate the review!\n\nOn Wed, Aug 11, 2021 at 12:40 AM Michael Paquier <michael@paquier.xyz> wrote:\n\n> Agreed that the current behavior is confusing. As you are using the\n> commit timestamp for the comparison, this is right. One small-ish\n> comment I have about the code is that we should mention\n> recovery_min_apply_delay for HandleStartupProcInterrupts(), and not\n> only the trigger file location.\n\nCool, updated.\n\n> +# First, set the delay for the next commit to some obscenely high value.\n> It has no need to be obscenely high, just high enough to give the time\n> to slow machines to catch the wait event lookup done. So this could\n> use better words to explain this choice.\n\nSounds good. Done.\n\n> Anyway, it seems to me that something is incorrect in this new test\n> (manual tests pass here, the TAP test is off). One thing we need to\n> make sure for any new test added is that it correctly breaks if the\n> fix proposed is *not* in place. And as far as I can see, the test\n> passes even if the recalculation of delayUntil is done within the loop\n> that reloads the configuration. The thing may be a bit tricky to make\n> reliable as the parameter reloading may cause wait_event to not be\n> RecoveryApplyDelay, so we should have at least a check based on a scan\n> of pg_stat_replication.replay_lsn on the primary. Perhaps you have\n> an other idea?\n\nHmm, please see attached v4 which just shifts the test to the middle,\nlike v1. When I run the test without the code change, the test hangs\nas expected in:\n\n# Now the standby should catch up.\n$node_primary->wait_for_catchup('standby', 'replay');\n\nand passes with the code change, as expected. I can't explain why the\ntest doesn't freeze up in v3 in wait_for_catchup() at the end.\n\nAs for checking on the wait event, since we only signal the standby\nafter performing the check, that should be fine. Nothing else would be\nsending a SIGHUP before the check. Is that assumption correct?\n\n> When using wait_for_catchup(), I would recommend to list \"replay\" for\n> this test, even if that's the default mode, to make clear what the\n> intention is.\n\nDone.\n\nRegards,\nSoumyadeep (VMware)", "msg_date": "Fri, 13 Aug 2021 17:59:21 -0700", "msg_from": "Soumyadeep Chakraborty <soumyadeep2007@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Changes to recovery_min_apply_delay are ignored while waiting for\n delay" }, { "msg_contents": "On Fri, Aug 13, 2021 at 05:59:21PM -0700, Soumyadeep Chakraborty wrote:\n> and passes with the code change, as expected. I can't explain why the\n> test doesn't freeze up in v3 in wait_for_catchup() at the end.\n\nIt took me some some to understand why. If I am right, that's because\nof the intermediate test block working on $standby_2 and the two\nINSERT queries of the primary. In v1 and v4, we have no activity on\nthe primary between the first set of tests and yours, meaning that\n$standby has nothing to do. In v2 and v3, the two INSERT queries run\non the primary for the purpose of the recovery pause make $standby_1\nwait for the default value of recovery_min_apply_delay, aka 3s, in\nparallel. If the set of tests for $standby_2 is faster than that,\nwe'd bump on the phase where the code still waited for 3s, not the 2\nhours set, visibly.\n\nAfter considering this stuff, the order dependency we'd introduce in\nthis test makes the whole thing more brittle than it should. And such\nan edge case does not seem worth spending extra cycles testing anyway,\nas if things break we'd finish with a test stuck for an unnecessary\nlong time by relying on wait_for_catchup(\"replay\"). We could use\nsomething else, say based on a lookup of pg_stat_activity but this\nstill requires extra run time for the wait phases needed. So at the\nend I have dropped the test, but backpatched the fix.\n--\nMichael", "msg_date": "Mon, 16 Aug 2021 12:16:15 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Changes to recovery_min_apply_delay are ignored while waiting\n for delay" }, { "msg_contents": "On Sun, Aug 15, 2021 at 8:16 PM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> On Fri, Aug 13, 2021 at 05:59:21PM -0700, Soumyadeep Chakraborty wrote:\n> > and passes with the code change, as expected. I can't explain why the\n> > test doesn't freeze up in v3 in wait_for_catchup() at the end.\n>\n> It took me some some to understand why. If I am right, that's because\n> of the intermediate test block working on $standby_2 and the two\n> INSERT queries of the primary. In v1 and v4, we have no activity on\n> the primary between the first set of tests and yours, meaning that\n> $standby has nothing to do. In v2 and v3, the two INSERT queries run\n> on the primary for the purpose of the recovery pause make $standby_1\n> wait for the default value of recovery_min_apply_delay, aka 3s, in\n> parallel. If the set of tests for $standby_2 is faster than that,\n> we'd bump on the phase where the code still waited for 3s, not the 2\n> hours set, visibly.\n\nI see, thanks a lot for the explanation. Thanks to your investigation, I\ncan now kind of reuse some of the test mechanisms for the other patch that\nI am working on [1]. There, we don't have multiple standbys getting in the\nway, thankfully.\n\n> After considering this stuff, the order dependency we'd introduce in\n> this test makes the whole thing more brittle than it should. And such\n> an edge case does not seem worth spending extra cycles testing anyway,\n> as if things break we'd finish with a test stuck for an unnecessary\n> long time by relying on wait_for_catchup(\"replay\"). We could use\n> something else, say based on a lookup of pg_stat_activity but this\n> still requires extra run time for the wait phases needed. So at the\n> end I have dropped the test, but backpatched the fix.\n> --\n\nFair.\n\nRegards,\nSoumyadeep (VMware)\n\n[1] https://www.postgresql.org/message-id/flat/CANXE4Tc3FNvZ_xAimempJWv_RH9pCvsZH7Yq93o1VuNLjUT-mQ%40mail.gmail.com\n\n\n", "msg_date": "Sun, 15 Aug 2021 21:21:14 -0700", "msg_from": "Soumyadeep Chakraborty <soumyadeep2007@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Changes to recovery_min_apply_delay are ignored while waiting for\n delay" } ]
[ { "msg_contents": "Going by [1], it looks like we can use the __popcnt and __popcnt64\nintrinsic functions on MSVC if the CPU supports POPCNT. We already\nhave code to check for that, we just need to enable it on MSVC.\n\nThe attached patch seems to be all that's needed.\n\nDavid\n\n[1] https://docs.microsoft.com/en-us/cpp/intrinsics/popcnt16-popcnt-popcnt64?view=msvc-140", "msg_date": "Tue, 3 Aug 2021 21:03:06 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Use POPCNT on MSVC" }, { "msg_contents": "On Tue, Aug 3, 2021 at 5:03 AM David Rowley <dgrowleyml@gmail.com> wrote:\n>\n> Going by [1], it looks like we can use the __popcnt and __popcnt64\n> intrinsic functions on MSVC if the CPU supports POPCNT. We already\n> have code to check for that, we just need to enable it on MSVC.\n>\n> The attached patch seems to be all that's needed.\n\n+1 for the concept, but the coding is a bit strange. Granted, the way we\nhandle popcnt is a bit strange, but this makes it stranger:\n\n1. the __popcnt64() intrinsic is put inside pg_popcount64_asm(), which is a\nbit of a misnomer since it's not assembly. Renaming s/_asm/_fast/ would\nhelp it look better. But then looking around, other platforms have\nintrinsics coded, but for some reason they're put in pg_popcount64_slow(),\nwhere the compiler will emit instructions we could easily write ourselves\nin C (and without #ifdefs) since without the right CFLAGS these intrinsics\nwon't emit a popcnt instruction. Is MSVC different in that regard? If so,\nit might be worth a comment.\n\n2. (defined(_MSC_VER) && defined(_WIN64) lead to a runtime check for the\nCPUID, which is fine, but now next to it HAVE_X86_64_POPCNTQ looks strange\nbecause the latter symbol comes from a specific configure test -- the two\ndon't seem equivalent, but maybe they are because of what MSVC does? That\nwould be nice to spell out here.\n\nI know the present state of affairs works a bit different than what you\nproposed a couple years ago and that something had to change for\nportability reasons I didn't quite understand, but I think if we change\nthings here we should at least try to have things fit together a bit more\nnicely.\n\n(Side note, but sort of related to #1 above: non-x86 platforms have to\nindirect through a function pointer even though they have no fast\nimplementation to make it worth their while. It would be better for them if\nthe \"slow\" implementation was called static inline or at least a direct\nfunction call, but that's a separate thread.)\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Tue, Aug 3, 2021 at 5:03 AM David Rowley <dgrowleyml@gmail.com> wrote:>> Going by [1], it looks like we can use the __popcnt and __popcnt64> intrinsic functions on MSVC if the CPU supports POPCNT.  We already> have code to check for that, we just need to enable it on MSVC.>> The attached patch seems to be all that's needed.+1 for the concept, but the coding is a bit strange. Granted, the way we handle popcnt is a bit strange, but this makes it stranger:1. the __popcnt64() intrinsic is put inside pg_popcount64_asm(), which is a bit of a misnomer since it's not assembly. Renaming s/_asm/_fast/ would help it look better. But then looking around, other platforms have intrinsics coded, but for some reason they're put in pg_popcount64_slow(), where the compiler will emit instructions we could easily write ourselves in C (and without #ifdefs) since without the right CFLAGS these intrinsics won't emit a popcnt instruction. Is MSVC different in that regard? If so, it might be worth a comment.2. (defined(_MSC_VER) && defined(_WIN64)  lead to a runtime check for the CPUID, which is fine, but now next to it HAVE_X86_64_POPCNTQ looks strange because the latter symbol comes from a specific configure test -- the two don't seem equivalent, but maybe they are because of what MSVC does? That would be nice to spell out here.I know the present state of affairs works a bit different than what you proposed a couple years ago and that something had to change for portability reasons I didn't quite understand, but I think if we change things here we should at least try to have things fit together a bit more nicely. (Side note, but sort of related to #1 above: non-x86 platforms have to indirect through a function pointer even though they have no fast implementation to make it worth their while. It would be better for them if the \"slow\" implementation was called static inline or at least a direct function call, but that's a separate thread.)--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Tue, 3 Aug 2021 06:43:25 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use POPCNT on MSVC" }, { "msg_contents": "On Tue, Aug 3, 2021 at 10:43 PM John Naylor\n<john.naylor@enterprisedb.com> wrote:\n> (Side note, but sort of related to #1 above: non-x86 platforms have to indirect through a function pointer even though they have no fast implementation to make it worth their while. It would be better for them if the \"slow\" implementation was called static inline or at least a direct function call, but that's a separate thread.)\n\n+1\n\nI haven't looked into whether we could benefit from it in real use\ncases, but it seems like it'd also be nice if pg_popcount() were a\ncandidate for auto-vectorisation and inlining. For example, NEON has\nvector popcount, and for Intel/AMD there is a shuffle-based AVX2 trick\nthat at least Clang produces automatically[1]. We're obstructing that\nby doing function dispatch at individual word level, and using inline\nassembler instead of builtins.\n\n[1] https://arxiv.org/abs/1611.07612\n\n\n", "msg_date": "Wed, 4 Aug 2021 13:05:06 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Use POPCNT on MSVC" }, { "msg_contents": "On Tue, 3 Aug 2021 at 22:43, John Naylor <john.naylor@enterprisedb.com> wrote:\n> 1. the __popcnt64() intrinsic is put inside pg_popcount64_asm(), which is a bit of a misnomer since it's not assembly. Renaming s/_asm/_fast/ would help it look better. But then looking around, other platforms have intrinsics coded, but for some reason they're put in pg_popcount64_slow(), where the compiler will emit instructions we could easily write ourselves in C (and without #ifdefs) since without the right CFLAGS these intrinsics won't emit a popcnt instruction. Is MSVC different in that regard? If so, it might be worth a comment.\n\nYeah, the names no longer fit so well after stuffing the MSVC\nintrinsic into the asm function. The reason I did it that way is down\nto what I read in the docs. Namely:\n\n\"If you run code that uses these intrinsics on hardware that doesn't\nsupport the popcnt instruction, the results are unpredictable.\"\n\nSo, it has to go somewhere where we're sure the CPU supports POPCNT\nand that seemed like the correct place.\n\n From what I understand of GCC and __builtin_popcountl(), the code\nit'll output will depend on the -mpopcnt flag. So having\n__builtin_popcountl() does not mean the popcnt instruction will be\nused. The Microsoft documentation indicates that's not the case for\n__popcnt().\n\n> 2. (defined(_MSC_VER) && defined(_WIN64) lead to a runtime check for the CPUID, which is fine, but now next to it HAVE_X86_64_POPCNTQ looks strange because the latter symbol comes from a specific configure test -- the two don't seem equivalent, but maybe they are because of what MSVC does? That would be nice to spell out here.\n\nThe problem there is that we define HAVE_X86_64_POPCNTQ based on the\noutcome of configure so it does not get set for MSVC. Maybe it's\nworth coming up with some other constant that can be defined or we\ncould just do:\n\n#if defined(_MSC_VER) && defined(_WIN64)\n#define HAVE_X86_64_POPCNTQ\n#endif\n\n> I know the present state of affairs works a bit different than what you proposed a couple years ago and that something had to change for portability reasons I didn't quite understand, but I think if we change things here we should at least try to have things fit together a bit more nicely.\n\nI think the reason for the asm is that __builtin_popcountl does not\nmean popcnt will be used. Maybe we could have done something like\ncompile pg_bitutils.c with -mpopcnt, and have kept the run-time check,\nbut the problem there is that means that the compiler might end up\nusing that instruction in some other function in that file that we\ndon't want it to. It looks like my patch in [1] did pass the -mpopcnt\nflag which Tom fixed.\n\n> (Side note, but sort of related to #1 above: non-x86 platforms have to indirect through a function pointer even though they have no fast implementation to make it worth their while. It would be better for them if the \"slow\" implementation was called static inline or at least a direct function call, but that's a separate thread.)\n\nhmm yeah. I see there's a few more usages of pg_popcount() than when I\nlooked last. It would be fairly easy to get rid of the\npg_popcount64/pg_popcount32 function call in that. A separate patch\nthough.\n\nDavid\n\n[1] https://www.postgresql.org/message-id/CAKJS1f9WTAGG1tPeJnD18hiQW5gAk59fQ6WK-vfdAKEHyRg2RA@mail.gmail.com\n\n\n", "msg_date": "Wed, 4 Aug 2021 15:36:00 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use POPCNT on MSVC" }, { "msg_contents": "On Tue, Aug 3, 2021 at 11:36 PM David Rowley <dgrowleyml@gmail.com> wrote:\n>\n> On Tue, 3 Aug 2021 at 22:43, John Naylor <john.naylor@enterprisedb.com>\nwrote:\n> > 1. the __popcnt64() intrinsic is put inside pg_popcount64_asm(), which\nis a bit of a misnomer since it's not assembly. Renaming s/_asm/_fast/\nwould help it look better. But then looking around, other platforms have\nintrinsics coded, but for some reason they're put in pg_popcount64_slow(),\nwhere the compiler will emit instructions we could easily write ourselves\nin C (and without #ifdefs) since without the right CFLAGS these intrinsics\nwon't emit a popcnt instruction. Is MSVC different in that regard? If so,\nit might be worth a comment.\n>\n> Yeah, the names no longer fit so well after stuffing the MSVC\n> intrinsic into the asm function. The reason I did it that way is down\n> to what I read in the docs. Namely:\n>\n> \"If you run code that uses these intrinsics on hardware that doesn't\n> support the popcnt instruction, the results are unpredictable.\"\n>\n> So, it has to go somewhere where we're sure the CPU supports POPCNT\n> and that seemed like the correct place.\n>\n> From what I understand of GCC and __builtin_popcountl(), the code\n> it'll output will depend on the -mpopcnt flag. So having\n> __builtin_popcountl() does not mean the popcnt instruction will be\n> used. The Microsoft documentation indicates that's not the case for\n> __popcnt().\n\nOkay, \"unpredictable\" sounds bad.\n\n> > 2. (defined(_MSC_VER) && defined(_WIN64) lead to a runtime check for\nthe CPUID, which is fine, but now next to it HAVE_X86_64_POPCNTQ looks\nstrange because the latter symbol comes from a specific configure test --\nthe two don't seem equivalent, but maybe they are because of what MSVC\ndoes? That would be nice to spell out here.\n>\n> The problem there is that we define HAVE_X86_64_POPCNTQ based on the\n> outcome of configure so it does not get set for MSVC. Maybe it's\n> worth coming up with some other constant that can be defined or we\n> could just do:\n>\n> #if defined(_MSC_VER) && defined(_WIN64)\n> #define HAVE_X86_64_POPCNTQ\n> #endif\n\nThat seems fine. I don't know PG can build with Arm on Windows, but for the\ncpuid to work, it seems safer to also check for __x86_64?\n\n> I think the reason for the asm is that __builtin_popcountl does not\n> mean popcnt will be used. Maybe we could have done something like\n> compile pg_bitutils.c with -mpopcnt, and have kept the run-time check,\n> but the problem there is that means that the compiler might end up\n> using that instruction in some other function in that file that we\n> don't want it to. It looks like my patch in [1] did pass the -mpopcnt\n> flag which Tom fixed.\n\nAh, that makes sense. (If we someday offer a configure option for\nx86-64-v2, we can use intrinsics in the asm functions, and call them\ndirectly. Yet another different thread.)\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Tue, Aug 3, 2021 at 11:36 PM David Rowley <dgrowleyml@gmail.com> wrote:>> On Tue, 3 Aug 2021 at 22:43, John Naylor <john.naylor@enterprisedb.com> wrote:> > 1. the __popcnt64() intrinsic is put inside pg_popcount64_asm(), which is a bit of a misnomer since it's not assembly. Renaming s/_asm/_fast/ would help it look better. But then looking around, other platforms have intrinsics coded, but for some reason they're put in pg_popcount64_slow(), where the compiler will emit instructions we could easily write ourselves in C (and without #ifdefs) since without the right CFLAGS these intrinsics won't emit a popcnt instruction. Is MSVC different in that regard? If so, it might be worth a comment.>> Yeah, the names no longer fit so well after stuffing the MSVC> intrinsic into the asm function.  The reason I did it that way is down> to what I read in the docs. Namely:>> \"If you run code that uses these intrinsics on hardware that doesn't> support the popcnt instruction, the results are unpredictable.\">> So, it has to go somewhere where we're sure the CPU supports POPCNT> and that seemed like the correct place.>> From what I understand of GCC and __builtin_popcountl(), the code> it'll output will depend on the -mpopcnt flag.  So having> __builtin_popcountl() does not mean the popcnt instruction will be> used. The Microsoft documentation indicates that's not the case for> __popcnt().Okay, \"unpredictable\" sounds bad.> > 2. (defined(_MSC_VER) && defined(_WIN64)  lead to a runtime check for the CPUID, which is fine, but now next to it HAVE_X86_64_POPCNTQ looks strange because the latter symbol comes from a specific configure test -- the two don't seem equivalent, but maybe they are because of what MSVC does? That would be nice to spell out here.>> The problem there is that we define HAVE_X86_64_POPCNTQ based on the> outcome of configure so it does not get set for MSVC.  Maybe it's> worth coming up with some other constant that can be defined or we> could just do:>> #if defined(_MSC_VER) && defined(_WIN64)> #define HAVE_X86_64_POPCNTQ> #endifThat seems fine. I don't know PG can build with Arm on Windows, but for the cpuid to work, it seems safer to also check for __x86_64?> I think the reason for the asm is that __builtin_popcountl does not> mean popcnt will be used. Maybe we could have done something like> compile pg_bitutils.c with -mpopcnt, and have kept the run-time check,> but the problem there is that means that the compiler might end up> using that instruction in some other function in that file that we> don't want it to. It looks like my patch in [1] did pass the -mpopcnt> flag which Tom fixed.Ah, that makes sense. (If we someday offer a configure option for x86-64-v2, we can use intrinsics in the asm functions, and call them directly. Yet another different thread.)--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Wed, 4 Aug 2021 15:01:50 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use POPCNT on MSVC" }, { "msg_contents": "On Thu, 5 Aug 2021 at 07:02, John Naylor <john.naylor@enterprisedb.com> wrote:\n> > #if defined(_MSC_VER) && defined(_WIN64)\n> > #define HAVE_X86_64_POPCNTQ\n> > #endif\n>\n> That seems fine. I don't know PG can build with Arm on Windows, but for the cpuid to work, it seems safer to also check for __x86_64?\n\nThat's a good point. I've adjusted it to do #if defined(_MSC_VER) &&\ndefined(_M_AMD64).\n\nI've attached a v2 patch which I think is more along the lines of what\nyou had in mind.\n\nDavid", "msg_date": "Mon, 9 Aug 2021 12:31:16 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use POPCNT on MSVC" }, { "msg_contents": "On Sun, Aug 8, 2021 at 8:31 PM David Rowley <dgrowleyml@gmail.com> wrote:\n>\n> I've attached a v2 patch which I think is more along the lines of what\n> you had in mind.\n\nLGTM\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Sun, Aug 8, 2021 at 8:31 PM David Rowley <dgrowleyml@gmail.com> wrote:>> I've attached a v2 patch which I think is more along the lines of what> you had in mind.LGTM--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Sun, 8 Aug 2021 20:58:07 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Use POPCNT on MSVC" }, { "msg_contents": "On Mon, 9 Aug 2021 at 12:58, John Naylor <john.naylor@enterprisedb.com> wrote:\n>\n> On Sun, Aug 8, 2021 at 8:31 PM David Rowley <dgrowleyml@gmail.com> wrote:\n> >\n> > I've attached a v2 patch which I think is more along the lines of what\n> > you had in mind.\n>\n> LGTM\n\nThanks for the review.\n\nPushed.\n\nDavid\n\n\n", "msg_date": "Mon, 9 Aug 2021 15:24:56 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Use POPCNT on MSVC" } ]
[ { "msg_contents": "Hi,\n\nI found two extra code lines in commit_ts.h (see attachment).\nThey confused me during exploring of the code. If they still needed, may \nbe add some comments?\n\n-- \nregards,\nAndrey Lepikhov\nPostgres Professional", "msg_date": "Tue, 3 Aug 2021 14:36:34 +0500", "msg_from": "\"Andrey V. Lepikhov\" <a.lepikhov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Extra code in commit_ts.h" }, { "msg_contents": "On Tue, 3 Aug 2021 at 21:36, Andrey V. Lepikhov\n<a.lepikhov@postgrespro.ru> wrote:\n> I found two extra code lines in commit_ts.h (see attachment).\n> They confused me during exploring of the code. If they still needed, may\n> be add some comments?\n\nGoing by:\n\n$ git config --global diff.renamelimit 1000\n$ git diff 73c986adde5~1.. | grep check_track_commit_timestamp\n+extern bool check_track_commit_timestamp(bool *newval, void **extra,\n\nthat function has never been defined.\n\nDavid\n\n\n", "msg_date": "Tue, 3 Aug 2021 22:16:37 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Extra code in commit_ts.h" }, { "msg_contents": "On 3/8/21 15:16, David Rowley wrote:\n> it diff 73c986adde5~1.. | grep check_track_commit_timestamp\nI think this is waste code. May be delete it?\n\n-- \nregards,\nAndrey Lepikhov\nPostgres Professional\n\n\n", "msg_date": "Tue, 3 Aug 2021 16:12:01 +0500", "msg_from": "Andrey Lepikhov <a.lepikhov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Extra code in commit_ts.h" }, { "msg_contents": "On Tue, 3 Aug 2021 at 23:12, Andrey Lepikhov <a.lepikhov@postgrespro.ru> wrote:\n>\n> On 3/8/21 15:16, David Rowley wrote:\n> > it diff 73c986adde5~1.. | grep check_track_commit_timestamp\n> I think this is waste code. May be delete it?\n\nYeah, I think it can be safely removed. I can do so unless someone\nthinks otherwise.\n\nDavid\n\n\n", "msg_date": "Wed, 4 Aug 2021 00:02:17 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Extra code in commit_ts.h" }, { "msg_contents": "On Wed, 4 Aug 2021 at 00:02, David Rowley <dgrowleyml@gmail.com> wrote:\n> Yeah, I think it can be safely removed. I can do so unless someone\n> thinks otherwise.\n\nPushed.\n\nDavid\n\n\n", "msg_date": "Sun, 8 Aug 2021 23:29:27 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Extra code in commit_ts.h" } ]
[ { "msg_contents": "Hi Hackers,\n\nThe other day I noticed that there's no tab completion after ALTER TABLE\n… ADD, so here's a patch. In addition to COLUMN and all the table\nconstraint types, it also completes with the list of unique indexes on\nthe table after ALTER TABLE … ADD … USING INDEX.\n\n- ilmari", "msg_date": "Tue, 03 Aug 2021 12:48:38 +0100", "msg_from": "ilmari@ilmari.org (Dagfinn Ilmari =?utf-8?Q?Manns=C3=A5ker?=)", "msg_from_op": true, "msg_subject": "[PATCH] Tab completion for ALTER TABLE =?utf-8?Q?=E2=80=A6?= ADD\n =?utf-8?Q?=E2=80=A6?=" }, { "msg_contents": "ilmari@ilmari.org (Dagfinn Ilmari Mannsåker) writes:\n\n> Hi Hackers,\n>\n> The other day I noticed that there's no tab completion after ALTER TABLE\n> … ADD, so here's a patch. In addition to COLUMN and all the table\n> constraint types, it also completes with the list of unique indexes on\n> the table after ALTER TABLE … ADD … USING INDEX.\n\nAdded to the 2021-09 commitfest: https://commitfest.postgresql.org/34/3280/\n\n- ilmari\n\n\n", "msg_date": "Sat, 07 Aug 2021 23:25:44 +0100", "msg_from": "ilmari@ilmari.org (Dagfinn Ilmari =?utf-8?Q?Manns=C3=A5ker?=)", "msg_from_op": true, "msg_subject": "Re: [PATCH] Tab completion for ALTER TABLE =?utf-8?Q?=E2=80=A6?=\n ADD =?utf-8?Q?=E2=80=A6?=" }, { "msg_contents": "On Tue, Aug 03, 2021 at 12:48:38PM +0100, Dagfinn Ilmari Mannsåker wrote:\n> The other day I noticed that there's no tab completion after ALTER TABLE\n> … ADD, so here's a patch. In addition to COLUMN and all the table\n> constraint types, it also completes with the list of unique indexes on\n> the table after ALTER TABLE … ADD … USING INDEX.\n\nI was reading this patch (not actually tested), and that's a clear\nimprovement. One extra thing that could be done here is to complete\nwith types for a ALTER TABLE ADD COLUMN foo. We could as well have a\nlist of columns after UNIQUE or PRIMARY KEY, but that feels like extra\ncream on top of the cake. In short I am fine with what you have\nhere.\n--\nMichael", "msg_date": "Fri, 27 Aug 2021 13:04:00 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Tab completion for =?utf-8?Q?A?=\n =?utf-8?B?TFRFUiBUQUJMRSDigKYgQUREIOKApg==?=" }, { "msg_contents": "Michael Paquier <michael@paquier.xyz> writes:\n\n> On Tue, Aug 03, 2021 at 12:48:38PM +0100, Dagfinn Ilmari Mannsåker wrote:\n>> The other day I noticed that there's no tab completion after ALTER TABLE\n>> … ADD, so here's a patch. In addition to COLUMN and all the table\n>> constraint types, it also completes with the list of unique indexes on\n>> the table after ALTER TABLE … ADD … USING INDEX.\n>\n> I was reading this patch (not actually tested), and that's a clear\n> improvement. One extra thing that could be done here is to complete\n> with types for a ALTER TABLE ADD COLUMN foo.\n\nThat was easy enough to add (just a bit of extra fiddling to handle\nCOLUMN being optional), done in the attached v2 patch.\n\n> We could as well have a list of columns after UNIQUE or PRIMARY KEY,\n> but that feels like extra cream on top of the cake.\n\nDoing a list of arbitrarily many comma-separated names is more\ncomplicated, so that can be the subject for another patch.\n\n> In short I am fine with what you have here.\n\nThanks for the review.\n\n- ilmari", "msg_date": "Fri, 27 Aug 2021 11:52:33 +0100", "msg_from": "=?utf-8?Q?Dagfinn_Ilmari_Manns=C3=A5ker?= <ilmari@ilmari.org>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Tab completion for ALTER TABLE =?utf-8?Q?=E2=80=A6?=\n ADD =?utf-8?Q?=E2=80=A6?=" }, { "msg_contents": "On Fri, Aug 27, 2021 at 11:52:33AM +0100, Dagfinn Ilmari Mannsåker wrote:\n> That was easy enough to add (just a bit of extra fiddling to handle\n> COLUMN being optional), done in the attached v2 patch.\n\nThis part was a bit misleading, as it would recommend a list of types\nwhen specifying just ADD CONSTRAINT for example, so I have removed\nit. An extra thing that felt a bit overdoing is the addition of KEY\nafter PRIMARY/FOREIGN.\n\n> Doing a list of arbitrarily many comma-separated names is more\n> complicated, so that can be the subject for another patch.\n\nNo objections to that. I have applied what we have now, as that's\nalready an improvement.\n--\nMichael", "msg_date": "Mon, 30 Aug 2021 09:55:53 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Tab completion for =?utf-8?Q?A?=\n =?utf-8?B?TFRFUiBUQUJMRSDigKYgQUREIOKApg==?=" }, { "msg_contents": "Michael Paquier <michael@paquier.xyz> writes:\n\n> On Fri, Aug 27, 2021 at 11:52:33AM +0100, Dagfinn Ilmari Mannsåker wrote:\n>> That was easy enough to add (just a bit of extra fiddling to handle\n>> COLUMN being optional), done in the attached v2 patch.\n>\n> This part was a bit misleading, as it would recommend a list of types\n> when specifying just ADD CONSTRAINT for example, so I have removed\n> it.\n\nThat was because I forgot to exclude all the other object types that can\ncome after ADD. Attached is a patch that does that. I also moved it\nright next to the ALTER TABLE … ADD completion, and added a comment to\nkeep the two lists in sync.\n\n> An extra thing that felt a bit overdoing is the addition of KEY after\n> PRIMARY/FOREIGN.\n\nYeah, I guess people are unlikely to write out the whole PRIMARY or FOREIGN\nand only then hit tab to complete the rest.\n\n>> Doing a list of arbitrarily many comma-separated names is more\n>> complicated, so that can be the subject for another patch.\n>\n> No objections to that. I have applied what we have now, as that's\n> already an improvement.\n\nThanks!\n\n- ilmari", "msg_date": "Mon, 30 Aug 2021 14:38:19 +0100", "msg_from": "=?utf-8?Q?Dagfinn_Ilmari_Manns=C3=A5ker?= <ilmari@ilmari.org>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Tab completion for ALTER TABLE =?utf-8?Q?=E2=80=A6?=\n ADD =?utf-8?Q?=E2=80=A6?=" }, { "msg_contents": "On Mon, Aug 30, 2021 at 02:38:19PM +0100, Dagfinn Ilmari Mannsåker wrote:\n> That was because I forgot to exclude all the other object types that can\n> come after ADD. Attached is a patch that does that. I also moved it\n> right next to the ALTER TABLE … ADD completion, and added a comment to\n> keep the two lists in sync.\n\nLooks fine to me, so applied while we are on it.\n--\nMichael", "msg_date": "Tue, 31 Aug 2021 12:20:14 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Tab completion for =?utf-8?Q?A?=\n =?utf-8?B?TFRFUiBUQUJMRSDigKYgQUREIOKApg==?=" }, { "msg_contents": "On Tue, 31 Aug 2021, at 04:20, Michael Paquier wrote:\n> On Mon, Aug 30, 2021 at 02:38:19PM +0100, Dagfinn Ilmari Mannsåker wrote:\n> > That was because I forgot to exclude all the other object types that can\n> > come after ADD. Attached is a patch that does that. I also moved it\n> > right next to the ALTER TABLE … ADD completion, and added a comment to\n> > keep the two lists in sync.\n> \n> Looks fine to me, so applied while we are on it.\n\nThanks!\n\n- ilmari\n\n\n", "msg_date": "Tue, 31 Aug 2021 09:36:48 +0100", "msg_from": "=?UTF-8?Q?Dagfinn_Ilmari_Manns=C3=A5ker?= <ilmari@ilmari.org>", "msg_from_op": false, "msg_subject": "=?UTF-8?Q?Re:_[PATCH]_Tab_completion_for_ALTER_TABLE_=E2=80=A6_ADD_?=\n =?UTF-8?Q?=E2=80=A6?=" } ]
[ { "msg_contents": "There are 273 patches in the queue for the Sept Commitfest already, so\nit seems clear the queue is not being cleared down each CF as it was\nbefore. We've been trying hard, but it's overflowing.\n\nOf those, about 50 items have been waiting more than one year, and\nabout 25 entries waiting for more than two years.\n\nOne problem is that many entries don't have official reviewers, though\nmany people have commented on Hackers, making it difficult to track\ndown items that actually need work. That wastes a lot of time for\nwould-be reviewers (or at least, it has done for me).\n\nPlease can there be some additional coordination to actively clear\ndown this problem? I won't attempt to come up with ideas to do this,\nbut others may wish to suggest ways that avoid Committer burn-out?\n\nI will be happy to volunteer to be part of an organized approach that\nspreads out the work.\n\nThanks\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/\n\n\n", "msg_date": "Tue, 3 Aug 2021 16:53:40 +0100", "msg_from": "Simon Riggs <simon.riggs@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Commitfest overflow" }, { "msg_contents": "On Tue, Aug 3, 2021 at 04:53:40PM +0100, Simon Riggs wrote:\n> There are 273 patches in the queue for the Sept Commitfest already, so\n> it seems clear the queue is not being cleared down each CF as it was\n> before. We've been trying hard, but it's overflowing.\n> \n> Of those, about 50 items have been waiting more than one year, and\n> about 25 entries waiting for more than two years.\n> \n> One problem is that many entries don't have official reviewers, though\n> many people have commented on Hackers, making it difficult to track\n> down items that actually need work. That wastes a lot of time for\n> would-be reviewers (or at least, it has done for me).\n> \n> Please can there be some additional coordination to actively clear\n> down this problem? I won't attempt to come up with ideas to do this,\n> but others may wish to suggest ways that avoid Committer burn-out?\n> \n> I will be happy to volunteer to be part of an organized approach that\n> spreads out the work.\n\nI wonder if our lack of in-person developer meetings is causing some of\nour issues to not get closed.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Tue, 3 Aug 2021 11:55:50 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "Bruce Momjian <bruce@momjian.us> writes:\n> On Tue, Aug 3, 2021 at 04:53:40PM +0100, Simon Riggs wrote:\n>> There are 273 patches in the queue for the Sept Commitfest already, so\n>> it seems clear the queue is not being cleared down each CF as it was\n>> before. We've been trying hard, but it's overflowing.\n\n> I wonder if our lack of in-person developer meetings is causing some of\n> our issues to not get closed.\n\nI think there are a couple of things happening here:\n\n1. There wasn't that much getting done during this CF because it's\nsummer and many people are on vacation (in the northern hemisphere\nanyway).\n\n2. As a community, we don't really have the strength of will to\nflat-out reject patches. I think the dynamic is that individual\ncommitters look at something, think \"I don't like that, I'll go\nwork on some better-designed patch\", and it just keeps slipping\nto the next CF. In the past we've had some CFMs who were assertive\nenough and senior enough to kill off patches that didn't look like\nthey were going to go anywhere. But that hasn't happened for\nawhile, and I'm not sure it should be the CFM's job anyway.\n\n(I hasten to add that I'm not trying to imply that all the\nlong-lingering patches are hopeless. But I think some of them are.)\n\nI don't think there's much to be done about the vacation effect;\nwe just have to accept that the summer CF is likely to be less\nproductive than others. But I'd like to see some better-formalized\nway of rejecting patches that aren't going anywhere. Maybe there\nshould be a time limit on how many CFs a patch is allowed to just\nautomatically slide through?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 03 Aug 2021 12:13:44 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Tue, 3 Aug 2021 at 17:13, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Bruce Momjian <bruce@momjian.us> writes:\n> > On Tue, Aug 3, 2021 at 04:53:40PM +0100, Simon Riggs wrote:\n> >> There are 273 patches in the queue for the Sept Commitfest already, so\n> >> it seems clear the queue is not being cleared down each CF as it was\n> >> before. We've been trying hard, but it's overflowing.\n>\n> > I wonder if our lack of in-person developer meetings is causing some of\n> > our issues to not get closed.\n>\n> I think there are a couple of things happening here:\n>\n> 1. There wasn't that much getting done during this CF because it's\n> summer and many people are on vacation (in the northern hemisphere\n> anyway).\n>\n> 2. As a community, we don't really have the strength of will to\n> flat-out reject patches. I think the dynamic is that individual\n> committers look at something, think \"I don't like that, I'll go\n> work on some better-designed patch\", and it just keeps slipping\n> to the next CF. In the past we've had some CFMs who were assertive\n> enough and senior enough to kill off patches that didn't look like\n> they were going to go anywhere. But that hasn't happened for\n> awhile, and I'm not sure it should be the CFM's job anyway.\n>\n> (I hasten to add that I'm not trying to imply that all the\n> long-lingering patches are hopeless. But I think some of them are.)\n>\n> I don't think there's much to be done about the vacation effect;\n> we just have to accept that the summer CF is likely to be less\n> productive than others. But I'd like to see some better-formalized\n> way of rejecting patches that aren't going anywhere. Maybe there\n> should be a time limit on how many CFs a patch is allowed to just\n> automatically slide through?\n\nI guess the big number is 233 patches moved to next CF, out of 342, or\n68% deferred.\n\nPerhaps we need a budget of how many patches can be moved to next CF,\ni.e. CF mgr is responsible for ensuring that no more than ?50% of\npatches can be moved forwards. Any in excess of that need to join the\nkill list.\n\nI would still ask for someone to spend a little time triaging things,\nso as to direct people who volunteer to be so directed. Many will not\nwant to be directed, but I'm sure there must be 5-10 people who would\ndo that? (Volunteers?)\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/\n\n\n", "msg_date": "Tue, 3 Aug 2021 19:30:38 +0100", "msg_from": "Simon Riggs <simon.riggs@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Tue, Aug 3, 2021 at 9:13 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Bruce Momjian <bruce@momjian.us> writes:\n> > On Tue, Aug 3, 2021 at 04:53:40PM +0100, Simon Riggs wrote:\n> >> There are 273 patches in the queue for the Sept Commitfest already, so\n> >> it seems clear the queue is not being cleared down each CF as it was\n> >> before. We've been trying hard, but it's overflowing.\n>\n> > I wonder if our lack of in-person developer meetings is causing some of\n> > our issues to not get closed.\n>\n> I think there are a couple of things happening here:\n>\n> 1. There wasn't that much getting done during this CF because it's\n> summer and many people are on vacation (in the northern hemisphere\n> anyway).\n>\n> 2. As a community, we don't really have the strength of will to\n> flat-out reject patches. I think the dynamic is that individual\n> committers look at something, think \"I don't like that, I'll go\n> work on some better-designed patch\", and it just keeps slipping\n> to the next CF. In the past we've had some CFMs who were assertive\n> enough and senior enough to kill off patches that didn't look like\n> they were going to go anywhere. But that hasn't happened for\n> awhile, and I'm not sure it should be the CFM's job anyway.\n>\n> (I hasten to add that I'm not trying to imply that all the\n> long-lingering patches are hopeless. But I think some of them are.)\n>\n> I don't think there's much to be done about the vacation effect;\n> we just have to accept that the summer CF is likely to be less\n> productive than others. But I'd like to see some better-formalized\n> way of rejecting patches that aren't going anywhere. Maybe there\n> should be a time limit on how many CFs a patch is allowed to just\n> automatically slide through?\n>\n\n+1 for the idea of allowed CFs. Secondly we can think about the patches\nwhich\nhave not had a response from the author since long.\n\n\n>\n> regards, tom lane\n>\n>\n>\n\n-- \nIbrar Ahmed\n\nOn Tue, Aug 3, 2021 at 9:13 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:Bruce Momjian <bruce@momjian.us> writes:\n> On Tue, Aug  3, 2021 at 04:53:40PM +0100, Simon Riggs wrote:\n>> There are 273 patches in the queue for the Sept Commitfest already, so\n>> it seems clear the queue is not being cleared down each CF as it was\n>> before. We've been trying hard, but it's overflowing.\n\n> I wonder if our lack of in-person developer meetings is causing some of\n> our issues to not get closed.\n\nI think there are a couple of things happening here:\n\n1. There wasn't that much getting done during this CF because it's\nsummer and many people are on vacation (in the northern hemisphere\nanyway).\n\n2. As a community, we don't really have the strength of will to\nflat-out reject patches.  I think the dynamic is that individual\ncommitters look at something, think \"I don't like that, I'll go\nwork on some better-designed patch\", and it just keeps slipping\nto the next CF.  In the past we've had some CFMs who were assertive\nenough and senior enough to kill off patches that didn't look like\nthey were going to go anywhere.  But that hasn't happened for\nawhile, and I'm not sure it should be the CFM's job anyway.\n\n(I hasten to add that I'm not trying to imply that all the\nlong-lingering patches are hopeless.  But I think some of them are.)\n\nI don't think there's much to be done about the vacation effect;\nwe just have to accept that the summer CF is likely to be less\nproductive than others.  But I'd like to see some better-formalized\nway of rejecting patches that aren't going anywhere.  Maybe there\nshould be a time limit on how many CFs a patch is allowed to just\nautomatically slide through?+1 for the idea of allowed CFs. Secondly we can think about the patches whichhave not had a response from the author since long.  \n\n                        regards, tom lane\n\n\n-- Ibrar Ahmed", "msg_date": "Tue, 3 Aug 2021 23:32:50 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Tue, Aug 3, 2021 at 11:31 PM Simon Riggs <simon.riggs@enterprisedb.com>\nwrote:\n\n> On Tue, 3 Aug 2021 at 17:13, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >\n> > Bruce Momjian <bruce@momjian.us> writes:\n> > > On Tue, Aug 3, 2021 at 04:53:40PM +0100, Simon Riggs wrote:\n> > >> There are 273 patches in the queue for the Sept Commitfest already, so\n> > >> it seems clear the queue is not being cleared down each CF as it was\n> > >> before. We've been trying hard, but it's overflowing.\n> >\n> > > I wonder if our lack of in-person developer meetings is causing some of\n> > > our issues to not get closed.\n> >\n> > I think there are a couple of things happening here:\n> >\n> > 1. There wasn't that much getting done during this CF because it's\n> > summer and many people are on vacation (in the northern hemisphere\n> > anyway).\n> >\n> > 2. As a community, we don't really have the strength of will to\n> > flat-out reject patches. I think the dynamic is that individual\n> > committers look at something, think \"I don't like that, I'll go\n> > work on some better-designed patch\", and it just keeps slipping\n> > to the next CF. In the past we've had some CFMs who were assertive\n> > enough and senior enough to kill off patches that didn't look like\n> > they were going to go anywhere. But that hasn't happened for\n> > awhile, and I'm not sure it should be the CFM's job anyway.\n> >\n> > (I hasten to add that I'm not trying to imply that all the\n> > long-lingering patches are hopeless. But I think some of them are.)\n> >\n> > I don't think there's much to be done about the vacation effect;\n> > we just have to accept that the summer CF is likely to be less\n> > productive than others. But I'd like to see some better-formalized\n> > way of rejecting patches that aren't going anywhere. Maybe there\n> > should be a time limit on how many CFs a patch is allowed to just\n> > automatically slide through?\n>\n> I guess the big number is 233 patches moved to next CF, out of 342, or\n> 68% deferred.\n>\n> Perhaps we need a budget of how many patches can be moved to next CF,\n> i.e. CF mgr is responsible for ensuring that no more than ?50% of\n> patches can be moved forwards. Any in excess of that need to join the\n> kill list.\n>\n> I would still ask for someone to spend a little time triaging things,\n> so as to direct people who volunteer to be so directed. Many will not\n> want to be directed, but I'm sure there must be 5-10 people who would\n> do that? (Volunteers?)\n>\n\nCount me as a Volunteer.\n\n\n> --\n> Simon Riggs http://www.EnterpriseDB.com/\n>\n>\n>\n\n-- \nIbrar Ahmed\n\nOn Tue, Aug 3, 2021 at 11:31 PM Simon Riggs <simon.riggs@enterprisedb.com> wrote:On Tue, 3 Aug 2021 at 17:13, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Bruce Momjian <bruce@momjian.us> writes:\n> > On Tue, Aug  3, 2021 at 04:53:40PM +0100, Simon Riggs wrote:\n> >> There are 273 patches in the queue for the Sept Commitfest already, so\n> >> it seems clear the queue is not being cleared down each CF as it was\n> >> before. We've been trying hard, but it's overflowing.\n>\n> > I wonder if our lack of in-person developer meetings is causing some of\n> > our issues to not get closed.\n>\n> I think there are a couple of things happening here:\n>\n> 1. There wasn't that much getting done during this CF because it's\n> summer and many people are on vacation (in the northern hemisphere\n> anyway).\n>\n> 2. As a community, we don't really have the strength of will to\n> flat-out reject patches.  I think the dynamic is that individual\n> committers look at something, think \"I don't like that, I'll go\n> work on some better-designed patch\", and it just keeps slipping\n> to the next CF.  In the past we've had some CFMs who were assertive\n> enough and senior enough to kill off patches that didn't look like\n> they were going to go anywhere.  But that hasn't happened for\n> awhile, and I'm not sure it should be the CFM's job anyway.\n>\n> (I hasten to add that I'm not trying to imply that all the\n> long-lingering patches are hopeless.  But I think some of them are.)\n>\n> I don't think there's much to be done about the vacation effect;\n> we just have to accept that the summer CF is likely to be less\n> productive than others.  But I'd like to see some better-formalized\n> way of rejecting patches that aren't going anywhere.  Maybe there\n> should be a time limit on how many CFs a patch is allowed to just\n> automatically slide through?\n\nI guess the big number is 233 patches moved to next CF, out of 342, or\n68% deferred.\n\nPerhaps we need a budget of how many patches can be moved to next CF,\ni.e. CF mgr is responsible for ensuring that no more than ?50% of\npatches can be moved forwards. Any in excess of that need to join the\nkill list.\n\nI would still ask for someone to spend a little time triaging things,\nso as to direct people who volunteer to be so directed. Many will not\nwant to be directed, but I'm sure there must be 5-10 people who would\ndo that? (Volunteers?)Count me as a Volunteer.\n\n-- \nSimon Riggs                http://www.EnterpriseDB.com/\n\n\n-- Ibrar Ahmed", "msg_date": "Tue, 3 Aug 2021 23:34:01 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On 8/3/21 8:30 PM, Simon Riggs wrote:\n> On Tue, 3 Aug 2021 at 17:13, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>>\n>> Bruce Momjian <bruce@momjian.us> writes:\n>>> On Tue, Aug 3, 2021 at 04:53:40PM +0100, Simon Riggs wrote:\n>>>> There are 273 patches in the queue for the Sept Commitfest already, so\n>>>> it seems clear the queue is not being cleared down each CF as it was\n>>>> before. We've been trying hard, but it's overflowing.\n>>\n>>> I wonder if our lack of in-person developer meetings is causing some of\n>>> our issues to not get closed.\n>>\n>> I think there are a couple of things happening here:\n>>\n>> 1. There wasn't that much getting done during this CF because it's\n>> summer and many people are on vacation (in the northern hemisphere\n>> anyway).\n>>\n>> 2. As a community, we don't really have the strength of will to\n>> flat-out reject patches. I think the dynamic is that individual\n>> committers look at something, think \"I don't like that, I'll go\n>> work on some better-designed patch\", and it just keeps slipping\n>> to the next CF. In the past we've had some CFMs who were assertive\n>> enough and senior enough to kill off patches that didn't look like\n>> they were going to go anywhere. But that hasn't happened for\n>> awhile, and I'm not sure it should be the CFM's job anyway.\n>>\n>> (I hasten to add that I'm not trying to imply that all the\n>> long-lingering patches are hopeless. But I think some of them are.)\n>>\n>> I don't think there's much to be done about the vacation effect;\n>> we just have to accept that the summer CF is likely to be less\n>> productive than others. But I'd like to see some better-formalized\n>> way of rejecting patches that aren't going anywhere. Maybe there\n>> should be a time limit on how many CFs a patch is allowed to just\n>> automatically slide through?\n> \n> I guess the big number is 233 patches moved to next CF, out of 342, or\n> 68% deferred.\n> \n> Perhaps we need a budget of how many patches can be moved to next CF,\n> i.e. CF mgr is responsible for ensuring that no more than ?50% of\n> patches can be moved forwards. Any in excess of that need to join the\n> kill list.\n> \n\nHow would this be different from the CFM just rejecting patches? It does \nnot matter if there's an explicit number of patches that we allow to be \nmoved to the next CF - someone still needs to make the decision, and I \nagree with Tom it probably should not be CFM's job.\n\nIMO what the CFM can do is make an assessment, share it on the mailing \nlist with a proposal to reject the patch, and leave the decision up to \nthe patch author. Either the author accepts the view it's futile, or \ndecides to keep working on it, solicits some reviews, etc.\n\n> I would still ask for someone to spend a little time triaging things,\n> so as to direct people who volunteer to be so directed. Many will not\n> want to be directed, but I'm sure there must be 5-10 people who would\n> do that? (Volunteers?)\n> \n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 3 Aug 2021 20:51:57 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Tue, Aug 3, 2021 at 07:30:38PM +0100, Simon Riggs wrote:\n> I would still ask for someone to spend a little time triaging things,\n> so as to direct people who volunteer to be so directed. Many will not\n> want to be directed, but I'm sure there must be 5-10 people who would\n> do that? (Volunteers?)\n\nI am usually not around long enough to handle complex patches but I\nconsidered the query id patch important and needing guidance so I was\nable to help on that for PG 14, and I needed Álvaro Herrera's help to\ncomplete it. My point is that some of these patches are really complex\nto get them through, but I think a focused effort could make a big\nimpact, though it will take months.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Tue, 3 Aug 2021 14:54:46 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Tue, Aug 3, 2021 at 08:51:57PM +0200, Tomas Vondra wrote:\n> How would this be different from the CFM just rejecting patches? It does not\n> matter if there's an explicit number of patches that we allow to be moved to\n> the next CF - someone still needs to make the decision, and I agree with Tom\n> it probably should not be CFM's job.\n\nMy experience with the query id patch is that it can't be rejected\nbecause everyone wants it, but it needs work to get it in a state that\neveryone approves of. Sometimes it is impossible for the patch author\nto figure that out, and I needed Álvaro Herrera's help on the query id\npatch, so even I wasn't able to figure it out alone.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Tue, 3 Aug 2021 14:57:49 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On 8/3/21 8:57 PM, Bruce Momjian wrote:\n> On Tue, Aug 3, 2021 at 08:51:57PM +0200, Tomas Vondra wrote:\n>> How would this be different from the CFM just rejecting patches? It does not\n>> matter if there's an explicit number of patches that we allow to be moved to\n>> the next CF - someone still needs to make the decision, and I agree with Tom\n>> it probably should not be CFM's job.\n> \n> My experience with the query id patch is that it can't be rejected\n> because everyone wants it, but it needs work to get it in a state that\n> everyone approves of. Sometimes it is impossible for the patch author\n> to figure that out, and I needed Álvaro Herrera's help on the query id\n> patch, so even I wasn't able to figure it out alone.\n> \n\nYeah, and I'm sure this applies to various other patches too - we want \nthe feature, but it requires more work, and it may not be clear how much \nand what's the path forward.\n\nBut it's not clear to me whether you're arguing for CFM to assess this, \nor whether someone else should make this decision?\n\nIMHO asking the CFM to do this would be a tremendous burden - properly \nassessing 50+ patches is a lot of work, and probably requires a fairly \nexperienced hacker ...\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 3 Aug 2021 21:36:41 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Tue, Aug 3, 2021 at 09:36:41PM +0200, Tomas Vondra wrote:\n> On 8/3/21 8:57 PM, Bruce Momjian wrote:\n> > On Tue, Aug 3, 2021 at 08:51:57PM +0200, Tomas Vondra wrote:\n> > > How would this be different from the CFM just rejecting patches? It does not\n> > > matter if there's an explicit number of patches that we allow to be moved to\n> > > the next CF - someone still needs to make the decision, and I agree with Tom\n> > > it probably should not be CFM's job.\n> > \n> > My experience with the query id patch is that it can't be rejected\n> > because everyone wants it, but it needs work to get it in a state that\n> > everyone approves of. Sometimes it is impossible for the patch author\n> > to figure that out, and I needed Álvaro Herrera's help on the query id\n> > patch, so even I wasn't able to figure it out alone.\n> > \n> \n> Yeah, and I'm sure this applies to various other patches too - we want the\n> feature, but it requires more work, and it may not be clear how much and\n> what's the path forward.\n> \n> But it's not clear to me whether you're arguing for CFM to assess this, or\n> whether someone else should make this decision?\n> \n> IMHO asking the CFM to do this would be a tremendous burden - properly\n> assessing 50+ patches is a lot of work, and probably requires a fairly\n> experienced hacker ...\n\nI don't think the CFM can do this --- I think it has to be a team\neffort, as was the query id patch.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Tue, 3 Aug 2021 15:39:06 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "Tomas Vondra <tomas.vondra@enterprisedb.com> writes:\n> But it's not clear to me whether you're arguing for CFM to assess this, \n> or whether someone else should make this decision?\n\n> IMHO asking the CFM to do this would be a tremendous burden - properly \n> assessing 50+ patches is a lot of work, and probably requires a fairly \n> experienced hacker ...\n\nYeah. I can recall that once or twice, Andres went through and triaged\nall the open patches, which was tremendously helpful and I'm sure took a\nserious investment of time. That way doesn't scale. But maybe if we\nsplit the work among half a dozen or so senior hackers, it'd be a\ntolerable amount of work per-person?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 03 Aug 2021 15:42:57 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Tue, Aug 3, 2021 at 03:42:57PM -0400, Tom Lane wrote:\n> Tomas Vondra <tomas.vondra@enterprisedb.com> writes:\n> > But it's not clear to me whether you're arguing for CFM to assess this, \n> > or whether someone else should make this decision?\n> \n> > IMHO asking the CFM to do this would be a tremendous burden - properly \n> > assessing 50+ patches is a lot of work, and probably requires a fairly \n> > experienced hacker ...\n> \n> Yeah. I can recall that once or twice, Andres went through and triaged\n> all the open patches, which was tremendously helpful and I'm sure took a\n> serious investment of time. That way doesn't scale. But maybe if we\n> split the work among half a dozen or so senior hackers, it'd be a\n> tolerable amount of work per-person?\n\nYes, I think we are going to need to do something like this.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Tue, 3 Aug 2021 15:54:11 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Tue, 3 Aug 2021 at 11:56, Bruce Momjian <bruce@momjian.us> wrote:\n\n> I wonder if our lack of in-person developer meetings is causing some of\n> our issues to not get closed.\n\nThat's an interesting thought. Every year there are some especially\ncontentious patches that don't get dealt with until the in-person\nmeeting which pushes people to make a call. However it seems like\nthat's only a handful and not really enough to explain the volume.\n\nUnless people just find it easier to focus on reviewing in the days\nleading up to the conferences and meetings. Fwiw I will have some time\nset aside to do some patch reviewing coming up -- though I don't know\nhow much I can really help if the patches are the problem.\n\n\n-- \ngreg\n\n\n", "msg_date": "Tue, 3 Aug 2021 16:22:16 -0400", "msg_from": "Greg Stark <stark@mit.edu>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Wed, Aug 4, 2021 at 8:23 AM Greg Stark <stark@mit.edu> wrote:\n> On Tue, 3 Aug 2021 at 11:56, Bruce Momjian <bruce@momjian.us> wrote:\n>\n> > I wonder if our lack of in-person developer meetings is causing some of\n> > our issues to not get closed.\n>\n> That's an interesting thought. Every year there are some especially\n> contentious patches that don't get dealt with until the in-person\n> meeting which pushes people to make a call. However it seems like\n> that's only a handful and not really enough to explain the volume.\n\nI think there might be a higher number of work-in-progress patches\nthese days, which represent ongoing collaborative efforts, and are not\nexpected to be committed soon, but are registered to attract the\nattention of humans and robots. Perhaps if there were a separate\nstatus for that, it would be clearer. Or perhaps they don't belong in\nthe \"commit\" fest.\n\n\n", "msg_date": "Wed, 4 Aug 2021 13:49:23 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": ">\n> I think there might be a higher number of work-in-progress patches\n> these days, which represent ongoing collaborative efforts, and are not\n> expected to be committed soon, but are registered to attract the\n> attention of humans and robots. Perhaps if there were a separate\n> status for that, it would be clearer. Or perhaps they don't belong in\n> the \"commit\" fest.\n>\n\nI totally support this view on CF as a better way to track and process\nongoing community activity in the one place than the mailing list. The fact\nis that complicated patches need many CFs to be reviewed, improved and\ncommitted. I'd vote for not-so-strict approach to what should be on CF and\nwhat should not. But probably some prioritization inside CF is indeed\nneeded.\n\n-- \nBest regards,\nPavel Borisov\n\nPostgres Professional: http://postgrespro.com <http://www.postgrespro.com>\n\nI think there might be a higher number of work-in-progress patches\nthese days, which represent ongoing collaborative efforts, and are not\nexpected to be committed soon, but are registered to attract the\nattention of humans and robots.  Perhaps if there were a separate\nstatus for that, it would be clearer.  Or perhaps they don't belong in\nthe \"commit\" fest. I totally support this view on CF as a better way to track and process ongoing community activity in the one place than the mailing list. The fact is that complicated patches need many CFs to be reviewed, improved and committed. I'd vote for not-so-strict approach to what should be on CF and what should not. But probably some prioritization inside CF is indeed needed.-- Best regards,Pavel BorisovPostgres Professional: http://postgrespro.com", "msg_date": "Wed, 4 Aug 2021 22:51:50 +0400", "msg_from": "Pavel Borisov <pashkin.elfe@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Tue, Aug 03, 2021 at 12:13:44PM -0400, Tom Lane wrote:\n> Bruce Momjian <bruce@momjian.us> writes:\n> > On Tue, Aug 3, 2021 at 04:53:40PM +0100, Simon Riggs wrote:\n> >> There are 273 patches in the queue for the Sept Commitfest already, so\n> >> it seems clear the queue is not being cleared down each CF as it was\n> >> before. We've been trying hard, but it's overflowing.\n\n> 1. There wasn't that much getting done during this CF because it's\n> summer and many people are on vacation (in the northern hemisphere\n> anyway).\n\n> I don't think there's much to be done about the vacation effect;\n> we just have to accept that the summer CF is likely to be less\n> productive than others.\n\nEarly commitfests recognized a rule that patch authors owed one review per\npatch registered in the commitfest. If authors were holding to that, then\nboth submissions and reviews would slow during vacations, but the neglected\nfraction of the commitfest would be about the same. I think it would help to\ntrack each author's balance (reviews_done - reviews_owed).\n\n\n", "msg_date": "Thu, 5 Aug 2021 00:25:32 -0400", "msg_from": "Noah Misch <noah@leadboat.com>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "\n\n> 5 авг. 2021 г., в 09:25, Noah Misch <noah@leadboat.com> написал(а):\n> \n> On Tue, Aug 03, 2021 at 12:13:44PM -0400, Tom Lane wrote:\n>> Bruce Momjian <bruce@momjian.us> writes:\n>>> On Tue, Aug 3, 2021 at 04:53:40PM +0100, Simon Riggs wrote:\n>>>> There are 273 patches in the queue for the Sept Commitfest already, so\n>>>> it seems clear the queue is not being cleared down each CF as it was\n>>>> before. We've been trying hard, but it's overflowing.\n> \n>> 1. There wasn't that much getting done during this CF because it's\n>> summer and many people are on vacation (in the northern hemisphere\n>> anyway).\n> \n>> I don't think there's much to be done about the vacation effect;\n>> we just have to accept that the summer CF is likely to be less\n>> productive than others.\n> \n> Early commitfests recognized a rule that patch authors owed one review per\n> patch registered in the commitfest. If authors were holding to that, then\n> both submissions and reviews would slow during vacations, but the neglected\n> fraction of the commitfest would be about the same. I think it would help to\n> track each author's balance (reviews_done - reviews_owed).\n\n+1 for tracking this.\nBTW when review is done? When first revision is published? Or when patch is committed\\rollbacked?\nWhen the review is owed? At the moment when patch is submitted? Or when it is committed?\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Thu, 5 Aug 2021 11:39:47 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Tue, Aug 03, 2021 at 11:55:50AM -0400, Bruce Momjian wrote:\n> On Tue, Aug 3, 2021 at 04:53:40PM +0100, Simon Riggs wrote:\n> > There are 273 patches in the queue for the Sept Commitfest already, so\n> > it seems clear the queue is not being cleared down each CF as it was\n> > before. We've been trying hard, but it's overflowing.\n> > \n> > Of those, about 50 items have been waiting more than one year, and\n> > about 25 entries waiting for more than two years.\n> > \n> > One problem is that many entries don't have official reviewers, though\n> > many people have commented on Hackers, making it difficult to track\n> > down items that actually need work. That wastes a lot of time for\n> > would-be reviewers (or at least, it has done for me).\n> > \n> > Please can there be some additional coordination to actively clear\n> > down this problem? I won't attempt to come up with ideas to do this,\n> > but others may wish to suggest ways that avoid Committer burn-out?\n> > \n> > I will be happy to volunteer to be part of an organized approach that\n> > spreads out the work.\n> \n> I wonder if our lack of in-person developer meetings is causing some of\n> our issues to not get closed.\n\nWell, or the lack of virtual developer meetings? Sure, in-person\nmeetings are difficult now, but OTOH virtual meetings are very common\nthese days and maybe could be tried as quarterly developer meetings or\nso and have the advantage that, modulo timezone problems, every\n(invited) developer could attend.\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, Geoff Richardson,\nPeter Lilley\n\nUnser Umgang mit personenbezogenen Daten unterliegt\nfolgenden Bestimmungen: https://www.credativ.de/datenschutz\n\n\n", "msg_date": "Thu, 5 Aug 2021 11:27:28 +0200", "msg_from": "Michael Banck <michael.banck@credativ.de>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On 8/5/21 11:27 AM, Michael Banck wrote:\n> On Tue, Aug 03, 2021 at 11:55:50AM -0400, Bruce Momjian wrote:\n>> On Tue, Aug 3, 2021 at 04:53:40PM +0100, Simon Riggs wrote:\n>>> There are 273 patches in the queue for the Sept Commitfest already, so\n>>> it seems clear the queue is not being cleared down each CF as it was\n>>> before. We've been trying hard, but it's overflowing.\n>>>\n>>> ...\n>>\n>> I wonder if our lack of in-person developer meetings is causing some of\n>> our issues to not get closed.\n> \n> Well, or the lack of virtual developer meetings? Sure, in-person\n> meetings are difficult now, but OTOH virtual meetings are very common\n> these days and maybe could be tried as quarterly developer meetings or\n> so and have the advantage that, modulo timezone problems, every\n> (invited) developer could attend.\n> \n\nI'm quite tired of virtual meetings, but I agree the lack of meetings is \nnoticeable so maybe we should give it a try. In fact, we'll probably \nneed to do that anyway, because even if there's an in-person meeting \nearly next year the in-person participation is likely to be limited.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 5 Aug 2021 14:49:14 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On 8/5/21 8:39 AM, Andrey Borodin wrote:\n>> ...\n>>\n>> Early commitfests recognized a rule that patch authors owed one review per\n>> patch registered in the commitfest. If authors were holding to that, then\n>> both submissions and reviews would slow during vacations, but the neglected\n>> fraction of the commitfest would be about the same. I think it would help to\n>> track each author's balance (reviews_done - reviews_owed).\n> \n> +1 for tracking this.\n\nYeah, I agree we should be stricter about this rule, but I'm somewhat \nskeptical about tracking it in the CF app - judging patch and review \ncomplexity seems quite subjective, etc.\n\n> BTW when review is done? When first revision is published? Or when patch is committed\\rollbacked?\n> When the review is owed? At the moment when patch is submitted? Or when it is committed?\n> \n\nI think the rule is roughly that when you submit a patch to a CF, you're \nexpected to review a patch of comparable complexity in the same CF. It's \nnot tied to whether the patch is committed, etc.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 5 Aug 2021 15:06:54 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "\nOn 8/5/21 8:49 AM, Tomas Vondra wrote:\n> On 8/5/21 11:27 AM, Michael Banck wrote:\n>> On Tue, Aug 03, 2021 at 11:55:50AM -0400, Bruce Momjian wrote:\n>>> On Tue, Aug  3, 2021 at 04:53:40PM +0100, Simon Riggs wrote:\n>>>> There are 273 patches in the queue for the Sept Commitfest already, so\n>>>> it seems clear the queue is not being cleared down each CF as it was\n>>>> before. We've been trying hard, but it's overflowing.\n>>>>\n>>>> ...\n>>>\n>>> I wonder if our lack of in-person developer meetings is causing some of\n>>> our issues to not get closed.\n>>\n>> Well, or the lack of virtual developer meetings? Sure, in-person\n>> meetings are difficult now, but OTOH virtual meetings are very common\n>> these days and maybe could be tried as quarterly developer meetings or\n>> so and have the advantage that, modulo timezone problems, every\n>> (invited) developer could attend.\n>>\n>\n> I'm quite tired of virtual meetings, but I agree the lack of meetings\n> is noticeable so maybe we should give it a try. In fact, we'll\n> probably need to do that anyway, because even if there's an in-person\n> meeting early next year the in-person participation is likely to be\n> limited.\n>\n>\n>\n\n+1\n\n\ncheers\n\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Thu, 5 Aug 2021 10:05:09 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Tue, Aug 3, 2021 at 2:52 PM Tomas Vondra\n<tomas.vondra@enterprisedb.com> wrote:\n> How would this be different from the CFM just rejecting patches? It does\n> not matter if there's an explicit number of patches that we allow to be\n> moved to the next CF - someone still needs to make the decision, and I\n> agree with Tom it probably should not be CFM's job.\n>\n> IMO what the CFM can do is make an assessment, share it on the mailing\n> list with a proposal to reject the patch, and leave the decision up to\n> the patch author. Either the author accepts the view it's futile, or\n> decides to keep working on it, solicits some reviews, etc.\n\nI don't really agree with this. Not all decisions can or should be\nmade collaboratively.\n\nIn particular, I think CfM's have been pretty timid about bouncing\nstuff that isn't really showing signs of progress. If a patch has been\nreviewed at some point in the past, and say a month has gone by, and\nnow we're beginning or ending a CommitFest, the patch should just be\nclosed. Otherwise the CommitFest just fills up with clutter. It's not\nthe worst thing in the world to ask on the thread, \"hey, can we RwF\nthis?\" but it risks delaying a decision that ought to have been\nautomatic. Patches that are not being updated regularly have no\nbusiness being part of a CommitFest.\n\nAlso, if it's clear that an idea has quite a bit of opposition, it\nshould be RwF'd or rejected, even if the patch author doesn't agree.\nNothing whatever keeps the patch author from continuing to argue about\nit, or indeed resubmitting the patch. But we don't get any value out\nof having a list of things that somebody should take a look at which\nincludes things that have been looked at already and judged by\nmultiple people to be not acceptable. I don't think a patch should be\nrejected on the strength of a single -1, but when 2 or 3 people have\nshown up to say either that they don't like the idea or that the\nimplementation is way off base, it's not helpful to leave things in a\nstate that suggests it needs more eyeballs.\n\nArguing with people about the merits of a patch that has a 0%\nprobability of being committed by anybody is one of my least favorite\nthings. I have only so much time, and I want to invest the time I have\nin things that have a chance of getting someplace. I don't mind the\ntime spent telling somebody whose patch is bad why it has no hope -\nand I think that's an important thing for us to do. But if somebody\nthinks, say, that full page writes are not needed and we should just\nremove them, I only want to explain why they are wrong. I don't want\nto argue about whether they are actually right. There are plenty of\npatches where somebody has ideas that may or may not be good and we\nshould talk about it - but there are also some where talking isn't\ngoing to help, and those can easily consume massive amounts of time\nand energy.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 5 Aug 2021 10:36:14 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Thu, Aug 05, 2021 at 03:06:54PM +0200, Tomas Vondra wrote:\n> On 8/5/21 8:39 AM, Andrey Borodin wrote:\n> >>...\n> >>\n> >>Early commitfests recognized a rule that patch authors owed one review per\n> >>patch registered in the commitfest. If authors were holding to that, then\n> >>both submissions and reviews would slow during vacations, but the neglected\n> >>fraction of the commitfest would be about the same. I think it would help to\n> >>track each author's balance (reviews_done - reviews_owed).\n> >\n> >+1 for tracking this.\n> \n> Yeah, I agree we should be stricter about this rule, but I'm somewhat\n> skeptical about tracking it in the CF app - judging patch and review\n> complexity seems quite subjective, etc.\n\nThe CF app presently lacks the data to track this, but with relevant feature\nadditions, I suspect it would be the best place to manage tracking. Something\nlike this: when a CF app user changes a patch status from Needs Review or\nReady for Committer to anything else, invite that user to name a recipient of\nreview credit.\n\n> >BTW when review is done? When first revision is published? Or when patch is committed\\rollbacked?\n> >When the review is owed? At the moment when patch is submitted? Or when it is committed?\n\nThose are important questions. Here are answers that feel reasonable to me,\nbut they may need refinement. Anyone can increase their reviews_done by\nsending a review that causes a patch to leave Needs Review status in the CF\napp for the first time in a given commitfest. Trivial defect reports,\ne.g. that the patch doesn't compile, are not reviews; the person setting\nWaiting on Author shall not assign review credit. Committers can increase\ntheir reviews_done by sending a review that causes a patch to leave Ready for\nCommitter status for the first time in a given commitfest; however, nobody\nreceives two credits for the same patch, in the same commitfest. Whenever a\nCF entry is increasing someone's reviews_done, it also increases reviews_owed\nfor the entry's author. What do you think?\n\n(Consequences: each CF entry can increment reviews_done of up to two users per\ncommitfest, but it increments reviews_owed just once. If the patch bounces\nbetween Needs Review and Waiting on Author several times in a single CF, that\ncounts as a total of one review.)\n\n> I think the rule is roughly that when you submit a patch to a CF, you're\n> expected to review a patch of comparable complexity in the same CF. It's not\n> tied to whether the patch is committed, etc.\n\nYep. Would we get reasonable incentives without tracking \"comparable\ncomplexity\" explicitly? That bit is harder to judge.\n\n\n", "msg_date": "Thu, 5 Aug 2021 21:12:48 -0700", "msg_from": "Noah Misch <noah@leadboat.com>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "> On Tue, Aug 03, 2021 at 02:57:49PM -0400, Bruce Momjian wrote:\n>\n> On Tue, Aug 3, 2021 at 08:51:57PM +0200, Tomas Vondra wrote:\n> > How would this be different from the CFM just rejecting patches? It does not\n> > matter if there's an explicit number of patches that we allow to be moved to\n> > the next CF - someone still needs to make the decision, and I agree with Tom\n> > it probably should not be CFM's job.\n>\n> My experience with the query id patch is that it can't be rejected\n> because everyone wants it, but it needs work to get it in a state that\n> everyone approves of. Sometimes it is impossible for the patch author\n> to figure that out, and I needed �lvaro Herrera's help on the query id\n> patch, so even I wasn't able to figure it out alone.\n\nI know I'm late to the party, but I couldn't stop thinking about this\nthread. Since there seems to be no specific changes agreed upon in\nhere, I wanted to add my 5c.\n\nIt's indeed hard at times to use CF app efficiently due to cluttering of\ndifferent sorts:\n\n* Patches slipping through CFs \"waiting on author\". Hopefully CFM can\n identify such cases without much efforts.\n\n* Patches slipping through CFs on \"needs review\", while, as you mention,\n sometimes it is hard for the author to figure something out and an\n attention of more knowledgeable hacker is needed. Most of the time\n this status means \"needs a design review\" (which should be probably\n even introduced as a real status), and such review is indeed a scarce\n resource in the community. Due to that a certain level of cluttering\n is unavoidable in the long term I believe, no matter how many hackers\n will go triaging things.\n\n* Bloat in the official reviewers field, which was mentioned at the\n start. I believe there were suggestions in the past to address this\n via resetting the field automatically on the start of every CF.\n\n As a side note, maybe one could go even further in resetting /\n automation and put the responsibility for moving patches between CF\n fully on shoulders of the authors.\n\n\n", "msg_date": "Sat, 7 Aug 2021 21:32:45 +0200", "msg_from": "Dmitry Dolgov <9erthalion6@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Tue, Aug 3, 2021 at 8:53 AM Simon Riggs <simon.riggs@enterprisedb.com>\nwrote:\n\n> There are 273 patches in the queue for the Sept Commitfest already, so\n> it seems clear the queue is not being cleared down each CF as it was\n> before. We've been trying hard, but it's overflowing.\n>\n\nI think one simple change here would be of some help. Every patch should\ncome on to the commitfest in \"Proposed\" Status. Someone besides the author\nof the patch then needs to move it from \"Proposed\" to \"Needs Review\". That\nperson does not have to be a reviewer or committer and is not obligating\nthemselves to working on the patch (though likely they would provide\ninput). They are simply, in the language of Robert's Rules of Order,\nseconding the motion.\n\nRemoval from the CF could be automatic after the 3rd CF, though the CF\nmanagers involved should, before returning it as \"No Interest at this\nTime\", skim the thread and ask whether any commenters on the thread would\nlike to see it kept alive in the commitfest by seconding it. If so\nremoved, the author should be encouraged to re-submit during the next\nversion's development cycle.\n\nDavid J.\n\nOn Tue, Aug 3, 2021 at 8:53 AM Simon Riggs <simon.riggs@enterprisedb.com> wrote:There are 273 patches in the queue for the Sept Commitfest already, so\nit seems clear the queue is not being cleared down each CF as it was\nbefore. We've been trying hard, but it's overflowing.I think one simple change here would be of some help.  Every patch should come on to the commitfest in \"Proposed\" Status.  Someone besides the author of the patch then needs to move it from \"Proposed\" to \"Needs Review\".  That person does not have to be a reviewer or committer and is not obligating themselves to working on the patch (though likely they would provide input).  They are simply, in the language of Robert's Rules of Order, seconding the motion.Removal from the CF could be automatic after the 3rd CF, though the CF managers involved should, before returning it as \"No Interest at this Time\", skim the thread and ask whether any commenters on the thread would like to see it kept alive in the commitfest by seconding it.  If so removed, the author should be encouraged to re-submit during the next version's development cycle.David J.", "msg_date": "Sat, 7 Aug 2021 13:31:41 -0700", "msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Tue, Aug 3, 2021 at 8:53 AM Simon Riggs <simon.riggs@enterprisedb.com>\nwrote:\n\n> There are 273 patches in the queue for the Sept Commitfest already, so\n> it seems clear the queue is not being cleared down each CF as it was\n> before. We've been trying hard, but it's overflowing.\n>\n> Of those, about 50 items have been waiting more than one year, and\n> about 25 entries waiting for more than two years.\n>\n\nThe \"Last Modified\" field should probably omitted. The fact that \"Moved to\nNext CF\" changes this date is unhelpful. I'd much rather replace it with a\n\"last patch provided\" date, or, better, an \"days since\" calculation\ninstead. Having the system record the email addresses that replied to the\nthread instead of strictly looking at people who interact with the\ncommitfest application would probably also be useful information for\ncommitfest people looking to see where limited attention would be best\nspent.\n\nDavid J.\n\nOn Tue, Aug 3, 2021 at 8:53 AM Simon Riggs <simon.riggs@enterprisedb.com> wrote:There are 273 patches in the queue for the Sept Commitfest already, so\nit seems clear the queue is not being cleared down each CF as it was\nbefore. We've been trying hard, but it's overflowing.\n\nOf those, about 50 items have been waiting more than one year, and\nabout 25 entries waiting for more than two years.The \"Last Modified\" field should probably omitted.  The fact that \"Moved to Next CF\" changes this date is unhelpful.  I'd much rather replace it with a \"last patch provided\" date, or, better, an \"days since\" calculation instead.  Having the system record the email addresses that replied to the thread instead of strictly looking at people who interact with the commitfest application would probably also be useful information for commitfest people looking to see where limited attention would be best spent.David J.", "msg_date": "Sat, 7 Aug 2021 13:53:47 -0700", "msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" }, { "msg_contents": "On Thu, Aug 5, 2021 at 7:36 AM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> Patches that are not being updated regularly have no\n> business being part of a CommitFest.\n>\n\nAs the main issue seems to be \"Needs Review\" getting punted, the patch\nauthor rightly expects feedback before supplying new patches. If they are\nwaiting for months, that isn't on them.\n\n\n> I don't think a patch should be\n> rejected on the strength of a single -1, but when 2 or 3 people have\n> shown up to say either that they don't like the idea or that the\n> implementation is way off base, it's not helpful to leave things in a\n> state that suggests it needs more eyeballs.\n>\n>\nI would agree. One of those 3 people should then state in the thread where\nthey put their -1 that they are, in addition, going to mark the patch as\nRwF or Rejected in the CF, and then go do just that. If that isn't done,\nand the CfM comes across this situation, they should probably request the\nperson with the first -1 to make the change instead of doing it for them.\nAnd it doesn't have to be explicit -1s to qualify.\n\nDavid J.\n\nOn Thu, Aug 5, 2021 at 7:36 AM Robert Haas <robertmhaas@gmail.com> wrote:Patches that are not being updated regularly have no\nbusiness being part of a CommitFest.As the main issue seems to be \"Needs Review\" getting punted, the patch author rightly expects feedback before supplying new patches.  If they are waiting for months, that isn't on them. I don't think a patch should be\nrejected on the strength of a single -1, but when 2 or 3 people have\nshown up to say either that they don't like the idea or that the\nimplementation is way off base, it's not helpful to leave things in a\nstate that suggests it needs more eyeballs.I would agree.  One of those 3 people should then state in the thread where they put their -1 that they are, in addition, going to mark the patch as RwF or Rejected in the CF, and then go do just that.  If that isn't done, and the CfM comes across this situation, they should probably request the person with the first -1 to make the change instead of doing it for them.  And it doesn't have to be explicit -1s to qualify.David J.", "msg_date": "Sat, 7 Aug 2021 14:11:25 -0700", "msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Commitfest overflow" } ]
[ { "msg_contents": "Hi all,\nI am building libecpg 13.1 but 13.3 behaves in the same manner and my build\nfails with:\n\npath.c: In function 'get_html_path':\npath.c:787:38: error: 'HTMLDIR' undeclared (first use in this function)\n 787 | make_relative_path(ret_path, HTMLDIR, PGBINDIR, my_exec_path);\n | ^~~~~~~\npath.c:787:38: note: each undeclared identifier is reported only once\nfor each function it appears in\npath.c: In function 'get_man_path':\npath.c:796:38: error: 'MANDIR' undeclared (first use in this\nfunction); did you mean 'MAXDIM'?\n 796 | make_relative_path(ret_path, MANDIR, PGBINDIR, my_exec_path);\n | ^~~~~~\n | MAXDIM\nmake[2]: *** [<builtin>: path.o] Error 1\n\nIt looks like some dependency issue, because this error is followed by:\nmake[2]: Entering directory '/builddir/build/BUILD/postgresql-13.1/src/port'\necho \"#define PGBINDIR \\\"/usr/bin\\\"\" >pg_config_paths.h\necho \"#define PGSHAREDIR \\\"/usr/share/pgsql\\\"\" >>pg_config_paths.h\necho \"#define SYSCONFDIR \\\"/etc\\\"\" >>pg_config_paths.h\necho \"#define INCLUDEDIR \\\"/usr/include\\\"\" >>pg_config_paths.h\necho \"#define PKGINCLUDEDIR \\\"/usr/include/pgsql\\\"\" >>pg_config_paths.h\necho \"#define INCLUDEDIRSERVER \\\"/usr/include/pgsql/server\\\"\"\n>>pg_config_paths.h\necho \"#define LIBDIR \\\"/usr/lib64\\\"\" >>pg_config_paths.h\necho \"#define PKGLIBDIR \\\"/usr/lib64/pgsql\\\"\" >>pg_config_paths.h\necho \"#define LOCALEDIR \\\"/usr/share/locale\\\"\" >>pg_config_paths.h\necho \"#define DOCDIR \\\"/usr/share/doc//pgsql\\\"\" >>pg_config_paths.h\necho \"#define HTMLDIR \\\"/usr/share/doc//pgsql\\\"\" >>pg_config_paths.h\necho \"#define MANDIR \\\"/usr/share/man\\\"\" >>pg_config_paths.h\nmake[2]: Leaving directory '/builddir/build/BUILD/postgresql-13.1/src/port'\n\nSo from my point of view, pg_config_paths.h header file finished\n*after* it was used to compile code.\n\nThis issue is probably caused by parallel build because sometimes build succeed.\n\nComplete build log: log <https://fjanus.fedorapeople.org/postgresql/build.log>\n\nRegards,\n\n -Filip-\n\nHi all,I am building libecpg 13.1 but 13.3 behaves in the same manner and my build fails with:path.c: In function 'get_html_path':\npath.c:787:38: error: 'HTMLDIR' undeclared (first use in this function)\n 787 | make_relative_path(ret_path, HTMLDIR, PGBINDIR, my_exec_path);\n | ^~~~~~~\npath.c:787:38: note: each undeclared identifier is reported only once for each function it appears in\npath.c: In function 'get_man_path':\npath.c:796:38: error: 'MANDIR' undeclared (first use in this function); did you mean 'MAXDIM'?\n 796 | make_relative_path(ret_path, MANDIR, PGBINDIR, my_exec_path);\n | ^~~~~~\n | MAXDIM\nmake[2]: *** [<builtin>: path.o] Error 1It looks like some dependency issue, because this error is followed by:\n\nmake[2]: Entering directory '/builddir/build/BUILD/postgresql-13.1/src/port'\necho \"#define PGBINDIR \\\"/usr/bin\\\"\" >pg_config_paths.h\necho \"#define PGSHAREDIR \\\"/usr/share/pgsql\\\"\" >>pg_config_paths.h\necho \"#define SYSCONFDIR \\\"/etc\\\"\" >>pg_config_paths.h\necho \"#define INCLUDEDIR \\\"/usr/include\\\"\" >>pg_config_paths.h\necho \"#define PKGINCLUDEDIR \\\"/usr/include/pgsql\\\"\" >>pg_config_paths.h\necho \"#define INCLUDEDIRSERVER \\\"/usr/include/pgsql/server\\\"\" >>pg_config_paths.h\necho \"#define LIBDIR \\\"/usr/lib64\\\"\" >>pg_config_paths.h\necho \"#define PKGLIBDIR \\\"/usr/lib64/pgsql\\\"\" >>pg_config_paths.h\necho \"#define LOCALEDIR \\\"/usr/share/locale\\\"\" >>pg_config_paths.h\necho \"#define DOCDIR \\\"/usr/share/doc//pgsql\\\"\" >>pg_config_paths.h\necho \"#define HTMLDIR \\\"/usr/share/doc//pgsql\\\"\" >>pg_config_paths.h\necho \"#define MANDIR \\\"/usr/share/man\\\"\" >>pg_config_paths.h\nmake[2]: Leaving directory '/builddir/build/BUILD/postgresql-13.1/src/port'So from my point of view, pg_config_paths.h header file finished *after* it was used to compile code.This issue is probably caused by parallel build because sometimes build succeed.Complete build log: logRegards,\n    -Filip-", "msg_date": "Wed, 4 Aug 2021 09:50:31 +0200", "msg_from": "Filip Janus <fjanus@redhat.com>", "msg_from_op": true, "msg_subject": "Possible dependency issue in makefile" }, { "msg_contents": "Filip Janus <fjanus@redhat.com> writes:\n> I am building libecpg 13.1 but 13.3 behaves in the same manner and my build\n> fails with:\n> ...\n> Complete build log: log <https://fjanus.fedorapeople.org/postgresql/build.log>\n\nIt looks like you're just running configure and then trying to do this:\n\n/usr/bin/make -O -j40 V=1 VERBOSE=1 -C src/interfaces/ecpg\n\nwhich is probably not a great idea. It bypasses the .NOTPARALLEL:\nin src/Makefile, which would normally ensure that src/port gets\nbuilt before src/interfaces. If you want to not build the entire\nsystem, I think a minimal approach would be to make src/port,\nsrc/common, src/interfaces/libpq, then src/interfaces/ecpg, in series.\n\nAs-is, it looks like two different sub-makes are recursing to build\npg_config_paths.h concurrently. Since the rule for that is\n\npg_config_paths.h: $(top_builddir)/src/Makefile.global\n\techo \"#define PGBINDIR \\\"$(bindir)\\\"\" >$@\n\techo \"#define PGSHAREDIR \\\"$(datadir)\\\"\" >>$@\n\t...\n\techo \"#define HTMLDIR \\\"$(htmldir)\\\"\" >>$@\n\techo \"#define MANDIR \\\"$(mandir)\\\"\" >>$@\n\nit's not too surprising that concurrent builds misbehave. I don't\nknow of any way to prevent make from doing that other than\nsprinkling .NOTPARALLEL around a lot more, which would defeat\nyour purpose in using -j in the first place.\n\nWe could possibly adjust this specific rule to create pg_config_paths.h\natomically (say, write to a temp file and then \"mv\" it into place), but\nI don't have any faith that there's not other similar issues behind\nthis one. Building ecpg by itself is not a case that we test or consider\nsupported.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 04 Aug 2021 09:46:15 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Possible dependency issue in makefile" }, { "msg_contents": "Thanks, for Your advice Tom.\nI tried writing to temp file followed by mv, but it didn't bring the\ndesired effect.\nI am going to follow Your minimal approach and I'll build src/port,\nsrc/common, src/interfaces/libpq, then src/interfaces/ecpg, in series.\n\nRegards,\n\n -Filip-\n\nst 4. 8. 2021 v 15:46 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:\n\n> Filip Janus <fjanus@redhat.com> writes:\n> > I am building libecpg 13.1 but 13.3 behaves in the same manner and my\n> build\n> > fails with:\n> > ...\n> > Complete build log: log <\n> https://fjanus.fedorapeople.org/postgresql/build.log>\n>\n> It looks like you're just running configure and then trying to do this:\n>\n> /usr/bin/make -O -j40 V=1 VERBOSE=1 -C src/interfaces/ecpg\n>\n> which is probably not a great idea. It bypasses the .NOTPARALLEL:\n> in src/Makefile, which would normally ensure that src/port gets\n> built before src/interfaces. If you want to not build the entire\n> system, I think a minimal approach would be to make src/port,\n> src/common, src/interfaces/libpq, then src/interfaces/ecpg, in series.\n>\n> As-is, it looks like two different sub-makes are recursing to build\n> pg_config_paths.h concurrently. Since the rule for that is\n>\n> pg_config_paths.h: $(top_builddir)/src/Makefile.global\n> echo \"#define PGBINDIR \\\"$(bindir)\\\"\" >$@\n> echo \"#define PGSHAREDIR \\\"$(datadir)\\\"\" >>$@\n> ...\n> echo \"#define HTMLDIR \\\"$(htmldir)\\\"\" >>$@\n> echo \"#define MANDIR \\\"$(mandir)\\\"\" >>$@\n>\n> it's not too surprising that concurrent builds misbehave. I don't\n> know of any way to prevent make from doing that other than\n> sprinkling .NOTPARALLEL around a lot more, which would defeat\n> your purpose in using -j in the first place.\n>\n> We could possibly adjust this specific rule to create pg_config_paths.h\n> atomically (say, write to a temp file and then \"mv\" it into place), but\n> I don't have any faith that there's not other similar issues behind\n> this one. Building ecpg by itself is not a case that we test or consider\n> supported.\n>\n> regards, tom lane\n>\n>\n>\n\nThanks, for Your advice Tom.I tried writing to temp file followed by mv, but it didn't bring the desired effect.I am going to follow Your minimal approach and I'll build src/port,src/common, src/interfaces/libpq, then src/interfaces/ecpg, in series. Regards,    -Filip-st 4. 8. 2021 v 15:46 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:Filip Janus <fjanus@redhat.com> writes:\n> I am building libecpg 13.1 but 13.3 behaves in the same manner and my build\n> fails with:\n> ...\n> Complete build log: log <https://fjanus.fedorapeople.org/postgresql/build.log>\n\nIt looks like you're just running configure and then trying to do this:\n\n/usr/bin/make -O -j40 V=1 VERBOSE=1 -C src/interfaces/ecpg\n\nwhich is probably not a great idea.  It bypasses the .NOTPARALLEL:\nin src/Makefile, which would normally ensure that src/port gets\nbuilt before src/interfaces.  If you want to not build the entire\nsystem, I think a minimal approach would be to make src/port,\nsrc/common, src/interfaces/libpq, then src/interfaces/ecpg, in series.\n\nAs-is, it looks like two different sub-makes are recursing to build\npg_config_paths.h concurrently.  Since the rule for that is\n\npg_config_paths.h: $(top_builddir)/src/Makefile.global\n        echo \"#define PGBINDIR \\\"$(bindir)\\\"\" >$@\n        echo \"#define PGSHAREDIR \\\"$(datadir)\\\"\" >>$@\n        ...\n        echo \"#define HTMLDIR \\\"$(htmldir)\\\"\" >>$@\n        echo \"#define MANDIR \\\"$(mandir)\\\"\" >>$@\n\nit's not too surprising that concurrent builds misbehave.  I don't\nknow of any way to prevent make from doing that other than\nsprinkling .NOTPARALLEL around a lot more, which would defeat\nyour purpose in using -j in the first place.\n\nWe could possibly adjust this specific rule to create pg_config_paths.h\natomically (say, write to a temp file and then \"mv\" it into place), but\nI don't have any faith that there's not other similar issues behind\nthis one.  Building ecpg by itself is not a case that we test or consider\nsupported.\n\n                        regards, tom lane", "msg_date": "Thu, 5 Aug 2021 10:12:56 +0200", "msg_from": "Filip Janus <fjanus@redhat.com>", "msg_from_op": true, "msg_subject": "Re: Possible dependency issue in makefile" } ]
[ { "msg_contents": "\nI have just pushed Release 13.1 of the PostgreSQL BuildFarm client.\n\nThis update to Release 13 fixes errors that occur from the new default\nbranch name checking code when used with versions of git that are too\nold. This code is now disabled if the git version is not capable of\nrunning it, and in verbose mode a warning is printed. The warning can be\ndisabled by explicitly setting \"skip_git_default_check => 1\" in the\nconfig file. In either case, the owner will need to update their git\ninstallation or remove all branch and mirror repositories when the\ndefault branch name changes.\n\n\nDownloads are available at\n<https://github.com/PGBuildFarm/client-code/releases> and\n<https://buildfarm.postgresql.org/downloads>\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Wed, 4 Aug 2021 09:26:26 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": true, "msg_subject": "Release 13.1 of the PostgreSQL BuildFarm client" } ]
[ { "msg_contents": "CPU caches have multiple levels, so I had an idea to use that concept in\nthe syscaches.\n\nImagine if catcache buckets were cacheline-sized. In that case, we would\nstore the most recently accessed hash values and pointers to catctup, in\naddition to the dlist_head:\n\ntypedef struct cc_bucket\n{\n uint32 hashes[4];\n catctup *ct[4];\n dlist_head;\n};\n\nYou can think of the bucket here as a 4-way set associative L1 and the list\nwalk as an inclusive L2. There might be an existing term for this scheme,\nbut I don't know what it is offhand.\n\nCreating entries:\n\nInstead of calling dlist_push_head(), we call dlist_push_tail() and then\nstash the entry in the L1 so it's still quickly available if it's accessed\nin the near future. This way, older entries evicted from L1 will tend to\nremain toward the front of the list. Walking the list will always go from\noldest to newest, which might have better prefetch behavior (not sure).\n\nSearch:\n\nBuckets with <= 4 entries would only need to access a single cacheline to\nget the catctup pointer with the matching hash value. If we have to walk\nthe list to find a match, we stash it in the L1, which is faster than\ncalling dlist_move_head().\n\nL1 Eviction:\n\nWhen putting an entry here, we memmove() everything down in each array and\nplace the pointer and the hash value in the front, evicting the fourth\n(possibly NULL) entry.\n\nThe buckets would now be 4 times larger on 64-bit machines, but that might\nnot be a problem if we just divide the initial bucket size by four as well.\nIf the minimum nbuckets is 2, then the smaller caches would waste a bit of\nspace, but it doesn't seem too bad. As far as when to rehash the bucket\narray, the fill factor would logically jump from 2 to 8. The worst-case\nlist walk would be longer, but with a better overall memory access pattern,\nit might be fine.\n\nI think it would be straightforward to code this up -- the difficulty is\ntesting and accounting for random effects due to binary layout changes.\nThoughts?\n\n-- \nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nCPU caches have multiple levels, so I had an idea to use that concept in the syscaches.Imagine if catcache buckets were cacheline-sized. In that case, we would store the most recently accessed hash values and pointers to catctup, in addition to the dlist_head:typedef struct cc_bucket{  uint32 hashes[4];  catctup *ct[4];  dlist_head;};You can think of the bucket here as a 4-way set associative L1 and the list walk as an inclusive L2. There might be an existing term for this scheme, but I don't know what it is offhand.Creating entries:Instead of calling dlist_push_head(), we call dlist_push_tail() and then stash the entry in the L1 so it's still quickly available if it's accessed in the near future. This way, older entries evicted from L1 will tend to remain toward the front of the list. Walking the list will always go from oldest to newest, which might have better prefetch behavior (not sure).Search:Buckets with <= 4 entries would only need to access a single cacheline to get the catctup pointer with the matching hash value. If we have to walk the list to find a match, we stash it in the L1, which is faster than calling dlist_move_head().L1 Eviction:When putting an entry here, we memmove() everything down in each array and place the pointer and the hash value in the front, evicting the fourth (possibly NULL) entry.The buckets would now be 4 times larger on 64-bit machines, but that might not be a problem if we just divide the initial bucket size by four as well. If the minimum nbuckets is 2, then the smaller caches would waste a bit of space, but it doesn't seem too bad. As far as when to rehash the bucket array, the fill factor would logically jump from 2 to 8. The worst-case list walk would be longer, but with a better overall memory access pattern, it might be fine.I think it would be straightforward to code this up -- the difficulty is testing and accounting for random effects due to binary layout changes. Thoughts?-- John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Wed, 4 Aug 2021 12:39:29 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": true, "msg_subject": "RFC: Improve CPU cache locality of syscache searches" }, { "msg_contents": "Hi,\n\nOn 2021-08-04 12:39:29 -0400, John Naylor wrote:\n> CPU caches have multiple levels, so I had an idea to use that concept in\n> the syscaches.\n\nI do think we loose a good bit to syscache efficiency in real workloads, so I\nthink it's worth investing time into it.\n\nHowever:\n\n> Imagine if catcache buckets were cacheline-sized. In that case, we would\n> store the most recently accessed hash values and pointers to catctup, in\n> addition to the dlist_head:\n>\n> typedef struct cc_bucket\n> {\n> uint32 hashes[4];\n> catctup *ct[4];\n> dlist_head;\n> };\n\nI'm not convinced that the above the right idea though. Even if the hash\nmatches, you're still going to need to fetch at least catctup->keys[0] from\na separate cacheline to be able to return the cache entry.\n\nIf the hashes we use are decent and we're resizing at reasonable thresholds,\nwe shouldn't constantly lookup up values that are later in a collision chain -\nparticularly because we move cache hits to the head of the bucket. So I don't\nthink a scheme as you described would actually result in a really better cache\nhit ratio?\n\nISTM that something like\n\nstruct cc_bucket_1\n{\n uint32 hashes[3]; // 12\n // 4 bytes alignment padding\n Datum key0s[3]; // 24\n catctup *ct[3]; // 24\n // cacheline boundary\n dlist_head conflicts; // 16\n};\n\nwould be better for 1 key values?\n\nIt's obviously annoying to need different bucket types for different key\ncounts, but given how much 3 unused key Datums waste, it seems worth paying\nfor?\n\nOne issue with stuff like this is that aset.c won't return cacheline aligned\nvalues...\n\n\nIt's possible that it'd be better to put the catctup pointers onto a\nneigboring cacheline (so you still get TLB benefits, as well as making it easy\nfor prefetchers) and increase the number of hashes/keys that fit on one\ncacheline.\n\nIf we stuffed four values into one bucket we could potentially SIMD the hash\nand Datum comparisons ;)\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 4 Aug 2021 12:44:44 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: RFC: Improve CPU cache locality of syscache searches" }, { "msg_contents": "On Wed, Aug 4, 2021 at 3:44 PM Andres Freund <andres@anarazel.de> wrote:\n> On 2021-08-04 12:39:29 -0400, John Naylor wrote:\n> > typedef struct cc_bucket\n> > {\n> > uint32 hashes[4];\n> > catctup *ct[4];\n> > dlist_head;\n> > };\n>\n> I'm not convinced that the above the right idea though. Even if the hash\n> matches, you're still going to need to fetch at least catctup->keys[0]\nfrom\n> a separate cacheline to be able to return the cache entry.\n\nI see your point. It doesn't make sense to inline only part of the\ninformation needed.\n\n> struct cc_bucket_1\n> {\n> uint32 hashes[3]; // 12\n> // 4 bytes alignment padding\n> Datum key0s[3]; // 24\n> catctup *ct[3]; // 24\n> // cacheline boundary\n> dlist_head conflicts; // 16\n> };\n>\n> would be better for 1 key values?\n>\n> It's obviously annoying to need different bucket types for different key\n> counts, but given how much 3 unused key Datums waste, it seems worth\npaying\n> for?\n\nYeah, it's annoying, but it does make a big difference to keep out unused\nDatums:\n\nkeys cachelines\n 3 values 4 values\n\n1 1 1/4 1 1/2\n2 1 5/8 2\n3 2 2 1/2\n4 2 3/8 3\n\nOr, looking at it another way, limiting the bucket size to 2 cachelines, we\ncan fit:\n\nkeys values\n1 5\n2 4\n3 3\n4 2\n\nAlthough I'm guessing inlining just two values in the 4-key case wouldn't\nbuy much.\n\n> If we stuffed four values into one bucket we could potentially SIMD the\nhash\n> and Datum comparisons ;)\n\n;-) That's an interesting future direction to consider when we support\nbuilding with x86-64-v2. It'd be pretty easy to compare a vector of hashes\nand quickly get the array index for the key comparisons (ignoring for the\nmoment how to handle the rare case of multiple identical hashes).\nHowever, we currently don't memcmp() the Datums and instead call an\n\"eqfast\" function, so I don't see how that part would work in a vector\nsetting.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Wed, Aug 4, 2021 at 3:44 PM Andres Freund <andres@anarazel.de> wrote:> On 2021-08-04 12:39:29 -0400, John Naylor wrote:> > typedef struct cc_bucket> > {> >   uint32 hashes[4];> >   catctup *ct[4];> >   dlist_head;> > };>> I'm not convinced that the above the right idea though. Even if the hash> matches, you're still going to need to fetch at least catctup->keys[0] from> a separate cacheline to be able to return the cache entry.I see your point. It doesn't make sense to inline only part of the information needed.> struct cc_bucket_1> {>     uint32 hashes[3]; // 12>     // 4 bytes alignment padding>     Datum key0s[3]; // 24>     catctup *ct[3]; // 24>     // cacheline boundary>     dlist_head conflicts; // 16> };>> would be better for 1 key values?>> It's obviously annoying to need different bucket types for different key> counts, but given how much 3 unused key Datums waste, it seems worth paying> for?Yeah, it's annoying, but it does make a big difference to keep out unused Datums:keys  cachelines      3 values  4 values1     1 1/4     1 1/22     1 5/8     23     2         2 1/24     2 3/8     3Or, looking at it another way, limiting the bucket size to 2 cachelines, we can fit:keys  values1     52     43     34     2Although I'm guessing inlining just two values in the 4-key case wouldn't buy much.> If we stuffed four values into one bucket we could potentially SIMD the hash> and Datum comparisons ;);-) That's an interesting future direction to consider when we support building with x86-64-v2. It'd be pretty easy to compare a vector of hashes and quickly get the array index for the key comparisons (ignoring for the moment how to handle the rare case of multiple identical hashes).  However, we currently don't memcmp() the Datums and instead call an \"eqfast\" function, so I don't see how that part  would work in a vector setting.--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Thu, 5 Aug 2021 12:27:49 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: RFC: Improve CPU cache locality of syscache searches" }, { "msg_contents": "Hi,\n\nOn 2021-08-05 12:27:49 -0400, John Naylor wrote:\n> On Wed, Aug 4, 2021 at 3:44 PM Andres Freund <andres@anarazel.de> wrote:\n> > On 2021-08-04 12:39:29 -0400, John Naylor wrote:\n> > > typedef struct cc_bucket\n> > > {\n> > > uint32 hashes[4];\n> > > catctup *ct[4];\n> > > dlist_head;\n> > > };\n> >\n> > I'm not convinced that the above the right idea though. Even if the hash\n> > matches, you're still going to need to fetch at least catctup->keys[0]\n> from\n> > a separate cacheline to be able to return the cache entry.\n> \n> I see your point. It doesn't make sense to inline only part of the\n> information needed.\n\nAt least not for the unconditionally needed information.\n\n\n> Although I'm guessing inlining just two values in the 4-key case wouldn't\n> buy much.\n\nNot so sure about that. I'd guess that two key comparisons take more cycles\nthan a cacheline fetch the further keys (perhaps not if we had inlined key\ncomparisons). I.e. I'd expect out-of-order + speculative execution to hide the\nlatency for fetching the second cacheline for later key values.\n\n\n> > If we stuffed four values into one bucket we could potentially SIMD the\n> hash\n> > and Datum comparisons ;)\n> \n> ;-) That's an interesting future direction to consider when we support\n> building with x86-64-v2. It'd be pretty easy to compare a vector of hashes\n> and quickly get the array index for the key comparisons (ignoring for the\n> moment how to handle the rare case of multiple identical hashes).\n> However, we currently don't memcmp() the Datums and instead call an\n> \"eqfast\" function, so I don't see how that part would work in a vector\n> setting.\n\nIt definitely couldn't work unconditionally - we have to deal with text,\noidvector, comparisons after all. But we could use it for the other\ntypes. However, looking at the syscaches, I think it'd not very often be\napplicable for caches with enough columns.\n\n\nI have wondered before whether we should have syscache definitions generate\ncode specific to each syscache definition. I do think that'd give a good bit\nof performance boost. But I don't see a trivial way to get there without\nnotational overhead.\n\nWe could define syscaches in a header using a macro that's defined differently\nin syscache.c than everywhere else. The header would declare a set of\nfunctions for each syscache, syscache.c would define them to call an\nalways_inline function with the relevant constants.\n\nOr perhaps we should move syscache definitions into the pg_*.h headers, and\ngenerate the relevant code as part of their processing. That seems like it\ncould be nice from a modularity POV alone. And it could do better than the\ncurrent approach, because we could hardcode the types for columns in the\nsyscache definition without increasing notational overhead.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 5 Aug 2021 13:12:01 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: RFC: Improve CPU cache locality of syscache searches" }, { "msg_contents": "Andres Freund писал 2021-08-05 23:12:\n> Hi,\n> \n> On 2021-08-05 12:27:49 -0400, John Naylor wrote:\n>> On Wed, Aug 4, 2021 at 3:44 PM Andres Freund <andres@anarazel.de> \n>> wrote:\n>> > On 2021-08-04 12:39:29 -0400, John Naylor wrote:\n>> > > typedef struct cc_bucket\n>> > > {\n>> > > uint32 hashes[4];\n>> > > catctup *ct[4];\n>> > > dlist_head;\n>> > > };\n>> >\n>> > I'm not convinced that the above the right idea though. Even if the hash\n>> > matches, you're still going to need to fetch at least catctup->keys[0]\n>> from\n>> > a separate cacheline to be able to return the cache entry.\n>> \n>> I see your point. It doesn't make sense to inline only part of the\n>> information needed.\n> \n> At least not for the unconditionally needed information.\n> \n> \n>> Although I'm guessing inlining just two values in the 4-key case \n>> wouldn't\n>> buy much.\n> \n> Not so sure about that. I'd guess that two key comparisons take more \n> cycles\n> than a cacheline fetch the further keys (perhaps not if we had inlined \n> key\n> comparisons). I.e. I'd expect out-of-order + speculative execution to \n> hide the\n> latency for fetching the second cacheline for later key values.\n> \n> \n>> > If we stuffed four values into one bucket we could potentially SIMD the\n>> hash\n>> > and Datum comparisons ;)\n>> \n>> ;-) That's an interesting future direction to consider when we support\n>> building with x86-64-v2. It'd be pretty easy to compare a vector of \n>> hashes\n>> and quickly get the array index for the key comparisons (ignoring for \n>> the\n>> moment how to handle the rare case of multiple identical hashes).\n>> However, we currently don't memcmp() the Datums and instead call an\n>> \"eqfast\" function, so I don't see how that part would work in a \n>> vector\n>> setting.\n> \n> It definitely couldn't work unconditionally - we have to deal with \n> text,\n> oidvector, comparisons after all. But we could use it for the other\n> types. However, looking at the syscaches, I think it'd not very often \n> be\n> applicable for caches with enough columns.\n> \n> \n> I have wondered before whether we should have syscache definitions \n> generate\n> code specific to each syscache definition. I do think that'd give a \n> good bit\n> of performance boost. But I don't see a trivial way to get there \n> without\n> notational overhead.\n> \n> We could define syscaches in a header using a macro that's defined \n> differently\n> in syscache.c than everywhere else. The header would declare a set of\n> functions for each syscache, syscache.c would define them to call an\n> always_inline function with the relevant constants.\n> \n> Or perhaps we should move syscache definitions into the pg_*.h headers, \n> and\n> generate the relevant code as part of their processing. That seems like \n> it\n> could be nice from a modularity POV alone. And it could do better than \n> the\n> current approach, because we could hardcode the types for columns in \n> the\n> syscache definition without increasing notational overhead.\n\nWhy don't use simplehash or something like that? Open-addressing schemes\nshow superior cache locality.\n\nIt could be combined: use hashValue as a key in simplehash and dlist for\nhashValue collision handling. 99.99% of time there will be no collisions\non hashValue itself, therefore it will be almost always two-three memory\nlookups: one-two for dlist_head in simple_hash by hashValue and then\nfetching first element in dlist.\n\nAnd code will remain almost same. Just \"bucket\" search will change a \nbit.\n\n(And I'd recommend use lower fill factor for this simplehash. At most \n0.85).\n\nWell, simplehash entry will be 24 bytes this way. If simplehash template\nsupports external key/element storage, then it could be shrunk to 16 \nbytes,\nand syscache entries will not need dlist_node. (But it doesn't at the\nmoment).\n\nAnd custom open-addressing table could be even with 8 bytes per element:\n- element is a pointer to entry,\n- missing node is encoded as NULL,\n- with fill factor as low as 0.66 there will be small amount of \ncollisions,\n therefore non-empty entry will be matched entry most of time, and \nmemory\n lookup for key comparison will be amortized free.\nNote that 8byte entry with fill factor 0.66 consumes amortized 12.12 \nbyte,\nwhile 16byte entry with fill factor 0.99 consumes amortized 16.16byte.\n\nregards,\nYura Sokolov\n\ny.sokolov@postgrespro.ru\nfunny.falcon@gmail.com\n\n\n", "msg_date": "Fri, 06 Aug 2021 06:43:55 +0300", "msg_from": "Yura Sokolov <y.sokolov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: RFC: Improve CPU cache locality of syscache searches" }, { "msg_contents": "Hi,\n\nOn 2021-08-06 06:43:55 +0300, Yura Sokolov wrote:\n> Why don't use simplehash or something like that? Open-addressing schemes\n> show superior cache locality.\n\nI thought about that as well - but it doesn't really resolve the question of\nwhat we want to store in-line in the hashtable and what not. We can't store\nthe tuples themselves in the hashtable for a myriad of reasons (need pointer\nstability, they're variably sized, way too large to move around frequently).\n\n\n> Well, simplehash entry will be 24 bytes this way. If simplehash template\n> supports external key/element storage, then it could be shrunk to 16 bytes,\n> and syscache entries will not need dlist_node. (But it doesn't at the\n> moment).\n\nI think storing keys outside of the hashtable entry defeats the purpose of the\nopen addressing, given that they are always checked and that our conflict\nratio should be fairly low.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 5 Aug 2021 20:49:45 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: RFC: Improve CPU cache locality of syscache searches" }, { "msg_contents": "Andres Freund писал 2021-08-06 06:49:\n> Hi,\n> \n> On 2021-08-06 06:43:55 +0300, Yura Sokolov wrote:\n>> Why don't use simplehash or something like that? Open-addressing \n>> schemes\n>> show superior cache locality.\n> \n> I thought about that as well - but it doesn't really resolve the \n> question of\n> what we want to store in-line in the hashtable and what not. We can't \n> store\n> the tuples themselves in the hashtable for a myriad of reasons (need \n> pointer\n> stability, they're variably sized, way too large to move around \n> frequently).\n> \n> \n>> Well, simplehash entry will be 24 bytes this way. If simplehash \n>> template\n>> supports external key/element storage, then it could be shrunk to 16 \n>> bytes,\n>> and syscache entries will not need dlist_node. (But it doesn't at the\n>> moment).\n> \n> I think storing keys outside of the hashtable entry defeats the purpose \n> of the\n> open addressing, given that they are always checked and that our \n> conflict\n> ratio should be fairly low.\n\nIt's opposite: if conflict ratio were high, then key outside of \nhashtable will\nbe expensive, since lookup to non-matched key will cost excess memory \naccess.\nBut with low conflict ratio we will usually hit matched entry at first \nprobe.\nAnd since we will use entry soon, it doesn't matter when it will go to \nCPU L1\ncache: during lookup or during actual usage.\n\nregards,\nYura Sokolov\n\n\n", "msg_date": "Fri, 06 Aug 2021 08:20:30 +0300", "msg_from": "Yura Sokolov <y.sokolov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: RFC: Improve CPU cache locality of syscache searches" }, { "msg_contents": "Hi,\n\nOn Thu, Aug 5, 2021, at 22:20, Yura Sokolov wrote:\n> Andres Freund писал 2021-08-06 06:49:\n> > Hi,\n> > \n> > On 2021-08-06 06:43:55 +0300, Yura Sokolov wrote:\n> >> Why don't use simplehash or something like that? Open-addressing \n> >> schemes\n> >> show superior cache locality.\n> > \n> > I thought about that as well - but it doesn't really resolve the \n> > question of\n> > what we want to store in-line in the hashtable and what not. We can't \n> > store\n> > the tuples themselves in the hashtable for a myriad of reasons (need \n> > pointer\n> > stability, they're variably sized, way too large to move around \n> > frequently).\n> > \n> > \n> >> Well, simplehash entry will be 24 bytes this way. If simplehash \n> >> template\n> >> supports external key/element storage, then it could be shrunk to 16 \n> >> bytes,\n> >> and syscache entries will not need dlist_node. (But it doesn't at the\n> >> moment).\n> > \n> > I think storing keys outside of the hashtable entry defeats the purpose \n> > of the\n> > open addressing, given that they are always checked and that our \n> > conflict\n> > ratio should be fairly low.\n> \n> It's opposite: if conflict ratio were high, then key outside of \n> hashtable will\n> be expensive, since lookup to non-matched key will cost excess memory \n> access.\n> But with low conflict ratio we will usually hit matched entry at first \n> probe.\n> And since we will use entry soon, it doesn't matter when it will go to \n> CPU L1\n> cache: during lookup or during actual usage.\n\nOften enough it does matter, because there will be earlier dependencies on whether a lookup is a cache hit/miss than on the content of the cached tuple.\n\nRegards,\n\nAndres\n\n\n", "msg_date": "Thu, 05 Aug 2021 23:11:53 -0700", "msg_from": "\"Andres Freund\" <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: RFC: Improve CPU cache locality of syscache searches" }, { "msg_contents": "On Thu, Aug 5, 2021 at 4:12 PM Andres Freund <andres@anarazel.de> wrote:\n> I have wondered before whether we should have syscache definitions\ngenerate\n> code specific to each syscache definition. I do think that'd give a good\nbit\n> of performance boost. But I don't see a trivial way to get there without\n> notational overhead.\n>\n> We could define syscaches in a header using a macro that's defined\ndifferently\n> in syscache.c than everywhere else. The header would declare a set of\n> functions for each syscache, syscache.c would define them to call an\n> always_inline function with the relevant constants.\n>\n> Or perhaps we should move syscache definitions into the pg_*.h headers,\nand\n> generate the relevant code as part of their processing. That seems like it\n> could be nice from a modularity POV alone. And it could do better than the\n> current approach, because we could hardcode the types for columns in the\n> syscache definition without increasing notational overhead.\n\nI had code laying around to generate the info needed for initialization,\nbut I apparently deleted it and never emailed it. :-(\n\nIf we went that far, I wonder if we could specialize the cc_bucket for the\nactual types, rather than just number of Datums, which would further save\non space. More complex, though.\n\nAlso, if comparisons got cheaper, maybe we could get away with not storing\nthe full hash in the bucket in favor of a tag of the 16 highest bits. (The\ncatctup would still need the full hash for invalidation, at least).\n\nAnother idea I came across while researching in-memory key-value stores is\n\"bulk chaining\" -- see [1] for an example. In that case, our example\n2-cacheline bucket would have a dlist_head pointing not to the catctups,\nbut to another bucket. So that throws away my L1/L2 analogy and uses a\nchain of buckets, each of which contain multiple sets of\nhashes/keys/pointers. That's closer to a normal collision chain, but with\nbetter cache locality. If we did that, I imagine the catctup could dispense\nwith storing its Datum array and its dlist_node entirely.\n\n[1]\nhttps://www.usenix.org/system/files/conference/nsdi14/nsdi14-paper-lim.pdf\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Thu, Aug 5, 2021 at 4:12 PM Andres Freund <andres@anarazel.de> wrote:> I have wondered before whether we should have syscache definitions generate> code specific to each syscache definition. I do think that'd give a good bit> of performance boost. But I don't see a trivial way to get there without> notational overhead.>> We could define syscaches in a header using a macro that's defined differently> in syscache.c than everywhere else. The header would declare a set of> functions for each syscache, syscache.c would define them to call an> always_inline function with the relevant constants.>> Or perhaps we should move syscache definitions into the pg_*.h headers, and> generate the relevant code as part of their processing. That seems like it> could be nice from a modularity POV alone. And it could do better than the> current approach, because we could hardcode the types for columns in the> syscache definition without increasing notational overhead.I had code laying around to generate the info needed for initialization, but I apparently deleted it and never emailed it. :-(If we went that far, I wonder if we could specialize the cc_bucket for the actual types, rather than just number of Datums, which would further save on space. More complex, though.Also, if comparisons got cheaper, maybe we could get away with not storing the full hash in the bucket in favor of a tag of the 16 highest bits. (The catctup would still need the full hash for invalidation, at least).Another idea I came across while researching in-memory key-value stores is \"bulk chaining\" -- see [1] for an example. In that case, our example 2-cacheline bucket would have a dlist_head pointing not to the catctups, but to another bucket. So that throws away my L1/L2 analogy and uses a chain of buckets, each of which contain multiple sets of hashes/keys/pointers. That's closer to a normal collision chain, but with better cache locality. If we did that, I imagine the catctup could dispense with storing its Datum array and its dlist_node entirely.[1] https://www.usenix.org/system/files/conference/nsdi14/nsdi14-paper-lim.pdf--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Fri, 6 Aug 2021 10:48:30 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: RFC: Improve CPU cache locality of syscache searches" }, { "msg_contents": "OK, here is a hackish WIP to see if we get anywhere with the L1 concept:\n\n0001 is extracted from a patch from Horiguchi-san to remove the \"dead\" flag\n0002 adds the large bucket, but doesn't use it for anything\n0003 uses the new bucket for the L1 cache\n0004 changes when to rehash\n0005 is Horiguchi-san's v7 benchmark\n0006 removes expiration stuff from the benchmark and prevents alloc errors\nwith my patches while running the benchmark\n\nThis doesn't align the bucket array to a cacheline boundary, nor does it\nchange the initial number of buckets\n\nmake -C contrib/catcachebench/ install\npsql -c 'create extension catcachebench'\n\n# This is also from Horiguchi-san\nperl gen_tbl.pl | psql > /dev/null\n\n# warmup\npsql -c 'select catcachebench(0)'\n\n# measure median of 3\n\nmaster:\n\npsql -c 'select catcachebench(1)'\n catcachebench\n---------------\n 6084.992169\n\npatch:\n\n./inst/bin/psql -c 'select catcachebench(1)'\n catcachebench\n---------------\n 5508.072532\n\nThat's decent, but not exactly stellar. I get a huge slowdown in\ncatcachebench(2), however, so I'll have to dig into why before going any\nfurther.\n\nSome time I'll also try the function specialization Andres mentioned and\nsee how big of a speedup that gives.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com", "msg_date": "Wed, 18 Aug 2021 14:19:21 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: RFC: Improve CPU cache locality of syscache searches" }, { "msg_contents": "On Thu, Aug 5, 2021 at 4:12 PM Andres Freund <andres@anarazel.de> wrote:\n> I have wondered before whether we should have syscache definitions\ngenerate\n> code specific to each syscache definition. I do think that'd give a good\nbit\n> of performance boost. But I don't see a trivial way to get there without\n> notational overhead.\n\nI've made a small step in this direction in the attached. It uses a\ntemplate approach to generate type-specific SearchCatCache* functions, for\nnow only the 4-key ones. Since there's only a few of those, it's manageable\nto invoke the template and change the call sites by hand. To get this to\nscale up to all syscaches would require some scripting, but this much is\nenough to get feedback on the approach. One possible concern in starting\ndown this path is that hundreds of call sites would have to be changed. (If\nthere's a good way around that, it hasn't occurred to me.) It might also be\npossible to replace the per-key invocations with a single memcpy() for most\ntypes, but that's a bit more work.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com", "msg_date": "Thu, 19 Aug 2021 19:10:37 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: RFC: Improve CPU cache locality of syscache searches" }, { "msg_contents": "Hi,\n\nOn 2021-08-19 19:10:37 -0400, John Naylor wrote:\n> I've made a small step in this direction in the attached. It uses a\n> template approach to generate type-specific SearchCatCache* functions, for\n> now only the 4-key ones. Since there's only a few of those, it's manageable\n> to invoke the template and change the call sites by hand. To get this to\n> scale up to all syscaches would require some scripting, but this much is\n> enough to get feedback on the approach. One possible concern in starting\n> down this path is that hundreds of call sites would have to be changed. (If\n> there's a good way around that, it hasn't occurred to me.)\n\nI was thinking of avoiding the need for that via a macro. I.e. have\nSearchSysCache4(AMOPSTRATEGY, ...) be mapped to\nSearchSysCache4AMOPSTRATEGY(...). That way callers wouldn't need to care, and\nwe could continue to evolve the internals without continually doing\nlarge-scale code changes?\n\n\n> diff --git a/src/include/utils/catcache_search_template.h b/src/include/utils/catcache_search_template.h\n> new file mode 100644\n> index 0000000000..6f5dc2573c\n> --- /dev/null\n> +++ b/src/include/utils/catcache_search_template.h\n> @@ -0,0 +1,176 @@\n> +/*-------------------------------------------------------------------------\n> + * catcache_search_template.h\n> + *\n> + * A template for type-specialized SearchCatCache functions\n> + *\n> + * Usage notes:\n> + *\n> + * To generate functions specialized for a set of catcache keys,\n> + * the following parameter macros should be #define'd before this\n> + * file is included.\n> + *\n> + * - CC_SEARCH - the name of the search function to be generated\n> + * - CC_NKEYS - the number of search keys for the tuple\n> + * - FASTEQFUNCx (x in 1,2,3,4) - type-specific equality function(s)\n> + * - HASHFUNCx (x in 1,2,3,4) - type-specific hash function(s)\n\nIt's not clear to me we need such a complicated interface here. Can't we just\nhave a pg_attribute_always_inline function with a bunch more parameters?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 27 Aug 2021 12:42:04 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: RFC: Improve CPU cache locality of syscache searches" }, { "msg_contents": "On Fri, Aug 27, 2021 at 3:42 PM Andres Freund <andres@anarazel.de> wrote:\n>\n> Hi,\n>\n> On 2021-08-19 19:10:37 -0400, John Naylor wrote:\n> > I've made a small step in this direction in the attached. It uses a\n> > template approach to generate type-specific SearchCatCache* functions,\nfor\n> > now only the 4-key ones. Since there's only a few of those, it's\nmanageable\n> > to invoke the template and change the call sites by hand. To get this to\n> > scale up to all syscaches would require some scripting, but this much is\n> > enough to get feedback on the approach. One possible concern in starting\n> > down this path is that hundreds of call sites would have to be changed.\n(If\n> > there's a good way around that, it hasn't occurred to me.)\n>\n> I was thinking of avoiding the need for that via a macro. I.e. have\n> SearchSysCache4(AMOPSTRATEGY, ...) be mapped to\n> SearchSysCache4AMOPSTRATEGY(...). That way callers wouldn't need to care,\nand\n> we could continue to evolve the internals without continually doing\n> large-scale code changes?\n\nMakes sense.\n\n> > + * To generate functions specialized for a set of catcache keys,\n> > + * the following parameter macros should be #define'd before this\n> > + * file is included.\n> > + *\n> > + * - CC_SEARCH - the name of the search function to be generated\n> > + * - CC_NKEYS - the number of search keys for the tuple\n> > + * - FASTEQFUNCx (x in 1,2,3,4) - type-specific equality function(s)\n> > + * - HASHFUNCx (x in 1,2,3,4) - type-specific hash function(s)\n>\n> It's not clear to me we need such a complicated interface here. Can't we\njust\n> have a pg_attribute_always_inline function with a bunch more parameters?\n\nWere you thinking in terms of passing the type oid in parameters, like this?\n\nHeapTuple\nSearchCatCache1(CatCache *cache, Datum v1, Oid t1)\n{\n return SearchCatCacheInternal(cache, 1, v1, t1, 0, 0, 0, 0, 0, 0);\n}\n\nAnd then CatalogCacheComputeHashValue() and CatalogCacheCompareTuple()\nwould likewise take types as parameters, which they could use to pick the\nright functions at compile time?\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Fri, Aug 27, 2021 at 3:42 PM Andres Freund <andres@anarazel.de> wrote:>> Hi,>> On 2021-08-19 19:10:37 -0400, John Naylor wrote:> > I've made a small step in this direction in the attached. It uses a> > template approach to generate type-specific SearchCatCache* functions, for> > now only the 4-key ones. Since there's only a few of those, it's manageable> > to invoke the template and change the call sites by hand. To get this to> > scale up to all syscaches would require some scripting, but this much is> > enough to get feedback on the approach. One possible concern in starting> > down this path is that hundreds of call sites would have to be changed. (If> > there's a good way around that, it hasn't occurred to me.)>> I was thinking of avoiding the need for that via a macro. I.e. have> SearchSysCache4(AMOPSTRATEGY, ...) be mapped to> SearchSysCache4AMOPSTRATEGY(...). That way callers wouldn't need to care, and> we could continue to evolve the internals without continually doing> large-scale code changes?Makes sense.> > + * To generate functions specialized for a set of catcache keys,> > + * the following parameter macros should be #define'd before this> > + * file is included.> > + *> > + * - CC_SEARCH - the name of the search function to be generated> > + * - CC_NKEYS - the number of search keys for the tuple> > + * - FASTEQFUNCx (x in 1,2,3,4) - type-specific equality function(s)> > + * - HASHFUNCx (x in 1,2,3,4) - type-specific hash function(s)>> It's not clear to me we need such a complicated interface here. Can't we just> have a pg_attribute_always_inline function with a bunch more parameters?Were you thinking in terms of passing the type oid in parameters, like this?HeapTupleSearchCatCache1(CatCache *cache, Datum v1, Oid t1){  return SearchCatCacheInternal(cache, 1, v1, t1, 0, 0, 0, 0, 0, 0);}And then CatalogCacheComputeHashValue() and CatalogCacheCompareTuple() would likewise take types as parameters, which they could use to pick the right functions at compile time?--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Tue, 31 Aug 2021 15:06:32 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: RFC: Improve CPU cache locality of syscache searches" }, { "msg_contents": "Hi,\n\nOn 2021-08-31 15:06:32 -0400, John Naylor wrote:\n> Were you thinking in terms of passing the type oid in parameters, like this?\n> \n> HeapTuple\n> SearchCatCache1(CatCache *cache, Datum v1, Oid t1)\n> {\n> return SearchCatCacheInternal(cache, 1, v1, t1, 0, 0, 0, 0, 0, 0);\n> }\n> \n> And then CatalogCacheComputeHashValue() and CatalogCacheCompareTuple()\n> would likewise take types as parameters, which they could use to pick the\n> right functions at compile time?\n\nI was thinking that the script could emit something like\n\nstatic const cachedesc syscachedesc_AGGFNOID = {\n .reloid = AggregateRelationId,\n .indoid = AggregateFnoidIndexId,\n .nkeys = 1,\n .keys = {\n {\n .varno = Anum_pg_aggregate_aggfnoid,\n .type = Oid,\n .comparator = ...\n }\n }\n};\n\nstatic CatCache syscache_AGGFNOID;\n\nHeapTuple\nSearchSysCacheAGGFNOID(Datum key1)\n{\n return SearchSysCacheInternal(&syscachedesc_AGGFNOID, syscache_AGGFNOID, key1);\n}\n\nand SearchSysCacheInternal would have a pg_attribute_always_inline()\nfastpath. That fastpath would basically be SearchCatCacheInternal(), with an\nextra const cachedesc * paramter. Then the compiler should be able to generate\ndirect function calls to the hash functions in CatalogCacheComputeHashValue()\nand direct calls to the equal function in CatalogCacheCompareTuple().\n\n\nOne difficulty would be that I don't see how to make this work with syscache.c\nbeing compiled separately from catcache.c - but there's probably no need\nto. The script could generate a syscache_impl.h that catcache.c includes.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 31 Aug 2021 13:59:06 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: RFC: Improve CPU cache locality of syscache searches" } ]
[ { "msg_contents": "Hackers,\n\nYou can easily get a cache lookup failure by changing the regression tests as included in this small patch. The failure looks thus:\n\n+COMMENT ON STATISTICS ab1_a_b_stats IS 'new comment';\n+CREATE ROLE temp_role;\n+SET SESSION AUTHORIZATION temp_role;\n+COMMENT ON STATISTICS ab1_a_b_stats IS 'changed comment';\n+ERROR: cache lookup failed for type 27447\n+DROP STATISTICS ab1_a_b_stats;\n+ERROR: cache lookup failed for type 27447\n+ALTER STATISTICS ab1_a_b_stats RENAME TO ab1_a_b_stats_new;\n+ERROR: must be owner of statistics object ab1_a_b_stats\n+RESET SESSION AUTHORIZATION;\n+DROP ROLE temp_role;\n\nI believe this case simply has not had any test coverage, as I don't see any way the current code would ever work. It treats the Oid of the statistics object as a type, which it is not.\n\n\n\n\n\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Wed, 4 Aug 2021 15:03:57 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Bug fix for cache lookup failure for statistic_ext type" }, { "msg_contents": "On 8/5/21 12:03 AM, Mark Dilger wrote:\n> Hackers,\n> \n> You can easily get a cache lookup failure by changing the regression tests as included in this small patch. The failure looks thus:\n> \n> +COMMENT ON STATISTICS ab1_a_b_stats IS 'new comment';\n> +CREATE ROLE temp_role;\n> +SET SESSION AUTHORIZATION temp_role;\n> +COMMENT ON STATISTICS ab1_a_b_stats IS 'changed comment';\n> +ERROR: cache lookup failed for type 27447\n> +DROP STATISTICS ab1_a_b_stats;\n> +ERROR: cache lookup failed for type 27447\n> +ALTER STATISTICS ab1_a_b_stats RENAME TO ab1_a_b_stats_new;\n> +ERROR: must be owner of statistics object ab1_a_b_stats\n> +RESET SESSION AUTHORIZATION;\n> +DROP ROLE temp_role;\n> \n> I believe this case simply has not had any test coverage, as I don't\n> see any way the current code would ever work. It treats the Oid of the\n> statistics object as a type, which it is not.\n> \n\nYeah, you're right - this is broken since 7b504eb282c. Thanks for the \nfix, I'll get it committed.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 5 Aug 2021 00:32:33 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Bug fix for cache lookup failure for statistic_ext type" }, { "msg_contents": "\n\nOn 8/5/21 12:32 AM, Tomas Vondra wrote:\n> On 8/5/21 12:03 AM, Mark Dilger wrote:\n>> Hackers,\n>>\n>> You can easily get a cache lookup failure by changing the regression \n>> tests as included in this small patch.� The failure looks thus:\n>>\n>> +COMMENT ON STATISTICS ab1_a_b_stats IS 'new comment';\n>> +CREATE ROLE temp_role;\n>> +SET SESSION AUTHORIZATION temp_role;\n>> +COMMENT ON STATISTICS ab1_a_b_stats IS 'changed comment';\n>> +ERROR:� cache lookup failed for type 27447\n>> +DROP STATISTICS ab1_a_b_stats;\n>> +ERROR:� cache lookup failed for type 27447\n>> +ALTER STATISTICS ab1_a_b_stats RENAME TO ab1_a_b_stats_new;\n>> +ERROR:� must be owner of statistics object ab1_a_b_stats\n>> +RESET SESSION AUTHORIZATION;\n>> +DROP ROLE temp_role;\n>>\n>> I believe this case simply has not had any test coverage, as I don't\n>> see any way the current code would ever work.� It treats the Oid of the\n>> statistics object as a type, which it is not.\n>>\n> \n> Yeah, you're right - this is broken since 7b504eb282c. Thanks for the \n> fix, I'll get it committed.\n> \n\nI've pushed a fix for this. And then a fix for the fix :-( because I \nforgot about the rule that role names in regression tests should start \nwith regress_ prefix, so animals enforcing this failed.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 31 Aug 2021 19:50:58 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Bug fix for cache lookup failure for statistic_ext type" }, { "msg_contents": "\n\n> On Aug 31, 2021, at 10:50 AM, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\n> \n> I've pushed a fix for this. And then a fix for the fix :-( because I forgot about the rule that role names in regression tests should start with regress_ prefix, so animals enforcing this failed.\n\nThanks!\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Tue, 31 Aug 2021 11:53:32 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Bug fix for cache lookup failure for statistic_ext type" } ]
[ { "msg_contents": "Here's a little finger exercise that improves a case that's bothered me\nfor awhile. In a POSIX regexp, parentheses cause capturing by default;\nyou have to write the very non-obvious \"(?:...)\" if you don't want the\nmatching substring to be reported by the regexp engine. That'd be fine\nif capturing were cheap, but with our engine it is not particularly\ncheap. In many situations, the initial DFA check is sufficient to\ntell whether there is an overall match, but it does not tell where any\nsubexpression match boundaries are. To identify exactly which substring\nis deemed to match a parenthesized subexpression, we have to recursively\nbreak down the match, which takes at the very least a few more DFA\ninvocations; and with an uncooperative regex, it can easily result in\nO(N^2) behavior where there was none at the DFA stage.\n\nTherefore, we really ought to expend some effort to not capture\nsubexpressions if the sub-match data is not actually needed, which in\nmany invocations we know that it isn't. Spencer's original code has\na REG_NOSUB option that looks like it ought to be good for this ... but\non closer inspection it's basically useless, because it turns *all*\nparens into non-capturing ones. That breaks back-references, so unless\nyou know that the regexp contains no back-refs, you can't use it.\n\nThe attached proposed patch redefines REG_NOSUB as being a regexp-\ncompile-time promise that the caller doesn't care about sub-match\nlocations, but not a promise that no backrefs exist. (If the\ncaller passes a match-locations array at execution anyway, it will\njust get back -1 values, as if no sub-match had been identified.)\nIf that flag is passed, we run through the completed sub-regexp\ntree and remove the \"capture\" markers on any subREs that are\nnot actually referenced by some backref. This typically causes\nsome parent subREs to no longer be deemed \"messy\", so that their\nseparate child subREs can be thrown away entirely, saving memory\nspace as well as runtime.\n\n(I'd originally thought that a much more complex patch would be\nneeded to do this, because I assumed that re-optimizing the subRE\ntree would be much more complicated than this. However, as far\nas I can see this is sufficient; this change doesn't expose any\ncases where additional tree restructuring would be helpful.)\n\nTesting with Joel's handy little corpus of web regexps, there's a\nuseful improvement of the speed of ~ operators (a/k/a regexp_like()).\nI see the total time to apply regexp_like() to all 4474520 entries\ndropping from 10:17 to 5:46. Interesting statistics include\n\nregexp=# select max(duration),avg(duration) from headresults;\n max | avg \n-----------------+-----------------\n 00:00:00.939389 | 00:00:00.000138\n(1 row)\n\nregexp=# select max(duration),avg(duration) from patchresults; \n max | avg \n-----------------+-----------------\n 00:00:00.918549 | 00:00:00.000077\n(1 row)\n\nThe lower percentiles don't move much, but upper ones do:\n\nregexp=# select percentile_cont(array[0.5,0.75,0.8,0.9]) within group(order by duration) from headresults;\n percentile_cont \n-------------------------------------------------------------------\n {00:00:00.000027,00:00:00.000059,00:00:00.000067,00:00:00.000108}\n(1 row)\n\nregexp=# select percentile_cont(array[0.5,0.75,0.8,0.9]) within group(order by duration) from patchresults;\n percentile_cont \n-------------------------------------------------------------------\n {00:00:00.000025,00:00:00.000042,00:00:00.000048,00:00:00.000065}\n(1 row)\n\nThis isn't terribly surprising, because regexps that were already\nreally cheap probably have no capturing parens to dispense with.\n\nOf course, there's no benefit with functions that do need sub-match\ndata, such as regexp_match. But the added overhead in such cases\nshould be quite negligible. The only downside I can see is that\nif you use the \"same\" regexp in both submatches-needed and\nnon-submatches-needed contexts, you'll end up with two separate\ncompiled regexp cache entries. That doesn't seem like a big\nproblem though.\n\n\t\t\tregards, tom lane", "msg_date": "Wed, 04 Aug 2021 18:15:34 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Another regexp performance improvement: skip useless paren-captures" }, { "msg_contents": "\nOn 8/4/21 6:15 PM, Tom Lane wrote:\n> Here's a little finger exercise that improves a case that's bothered me\n> for awhile. In a POSIX regexp, parentheses cause capturing by default;\n> you have to write the very non-obvious \"(?:...)\" if you don't want the\n> matching substring to be reported by the regexp engine. \n\n\nIt's not obscure to perl programmers :-)\n\n\n> That'd be fine\n> if capturing were cheap, but with our engine it is not particularly\n> cheap. In many situations, the initial DFA check is sufficient to\n> tell whether there is an overall match, but it does not tell where any\n> subexpression match boundaries are. To identify exactly which substring\n> is deemed to match a parenthesized subexpression, we have to recursively\n> break down the match, which takes at the very least a few more DFA\n> invocations; and with an uncooperative regex, it can easily result in\n> O(N^2) behavior where there was none at the DFA stage.\n>\n> Therefore, we really ought to expend some effort to not capture\n> subexpressions if the sub-match data is not actually needed, which in\n> many invocations we know that it isn't. Spencer's original code has\n> a REG_NOSUB option that looks like it ought to be good for this ... but\n> on closer inspection it's basically useless, because it turns *all*\n> parens into non-capturing ones. That breaks back-references, so unless\n> you know that the regexp contains no back-refs, you can't use it.\n\n\nIn perl you can use the 'n' modifier for this effect (since 5.22)\n\n\nI would expect to know if a back-ref were present.\n\n\nI'm a bit worried about how you'll keep track of back-ref numbering\nsince back-refs only count capturing groups, and you're silently turning\na capturing group into a non-capturing group.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Thu, 5 Aug 2021 09:42:47 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "Andrew Dunstan <andrew@dunslane.net> writes:\n> I'm a bit worried about how you'll keep track of back-ref numbering\n> since back-refs only count capturing groups, and you're silently turning\n> a capturing group into a non-capturing group.\n\nThey're already numbered at this point, and we aren't changing the numbers\nof the capturing groups that remain live. There will be unused entries in\nthe regmatch_t array at runtime (corresponding to the zapped groups), but\nthat doesn't cost anything worth mentioning.\n\nNow that you mention it, I am not sure whether there are any regression\ntest cases that specifically cover still being able to match \\2 when\nthe first capture group went away. Probably should add more cases...\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 05 Aug 2021 10:36:21 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "On Thu, Aug 5, 2021 at 9:43 AM Andrew Dunstan <andrew@dunslane.net> wrote:\n> On 8/4/21 6:15 PM, Tom Lane wrote:\n> > Here's a little finger exercise that improves a case that's bothered me\n> > for awhile. In a POSIX regexp, parentheses cause capturing by default;\n> > you have to write the very non-obvious \"(?:...)\" if you don't want the\n> > matching substring to be reported by the regexp engine.\n> It's not obscure to perl programmers :-)\n\nWell, I consider myself a pretty fair perl programmer, and I know\nthere's a way to do that, but I never do it, and I would have had to\nlook up the exact syntax. So +1 from me for anything automatic that\navoids paying the overhead in some cases.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 5 Aug 2021 10:39:21 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> Well, I consider myself a pretty fair perl programmer, and I know\n> there's a way to do that, but I never do it, and I would have had to\n> look up the exact syntax. So +1 from me for anything automatic that\n> avoids paying the overhead in some cases.\n\nThat's my feeling about it too --- I never really think of this\npoint when writing a regexp. It seems like something the engine\nought to handle gracefully, so this patch is an attempt to do so.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 05 Aug 2021 11:01:29 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "\nOn 8/5/21 10:39 AM, Robert Haas wrote:\n> On Thu, Aug 5, 2021 at 9:43 AM Andrew Dunstan <andrew@dunslane.net> wrote:\n>> On 8/4/21 6:15 PM, Tom Lane wrote:\n>>> Here's a little finger exercise that improves a case that's bothered me\n>>> for awhile. In a POSIX regexp, parentheses cause capturing by default;\n>>> you have to write the very non-obvious \"(?:...)\" if you don't want the\n>>> matching substring to be reported by the regexp engine.\n>> It's not obscure to perl programmers :-)\n> Well, I consider myself a pretty fair perl programmer, \n\n\nI also consider you one :-)\n\n\nPerhaps I should have said \"many perl programmers\".\n\n\n> and I know\n> there's a way to do that, but I never do it, and I would have had to\n> look up the exact syntax. So +1 from me for anything automatic that\n> avoids paying the overhead in some cases.\n\n\nYeah, I'm not arguing against the idea. I also have to look it up,\nmainly because there is such a huge amount of stuff that can follow\n\"(?\", do \"perldoc perlre\" happens a lot when I'm doing that sort of work.\n\n\ncheers\n\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Thu, 5 Aug 2021 11:41:38 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "\n\n> On Aug 5, 2021, at 7:36 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Probably should add more cases...\n\nThe patch triggers an assertion that master does not:\n\n+select 'azrlfkjbjgidgryryiglcabkgqluflu' !~ '(.(.)((.)))((?:(\\3)))';\n+server closed the connection unexpectedly\n+ This probably means the server terminated abnormally\n+ before or while processing the request.\n+connection to server was lost\n\nThe relevant portion of the stack trace:\n\n frame #3: 0x00000001043bcf6d postgres`ExceptionalCondition(conditionName=<unavailable>, errorType=<unavailable>, fileName=<unavailable>, lineNumber=<unavailable>) at assert.c:69:2 [opt]\n frame #4: 0x000000010410168b postgres`cdissect(v=0x00007ffeebdd2ad8, t=0x00007f863cd055b0, begin=0x00007f863d821528, end=0x00007f863d82152c) at regexec.c:767:4 [opt]\n frame #5: 0x000000010410129b postgres`cdissect [inlined] ccondissect(v=<unavailable>, t=<unavailable>, begin=0x00007f863d821524, end=<unavailable>) at regexec.c:835:10 [opt]\n frame #6: 0x000000010410123d postgres`cdissect(v=0x00007ffeebdd2ad8, t=0x00007f863cd05430, begin=0x00007f863d821524, end=0x00007f863d82152c) at regexec.c:752 [opt]\n frame #7: 0x000000010410129b postgres`cdissect [inlined] ccondissect(v=<unavailable>, t=<unavailable>, begin=0x00007f863d821520, end=<unavailable>) at regexec.c:835:10 [opt]\n frame #8: 0x000000010410123d postgres`cdissect(v=0x00007ffeebdd2ad8, t=0x00007f863cd050f0, begin=0x00007f863d821520, end=0x00007f863d82152c) at regexec.c:752 [opt]\n frame #9: 0x0000000104101282 postgres`cdissect [inlined] ccondissect(v=<unavailable>, t=<unavailable>, begin=0x00007f863d821520, end=<unavailable>) at regexec.c:832:9 [opt]\n frame #10: 0x000000010410123d postgres`cdissect(v=0x00007ffeebdd2ad8, t=0x00007f863cd04ff0, begin=0x00007f863d821520, end=0x00007f863d821530) at regexec.c:752 [opt]\n frame #11: 0x00000001040ff508 postgres`pg_regexec [inlined] cfindloop(v=<unavailable>, cnfa=<unavailable>, cm=<unavailable>, d=0x00007ffeebdd6d68, s=0x00007ffeebdd2b48, coldp=<unavailable>) at regexec.c:600:10 [opt]\n frame #12: 0x00000001040ff36b postgres`pg_regexec [inlined] cfind(v=0x000000010459c5f8, cnfa=<unavailable>, cm=<unavailable>) at regexec.c:515 [opt]\n frame #13: 0x00000001040ff315 postgres`pg_regexec(re=<unavailable>, string=<unavailable>, len=140732855577960, search_start=<unavailable>, details=<unavailable>, nmatch=0, pmatch=0x0000000000000000, flags=0) at regexec.c:293 [opt]\n frame #14: 0x0000000104244d61 postgres`RE_wchar_execute(re=<unavailable>, data=<unavailable>, data_len=<unavailable>, start_search=<unavailable>, nmatch=<unavailable>, pmatch=<unavailable>) at regexp.c:274:19 [opt]\n frame #15: 0x0000000104242c80 postgres`textregexne [inlined] RE_execute(dat=<unavailable>, dat_len=31, nmatch=0, pmatch=0x0000000000000000) at regexp.c:322:10 [opt]\n frame #16: 0x0000000104242c50 postgres`textregexne [inlined] RE_compile_and_execute(text_re=<unavailable>, dat=<unavailable>, dat_len=31, cflags=19, collation=<unavailable>, nmatch=0, pmatch=<unavailable>) at regexp.c:357 [opt]\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Thu, 5 Aug 2021 14:37:21 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> The patch triggers an assertion that master does not:\n\n> +select 'azrlfkjbjgidgryryiglcabkgqluflu' !~ '(.(.)((.)))((?:(\\3)))';\n\nOn looking into this, it's pretty simple: regexec.c has an assertion\nthat a pure-capture subre node ought to be doing some capturing.\n\n case '(': /* no-op capture node */\n assert(t->child != NULL);\n assert(t->capno > 0);\n\nThat's fine as of HEAD, but with the proposed patch, we may notice\nthat the node isn't actually referenced by any backref, and remove\nits capture marker, allowing this assertion to fire. Nothing's\nreally wrong though.\n\nThere seem to be three things we could do about that:\n\n1. Extend removecaptures() so that it can actually remove no-op\ncapture nodes if it's removed their capture markings. This would\nsubstantially complicate that function, and I judge that it's not\nworth the trouble. We'll only have such nodes in cases of\ncapturing parentheses immediately surrounding capturing parentheses,\nwhich doesn't seem like a case worth expending sweat for.\n\n2. Just drop the \"t->capno > 0\" assertion in regexec.c.\n\n3. Weaken said assertion, perhaps by also checking the BRUSE flag bit.\n\nNot sure that I see any point to #3, so I just dropped the\nassertion in the attached.\n\nI've also rebased over the bug fixes from the other thread,\nand added a couple more test cases.\n\n\t\t\tregards, tom lane", "msg_date": "Sun, 08 Aug 2021 13:04:38 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "\n\n> On Aug 8, 2021, at 10:04 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> I've also rebased over the bug fixes from the other thread,\n> and added a couple more test cases.\n> \n> \t\t\tregards, tom lane\n\nHmm. This changes the behavior when applied against master (c1132aae336c41cf9d316222e525d8d593c2b5d2):\n\n select regexp_split_to_array('uuuzkodphfbfbfb', '((.))(\\1\\2)', 'ntw');\n regexp_split_to_array\n -----------------------\n- {\"\",zkodphfbfbfb}\n+ {uuuzkodphfbfbfb}\n (1 row)\n\nThe string starts with three \"u\" characters. The first of them is doubly-matched, meaning \\1 and \\2 refer to the first \"u\" character. The (\\1\\2) that follows matches the next two \"u\" characters. When the extra \"useless\" capture group is skipped, apparently this doesn't work anymore. I haven't looked at your patch, so I'm not sure why, but I'm guessing that \\2 doesn't refer to anything.\n\nThat analysis is consistent with the next change:\n\n select regexp_split_to_array('snfwbvxeesnzqabixqbixqiumpgxdemmxvnsemjxgqoqknrqessmcqmfslfspskqpqxe', '((((?:.))))\\3');\n- regexp_split_to_array \n----------------------------------------------------------------------\n- {snfwbvx,snzqabixqbixqiumpgxde,xvnsemjxgqoqknrqe,mcqmfslfspskqpqxe}\n+ regexp_split_to_array \n+------------------------------------------------------------------------\n+ {snfwbvxeesnzqabixqbixqiumpgxdemmxvnsemjxgqoqknrqessmcqmfslfspskqpqxe}\n (1 row)\n\nThe pattern matches any double character. I would expect it to match the \"ee\", the \"mm\" and the \"ss\" in the text. With the patched code, it matches nothing.\n\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Sun, 8 Aug 2021 11:22:24 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> Hmm. This changes the behavior when applied against master (c1132aae336c41cf9d316222e525d8d593c2b5d2):\n\n> select regexp_split_to_array('uuuzkodphfbfbfb', '((.))(\\1\\2)', 'ntw');\n> regexp_split_to_array\n> -----------------------\n> - {\"\",zkodphfbfbfb}\n> + {uuuzkodphfbfbfb}\n> (1 row)\n\nUgh. The regex engine is finding the match correctly, but it's failing to\ntell the caller where it is :-(. I was a little too cute in optimizing\nthe regmatch_t result-vector copying in pg_regexec, and forgot to ensure\nthat the overall match position would be reported.\n\nThanks for the testing!\n\n\t\t\tregards, tom lane", "msg_date": "Sun, 08 Aug 2021 16:25:00 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "\n\n> On Aug 8, 2021, at 1:25 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Ugh. The regex engine is finding the match correctly, but it's failing to\n> tell the caller where it is :-(. I was a little too cute in optimizing\n> the regmatch_t result-vector copying in pg_regexec, and forgot to ensure\n> that the overall match position would be reported.\n> \n> Thanks for the testing!\n\nSure! Thanks for improving the regular expression engine!\n\nI have applied your latest patch and do not see any problems with it. All my tests pass with no asserts and with no differences in results vs. master. This is a test suite of nearly 1.5 million separate regular expressions.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Sun, 8 Aug 2021 13:39:46 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> I have applied your latest patch and do not see any problems with it. All my tests pass with no asserts and with no differences in results vs. master. This is a test suite of nearly 1.5 million separate regular expressions.\n\nCool, thanks. I also tried your millions-of-random-regexps script\nand didn't find any difference between the results from HEAD and\nthose from the v3 patch.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 08 Aug 2021 18:28:13 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "\n\n> On Aug 8, 2021, at 3:28 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Cool, thanks. I also tried your millions-of-random-regexps script\n> and didn't find any difference between the results from HEAD and\n> those from the v3 patch.\n\nThe patch looks ready to commit. I don't expect to test it any further unless you have something in particular you'd like me to focus on.\n\nThanks again for working on this.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Sun, 8 Aug 2021 15:33:06 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> The patch looks ready to commit. I don't expect to test it any further unless you have something in particular you'd like me to focus on.\n\nPushed, but while re-reading it before commit I noticed that there's\nsome more fairly low-hanging fruit in regexp_replace(). As I had it\nin that patch, it never used REG_NOSUB because of the possibility\nthat the replacement string uses \"\\N\". However, we're already\npre-checking the replacement string to see if it has backslashes\nat all, so while we're at it we can check for \\N to discover if we\nactually need any subexpression match data or not. We do need to\nrefactor a little to postpone calling pg_regcomp until after we\nknow that, but I think that makes replace_text_regexp's API less\nugly not more so.\n\nWhile I was at it, I changed the search-for-backslash loops to\nuse memchr rather than handwritten looping. Their use of\npg_mblen was pretty unnecessary given we only need to find\nbackslashes, and we can assume the backend encoding is ASCII-safe.\n\nUsing a bunch of random cases generated by your little perl\nscript, I see maybe 10-15% speedup on test cases that don't\nuse \\N in the replacement string, while it's about a wash\non cases that do. (If I'd been using a multibyte encoding,\nmaybe the memchr change would have made a difference, but\nI didn't try that.)\n\n\t\t\tregards, tom lane", "msg_date": "Mon, 09 Aug 2021 15:14:45 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "Tom,\n\nI can still trigger the old bug for which we thought we'd pushed a fix. The test case below crashes on master (e12694523e7e4482a052236f12d3d8b58be9a22c), and also on the fixed version \"Make regexp engine's backref-related compilation state more bulletproof.\" (cb76fbd7ec87e44b3c53165d68dc2747f7e26a9a).\n\nCan you test if it crashes for you, too? I'm not sure I see why this one fails when millions of others pass.\n\nThe backtrace is still complaining about regc_nfa.c:1265:\n\n+select regexp_split_to_array('', '(?:((?:q+))){0}(\\1){0,0}?*[^]');\n+server closed the connection unexpectedly\n+ This probably means the server terminated abnormally\n+ before or while processing the request.\n+connection to server was lost\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Mon, 9 Aug 2021 14:01:13 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> I can still trigger the old bug for which we thought we'd pushed a fix. The test case below crashes on master (e12694523e7e4482a052236f12d3d8b58be9a22c), and also on the fixed version \"Make regexp engine's backref-related compilation state more bulletproof.\" (cb76fbd7ec87e44b3c53165d68dc2747f7e26a9a).\n\n> Can you test if it crashes for you, too? I'm not sure I see why this one fails when millions of others pass.\n\n> The backtrace is still complaining about regc_nfa.c:1265:\n\n> +select regexp_split_to_array('', '(?:((?:q+))){0}(\\1){0,0}?*[^]');\n> +server closed the connection unexpectedly\n\nHmmm ... yeah, I see it too. This points up something I'd wondered\nabout before, which is whether the code that \"cancels everything\"\nafter detecting {0} is really OK. It throws away the outer subre\n*and children* without worrying about what might be inside, and\nhere we see that that's not good enough --- there's still a v->subs\npointer to the first capturing paren set, which we just deleted,\nso that the \\1 later on messes up. I'm not sure why the back\nbranches are managing not to crash, but that might just be a memory\nmanagement artifact.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 09 Aug 2021 17:26:16 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "I wrote:\n> Hmmm ... yeah, I see it too. This points up something I'd wondered\n> about before, which is whether the code that \"cancels everything\"\n> after detecting {0} is really OK. It throws away the outer subre\n> *and children* without worrying about what might be inside, and\n> here we see that that's not good enough --- there's still a v->subs\n> pointer to the first capturing paren set, which we just deleted,\n> so that the \\1 later on messes up. I'm not sure why the back\n> branches are managing not to crash, but that might just be a memory\n> management artifact.\n\n... yeah, it is. For me, this variant hits the assertion in all\nbranches:\n\nregression=# select regexp_split_to_array('', '((.)){0}(\\2){0}');\nserver closed the connection unexpectedly\n\nSo that's a pre-existing (and very long-standing) bug. I'm not\nsure if it has any serious impact in non-assert builds though.\nFailure to clean out some disconnected arcs probably has no\nreal effect on the regex's behavior later.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 09 Aug 2021 18:23:36 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> +select regexp_split_to_array('', '(?:((?:q+))){0}(\\1){0,0}?*[^]');\n> +server closed the connection unexpectedly\n\nHere's a quick draft patch for this. Basically it moves the\nresponsibility for clearing v->subs[] pointers into the freesubre()\nrecursion, so that it will happen for contained capturing parens\nnot only the top level.\n\nThere is a potentially interesting definitional question:\nwhat exactly ought this regexp do?\n\n\t\t((.)){0}\\2\n\nBecause the capturing paren sets are zero-quantified, they will\nnever be matched to any characters, so the backref can never\nhave any defined referent. I suspect that study of the POSIX\nspec would lead to the conclusion that this is a legal regexp\nbut it will never match anything. Implementing that would be\ntedious though, and what's more it seems very unlikely that\nthe user wanted any such behavior. So I think throwing an\nerror is an appropriate response. The existing code will\nthrow such an error for\n\n\t\t((.)){0}\\1\n\nso I guess Spencer did think about this to some extent -- he\njust forgot about the possibility of nested parens.\n\nThis patch should work OK in HEAD and v14, but it will need\na bit of fooling-about for older branches I think, given that\nthey fill v->subs[] a little differently.\n\n\t\t\tregards, tom lane", "msg_date": "Mon, 09 Aug 2021 19:31:41 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "\n\n> On Aug 9, 2021, at 12:14 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Pushed, but while re-reading it before commit I noticed that there's\n> some more fairly low-hanging fruit in regexp_replace(). As I had it\n> in that patch, it never used REG_NOSUB because of the possibility\n> that the replacement string uses \"\\N\". However, we're already\n> pre-checking the replacement string to see if it has backslashes\n> at all, so while we're at it we can check for \\N to discover if we\n> actually need any subexpression match data or not. We do need to\n> refactor a little to postpone calling pg_regcomp until after we\n> know that, but I think that makes replace_text_regexp's API less\n> ugly not more so.\n> \n> While I was at it, I changed the search-for-backslash loops to\n> use memchr rather than handwritten looping. Their use of\n> pg_mblen was pretty unnecessary given we only need to find\n> backslashes, and we can assume the backend encoding is ASCII-safe.\n> \n> Using a bunch of random cases generated by your little perl\n> script, I see maybe 10-15% speedup on test cases that don't\n> use \\N in the replacement string, while it's about a wash\n> on cases that do. (If I'd been using a multibyte encoding,\n> maybe the memchr change would have made a difference, but\n> I didn't try that.)\n\nI've been reviewing and testing this (let-regexp_replace-use-NOSUB.patch) since you sent it 4 hours ago, and I can't seem to break it. There are pre-existing problems in the regex code, but this doesn't seem to add any new breakage.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Mon, 9 Aug 2021 16:37:18 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "\n\n> On Aug 9, 2021, at 4:31 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> There is a potentially interesting definitional question:\n> what exactly ought this regexp do?\n> \n> \t\t((.)){0}\\2\n> \n> Because the capturing paren sets are zero-quantified, they will\n> never be matched to any characters, so the backref can never\n> have any defined referent.\n\nPerl regular expressions are not POSIX, but if there is a principled reason POSIX should differ from perl on this, we should be clear what that is:\n\n #!/usr/bin/perl\n \n use strict;\n use warnings;\n\n our $match;\n if ('foo' =~ m/((.)(??{ die; })){0}(..)/)\n {\n print \"captured 1 $1\\n\" if defined $1;\n print \"captured 2 $2\\n\" if defined $2;\n print \"captured 3 $3\\n\" if defined $3;\n print \"captured 4 $4\\n\" if defined $4;\n print \"match = $match\\n\" if defined $match;\n }\n\nThis will print \"captured 3 fo\", proving that although the regular expression is parsed with the (..) bound to the third capture group, the first two capture groups never run. If you don't believe that, change the {0} to {1} and observe that the script dies.\n\n> So I think throwing an\n> error is an appropriate response. The existing code will\n> throw such an error for\n> \n> \t\t((.)){0}\\1\n> \n> so I guess Spencer did think about this to some extent -- he\n> just forgot about the possibility of nested parens.\n\n\nUgg. That means our code throws an error where perl does not, pretty well negating my point above. If we're already throwing an error for this type of thing, I agree we should be consistent about it. My personal preference would have been to do the same thing as perl, but it seems that ship has already sailed.\n\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Mon, 9 Aug 2021 17:14:29 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "\n\n> On Aug 9, 2021, at 5:14 PM, Mark Dilger <mark.dilger@enterprisedb.com> wrote:\n> \n> our $match;\n> if ('foo' =~ m/((.)(??{ die; })){0}(..)/)\n\nI left in a stray variable. A prior version of this script was assigning to $match where it now has die. Sorry for any confusion.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Mon, 9 Aug 2021 17:18:27 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n>> On Aug 9, 2021, at 12:14 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Pushed, but while re-reading it before commit I noticed that there's\n>> some more fairly low-hanging fruit in regexp_replace().\n\n> I've been reviewing and testing this (let-regexp_replace-use-NOSUB.patch) since you sent it 4 hours ago, and I can't seem to break it. There are pre-existing problems in the regex code, but this doesn't seem to add any new breakage.\n\nPushed that bit, thanks for testing!\n\nI plan to not do anything about the (()){0} bug until after the release\nwindow, since that will need to be back-patched. That bug's gotta be\ntwenty years old, so while I kinda wish we'd found it a few days\nearlier, waiting another 3 months won't make much difference.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 09 Aug 2021 20:57:31 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n>> On Aug 9, 2021, at 4:31 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> There is a potentially interesting definitional question:\n>> what exactly ought this regexp do?\n>> \t((.)){0}\\2\n>> Because the capturing paren sets are zero-quantified, they will\n>> never be matched to any characters, so the backref can never\n>> have any defined referent.\n\n> Perl regular expressions are not POSIX, but if there is a principled reason POSIX should differ from perl on this, we should be clear what that is:\n\n> if ('foo' =~ m/((.)(??{ die; })){0}(..)/)\n> {\n> print \"captured 1 $1\\n\" if defined $1;\n> print \"captured 2 $2\\n\" if defined $2;\n> print \"captured 3 $3\\n\" if defined $3;\n> print \"captured 4 $4\\n\" if defined $4;\n> print \"match = $match\\n\" if defined $match;\n> }\n\nHm. I'm not sure that this example proves anything about Perl's handling\nof the situation, since you didn't use a backref. I tried both\n\n\tif ('foo' =~ m/((.)){0}\\1/)\n\n\tif ('foo' =~ m/((.)){0}\\2/)\n\nand while neither throws an error, they don't succeed either.\nSo AFAICS Perl is acting in the way I'm attributing to POSIX.\nBut maybe we should actually read POSIX ...\n\n>> ... I guess Spencer did think about this to some extent -- he\n>> just forgot about the possibility of nested parens.\n\n> Ugg. That means our code throws an error where perl does not, pretty\n> well negating my point above. If we're already throwing an error for\n> this type of thing, I agree we should be consistent about it. My\n> personal preference would have been to do the same thing as perl, but it\n> seems that ship has already sailed.\n\nRemoving an error case is usually an easier sell than adding one.\nHowever, the fact that the simplest case (viz, '(.){0}\\1') has always\nthrown an error and nobody has complained in twenty-ish years suggests\nthat nobody much cares.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 09 Aug 2021 21:11:14 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "\n\n> On Aug 9, 2021, at 6:11 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Hm. I'm not sure that this example proves anything about Perl's handling\n> of the situation, since you didn't use a backref.\n\nWell, this doesn't die either:\n\nif ('foo' =~ m/((??{ die; })(.)(??{ die $1; })){0}((??{ die \"got here\"; })|\\2)/)\n{\n print \"matched\\n\";\n}\n\nThe point is that the regex engine never walks the part of the pattern that {0} qualifies. I thought it was more clear in the prior example, because that example proves that the engine does get as far as capturing. This example also does that, and with a backref, because it dies with \"got here\".\n \n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Mon, 9 Aug 2021 18:17:40 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "\n\n> On Aug 9, 2021, at 6:17 PM, Mark Dilger <mark.dilger@enterprisedb.com> wrote:\n> \n> Well, this doesn't die either:\n\nMeaning it doesn't die in the part of the pattern qualified by {0} either. It does die in the other part. Sorry again for the confusion.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Mon, 9 Aug 2021 18:24:35 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "\n\n> On Aug 9, 2021, at 4:31 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> This patch should work OK in HEAD and v14, but it will need\n> a bit of fooling-about for older branches I think, given that\n> they fill v->subs[] a little differently.\n\nNote that I tested your patch *before* master, so the changes look backwards.\n\nI tested this fix and it seems good to me. Some patterns that used to work (by chance?) now raise an error, such as:\n\n select 'bpgouiwcquu' ~ '(((([e])*?)){0,0}?(\\3))';\n-ERROR: invalid regular expression: invalid backreference number\n+ ?column? \n+----------\n+ f\n+(1 row)\n\nI ran a lot of tests with the patch, and the asserts have all cleared up, but I don't know how to think about the user facing differences. If we had a good reason for raising an error for these back-references, maybe that'd be fine, but it seems to just be an implementation detail.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Mon, 9 Aug 2021 18:38:33 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> I ran a lot of tests with the patch, and the asserts have all cleared up, but I don't know how to think about the user facing differences. If we had a good reason for raising an error for these back-references, maybe that'd be fine, but it seems to just be an implementation detail.\n\nI thought about this some more, and I'm coming around to the idea that\nthrowing an error is the wrong thing. As a contrary example, consider\n\n\t(.)|(\\1\\1)\n\nWe don't throw an error for this, and neither does Perl, even though\nthe capturing parens can never be defined in the branch where the\nbackrefs are. So it seems hard to argue that this is okay but the\nother thing isn't. Another interesting example is\n\n\t(.){0}(\\1){0}\n\nI think that the correct interpretation is that this is a valid\nregexp matching an empty string (i.e., zero repetitions of each\npart), even though neither capture group will be defined.\nThat's different from\n\n\t(.){0}(\\1)\n\nwhich can never match.\n\nSo I took another look at the code, and it doesn't seem that hard\nto make it act this way. The attached passes regression, but\nI've not beat on it with random strings.\n\n\t\t\tregards, tom lane", "msg_date": "Mon, 09 Aug 2021 22:20:33 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "I wrote:\n> So AFAICS Perl is acting in the way I'm attributing to POSIX.\n> But maybe we should actually read POSIX ...\n\nI went to look at the POSIX spec, and was reminded that it lacks\nbackrefs altogether. (POSIX specifies the \"BRE\" and \"ERE\" regex\nflavors as described in our docs, but not \"ARE\".) So there's no\nhelp to be had there. The fact that Perl doesn't throw an error\nis probably the most useful precedent available.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 10 Aug 2021 11:15:22 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "\n\n> On Aug 9, 2021, at 7:20 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> So I took another look at the code, and it doesn't seem that hard\n> to make it act this way. The attached passes regression, but\n> I've not beat on it with random strings.\n\nI expect to get back around to testing this in a day or so.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Tue, 10 Aug 2021 08:16:35 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "\n\n> On Aug 9, 2021, at 7:20 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> So I took another look at the code, and it doesn't seem that hard\n> to make it act this way. The attached passes regression, but\n> I've not beat on it with random strings.\n> alternate-fix-zero-quantified-nested-parens.patch\n\nI've beaten on this with random patterns and it seems to hold up just fine. I have also reviewed the diffs and, for the patterns where the output changes, everything looks correct. I can't find anything wrong with this patch.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Tue, 24 Aug 2021 10:02:13 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> I've beaten on this with random patterns and it seems to hold up just fine. I have also reviewed the diffs and, for the patterns where the output changes, everything looks correct. I can't find anything wrong with this patch.\n\nThanks for testing! I'll push it in a bit.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 24 Aug 2021 14:29:01 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Another regexp performance improvement: skip useless\n paren-captures" } ]
[ { "msg_contents": "Dear Hackers, Tom,\n\n(I changed subject because this is no longer postgres_fdw's patch)\n\n> > What would be better to think about is how to let users specify this\n> > kind of behavior for themselves. I think it's possible to set\n> > application_name as part of a foreign server's connection options,\n> > but at present the result would only be a constant string. Somebody\n> > who wished the PID to be in there would like to have some sort of\n> > formatting escape, say \"%p\" for PID. Extrapolating wildly, maybe we\n> > could make all the %-codes known to log_line_prefix available here.\n> \n> I think your argument is better than mine. I will try to implement this approach.\n\nI made a patch based on your advice. I add parse and rewrite function in connectOptions2().\nI implemented in libpq layer, hence any other application can be used.\nHere is an example:\n\n```\n$ env PGAPPNAME=000%p%utest000 psql -d postgres -c \"show application_name\"\n application_name \n-----------------------\n 00025632hayatotest000\n(1 row)\n```\n\n> > I don't think this is a great idea as-is. People who need to do this\n> > sort of thing will all have their own ideas of what they need to track\n> > --- most obviously, it might be appropriate to include the originating\n> > server's name, else you don't know what machine the PID is for.\n> \n> I thought this is not big problem because hostname (or IP address) can be\n> added to log_line_prefix. I added only local-pid because this is the only thing\n> that cannot be set in the parameter.\n\nCurrently network hostname (or IP address) cannot be set because of the above reason.\nSome backends' code must be modified if we want to get and embed such information.\nOf cause we can get system hostname by gethostname(), but I cannot judge whether\nit is meaningful.\n\nHow do you think?\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Thu, 5 Aug 2021 03:18:58 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "Allow escape in application_name (was: [postgres_fdw] add local pid\n to fallback_application_name)" }, { "msg_contents": "\n\nOn 2021/08/05 12:18, kuroda.hayato@fujitsu.com wrote:\n> Dear Hackers, Tom,\n> \n> (I changed subject because this is no longer postgres_fdw's patch)\n> \n>>> What would be better to think about is how to let users specify this\n>>> kind of behavior for themselves. I think it's possible to set\n>>> application_name as part of a foreign server's connection options,\n>>> but at present the result would only be a constant string. Somebody\n>>> who wished the PID to be in there would like to have some sort of\n>>> formatting escape, say \"%p\" for PID. Extrapolating wildly, maybe we\n>>> could make all the %-codes known to log_line_prefix available here.\n>>\n>> I think your argument is better than mine. I will try to implement this approach.\n> \n> I made a patch based on your advice. I add parse and rewrite function in connectOptions2().\n> I implemented in libpq layer, hence any other application can be used.\n> Here is an example:\n> \n> ```\n> $ env PGAPPNAME=000%p%utest000 psql -d postgres -c \"show application_name\"\n> application_name\n> -----------------------\n> 00025632hayatotest000\n> (1 row)\n> ```\n\nWhy did you make even %u and %d available in application_name?\nWith the patch, they are replaced with the user name to connect as\nand the database name to connect to, respectively. Unlike %p\n(i.e., PID in *client* side), those information can be easily viewed via\nlog_line_prefix and pg_stat_activity, etc in the server side.\nSo I'm not sure how much helpful to expose them also in application_name.\n\n\n> \n>>> I don't think this is a great idea as-is. People who need to do this\n>>> sort of thing will all have their own ideas of what they need to track\n>>> --- most obviously, it might be appropriate to include the originating\n>>> server's name, else you don't know what machine the PID is for.\n\nSo some people may want to specify their own ID in application_name\nwhen connecting to the foreign server. For now they can do that by\nsetting application_name per foreign server object. But this means that\nevery session connecting to the same foreign server basically should\nuse the same application_name. If they want to change the setting,\nthey need to execute \"ALTER SERAVER ... OPTIONS ...\". Isn't this inconvenient?\nIf yes, what about allowing us to specify foreign server's application_name\nper session? For example, we can add postgres_fdw.application_name GUC,\nand then if it's set postgres_fdw always uses it instead of the server-level\noption when connecting to the foreign server. Thought?\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 19 Aug 2021 20:08:51 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "Dear Fujii-san,\n\nThank you for replying! I attached new version.\n\n> Why did you make even %u and %d available in application_name?\n\nActually no particular reason. I added them because they can easily add...\nAnd I agree what you say, so removed.\n\n> So some people may want to specify their own ID in application_name\n> when connecting to the foreign server. For now they can do that by\n> setting application_name per foreign server object. But this means that\n> every session connecting to the same foreign server basically should\n> use the same application_name. If they want to change the setting,\n> they need to execute \"ALTER SERAVER ... OPTIONS ...\". Isn't this inconvenient?\n\nYeah, currently such users must execute ALTER command for each time.\n\n> If yes, what about allowing us to specify foreign server's application_name\n> per session? For example, we can add postgres_fdw.application_name GUC,\n> and then if it's set postgres_fdw always uses it instead of the server-level\n> option when connecting to the foreign server. Thought?\n\nOK, I added the GUC parameter. My patch Defines new GUC at _PG_init().\nThe value is used when backends started to connect to remote server.\nNormal users can modify the value by SET commands but\nthat change does not propagate to the established connections.\n\nI'm not sure about the versioning policy about contrib.\nDo we have to make new version? Any other objects are not changed.\n\nFinally, I and Fujii-san were now discussing locally whether\nthis replacement should be in libpq or postgres_fdw layer.\nI started to think that it should be postgres_fdw, because:\n* previously aplications could distinguish by using current applicaiton_name,\n* libpq is used almost all uses so some modifications might affect someone, and\n* libpq might be just a tool, and should not be intelligent\n\nI will make and attach another version that new codes move to postgres_fdw.\nSo could you vote which version is better?\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Thu, 26 Aug 2021 06:00:27 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "Dear Fujii-san,\n\nI attached new version, that almost all codes\nmoved from libpq to postgres_fdw.\n\nNow we can accept four types of escapes.\nAll escapes will be rewritten to connection souce's information:\n\n* application_name,\n* user name,\n* database name, and\n* backend's pid.\n\nThese are cannot be set by log_line_prefix, so I think it is useful.\n\n\nWe can use escape sequences in two ways:\n* Sets postgres_fdw.application_name GUC paramter, or\n* Sets application_name option in CREATE SERVER command.\n\nWhich version do you like?\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Tue, 31 Aug 2021 07:11:33 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "\n\nOn 2021/08/31 16:11, kuroda.hayato@fujitsu.com wrote:\n> Dear Fujii-san,\n> \n> I attached new version, that almost all codes\n> moved from libpq to postgres_fdw.\n\nThanks for updating the patch!\n\nCan we split the patch into two as follows? If so, we can review\nand commit them one by one.\n\n#1. Add application_name GUC into postgres_fdw\n#2. Allow to specify special escape characters in application_name that postgres_fdw uses.\n\n\n> \n> Now we can accept four types of escapes.\n> All escapes will be rewritten to connection souce's information:\n> \n> * application_name,\n> * user name,\n> * database name, and\n> * backend's pid.\n\n+1\n\n\n> \n> These are cannot be set by log_line_prefix, so I think it is useful.\n> \n> \n> We can use escape sequences in two ways:\n> * Sets postgres_fdw.application_name GUC paramter, or\n> * Sets application_name option in CREATE SERVER command.\n\nOK.\n\n\n> \n> Which version do you like?\n\nFor now I've not found real use case that implementing the feature\nin libpq would introduce. So IMO postgres_fdw version is better.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Wed, 1 Sep 2021 14:13:13 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "Dear Fujii-san,\n\n> Can we split the patch into two as follows? If so, we can review\n> and commit them one by one.\n> \n> #1. Add application_name GUC into postgres_fdw\n> #2. Allow to specify special escape characters in application_name that\n> postgres_fdw uses.\n\nOK, I split and attached like that. 0001 adds new GUC, and\n0002 allows to accept escapes. \n\n> For now I've not found real use case that implementing the feature\n> in libpq would introduce. So IMO postgres_fdw version is better.\n\n+1, so I'll focus on the this version.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Wed, 1 Sep 2021 10:04:21 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "\n\nOn 2021/09/01 19:04, kuroda.hayato@fujitsu.com wrote:\n> OK, I split and attached like that. 0001 adds new GUC, and\n> 0002 allows to accept escapes.\n\nThanks for splitting and updating the patches!\n\nHere are the comments for 0001 patch.\n\n-\t\t/* Use \"postgres_fdw\" as fallback_application_name. */\n+\t\t/* Use GUC paramter if set */\n+\t\tif (pgfdw_application_name && *pgfdw_application_name != '\\0')\n\nThis GUC parameter should be set after the options of foreign server\nare set so that its setting can override the server-level ones.\nIsn't it better to comment this?\n\n\n+static bool\n+check_pgfdw_application_name(char **newval, void **extra, GucSource source)\n+{\n+\t/* Only allow clean ASCII chars in the application name */\n+\tif (*newval)\n+\t\tpg_clean_ascii(*newval);\n+\treturn true;\n\nDo we really need this check hook? Even without that, any non-ASCII characters\nin application_name would be replaced with \"?\" in the foreign PostgreSQL server\nwhen it's passed to that.\n\nOn the other hand, if it's really necessary, application_name set in foreign\nserver object also needs to be processed in the same way.\n\n\n+\t\t\t\t\t\t\t NULL,\n+\t\t\t\t\t\t\t PGC_USERSET,\n+\t\t\t\t\t\t\t GUC_IS_NAME,\n\nWhy is GUC_IS_NAME flag necessary?\n\n\npostgres_fdw.application_name overrides application_name set in foreign server object.\nShouldn't this information be documented?\n\n\nIsn't it better to have the regression test for this feature?\n\nRegards,\n\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 2 Sep 2021 00:40:48 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "Dear Fujii-san,\n\nThank you for reviewing!\n\n> This GUC parameter should be set after the options of foreign server\n> are set so that its setting can override the server-level ones.\n> Isn't it better to comment this?\n\nI added the following comments:\n\n```diff\n- /* Use \"postgres_fdw\" as fallback_application_name. */\n+ /*\n+ * Use pgfdw_application_name as application_name.\n+ *\n+ * Note that this check must be behind constructing generic options\n+ * because pgfdw_application_name has higher priority.\n+ */\n```\n\n> Do we really need this check hook? Even without that, any non-ASCII characters\n> in application_name would be replaced with \"?\" in the foreign PostgreSQL server\n> when it's passed to that.\n> \n> On the other hand, if it's really necessary, application_name set in foreign\n> server object also needs to be processed in the same way.\n\nI added check_hook because I want to make sure that\ninput for parse function has only ascii characters.\nBut in this phase we don't have such a function, so removed.\n(Actually I'm not sure it is really needed, so I will check until next phase)\n\n> Why is GUC_IS_NAME flag necessary?\n\nI thought again and I noticed even if extremely long string is specified\nit will be truncated at server-side. This check is duplicated so removed.\nMaybe such a check is a user-responsibility.\n\n> postgres_fdw.application_name overrides application_name set in foreign server\n> object.\n> Shouldn't this information be documented?\n\nI added descriptions to postgres_fdw.sgml.\n\n> Isn't it better to have the regression test for this feature?\n\n+1, added. In that test SET the parameter and check pg_stat_activity.\n\nAttached is the fixed version. 0002 will be rebased later.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Thu, 2 Sep 2021 09:27:09 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "\n\nOn 2021/09/02 18:27, kuroda.hayato@fujitsu.com wrote:\n> I added the following comments:\n> \n> ```diff\n> - /* Use \"postgres_fdw\" as fallback_application_name. */\n> + /*\n> + * Use pgfdw_application_name as application_name.\n> + *\n> + * Note that this check must be behind constructing generic options\n> + * because pgfdw_application_name has higher priority.\n> + */\n> ```\n\nThanks! What about updating the comments furthermore as follows?\n\n---------------------------------\nUse pgfdw_application_name as application_name if set.\n\nPQconnectdbParams() processes the parameter arrays from start to end.\nIf any key word is repeated, the last value is used. Therefore note that\npgfdw_application_name must be added to the arrays after options of\nForeignServer are, so that it can override application_name set in\nForeignServer.\n---------------------------------\n\n> Attached is the fixed version. 0002 will be rebased later.\n\nThanks for updating the patch!\n\n+\t\t}\n+\t\t/* Use \"postgres_fdw\" as fallback_application_name */\n\nIt's better to add new empty line between these two lines.\n\n+-- Disconnect once because the value is used only when establishing connections\n+DO $$\n+\tBEGIN\n+\t\tPERFORM postgres_fdw_disconnect_all();\n+\tEND\n+$$;\n\nWhy does DO command need to be used here to execute\npostgres_fdw_disconnect_all()? Instead, we can just execute\n\"SELECT 1 FROM postgres_fdw_disconnect_all();\"?\n\nFor test coverage, it's better to test at least the following three cases?\n\n(1) appname is set in neither GUC nor foreign server\n -> \"postgres_fdw\" set in fallback_application_name is used\n(2) appname is set in foreign server, but not in GUC\n -> appname in foreign server is used\n(3) appname is set both in GUC and foreign server\n -> appname in GUC is used\n\n+SELECT FROM ft1 LIMIT 1;\n\n\"1\" should be added just after SELECT in the above statement?\nBecause postgres_fdw regression test basically uses \"SELECT 1 FROM ...\"\nin other places.\n\n+\tDefineCustomStringVariable(\"postgres_fdw.application_name\",\n+\t\t\t\t\t\t\t \"Sets the application name. This is used when connects to the remote server.\",\n\nWhat about simplifying this description as follows?\n\n---------------\nSets the application name to be used on the remote server.\n---------------\n\n+ <title> Configuration Parameters </title>\n+ <variablelist>\n\nThe empty characters just after <title> and before </title> should be removed?\n\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 2 Sep 2021 21:36:34 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "Dear Fujii-san,\n\nThank you for your great works. Attached is the latest version.\n\n> Thanks! What about updating the comments furthermore as follows?\n> \n> ---------------------------------\n> Use pgfdw_application_name as application_name if set.\n> \n> PQconnectdbParams() processes the parameter arrays from start to end.\n> If any key word is repeated, the last value is used. Therefore note that\n> pgfdw_application_name must be added to the arrays after options of\n> ForeignServer are, so that it can override application_name set in\n> ForeignServer.\n> ---------------------------------\n\nIt's more friendly than mine because it mentions\nabout specification about PQconnectdbParams(). \nFixed like yours.\n\n> +\t\t}\n> +\t\t/* Use \"postgres_fdw\" as fallback_application_name */\n> \n> It's better to add new empty line between these two lines.\n\nFixed.\n\n> +-- Disconnect once because the value is used only when establishing\n> connections\n> +DO $$\n> +\tBEGIN\n> +\t\tPERFORM postgres_fdw_disconnect_all();\n> +\tEND\n> +$$;\n> \n> Why does DO command need to be used here to execute\n> postgres_fdw_disconnect_all()? Instead, we can just execute\n> \"SELECT 1 FROM postgres_fdw_disconnect_all();\"?\n\nDO command was used because I want to\nignore the returning value of postgres_fdw_disconnect_all().\nCurrently this function retruns false, but if other tests are modified,\nsome connection may remain and the function may become to return true.\n\nI seeked sql file and I found that this function was called by your way.\nHence I fixed.\n\n> For test coverage, it's better to test at least the following three cases?\n> \n> (1) appname is set in neither GUC nor foreign server\n> -> \"postgres_fdw\" set in fallback_application_name is used\n> (2) appname is set in foreign server, but not in GUC\n> -> appname in foreign server is used\n> (3) appname is set both in GUC and foreign server\n> -> appname in GUC is used\n\nI set four testcases:\n\n(1) Sets neither GUC nor server option\n(2) Sets server option, but not GUC\n(3) Sets GUC but not server option\n(4) Sets both GUC and server option\n\nI confirmed it almost works fine, but I found that\nfallback_application_name will be never used in our test enviroment.\nIt is caused because our test runner pg_regress sets PGAPPNAME to \"pg_regress\" and\nlibpq prefer the environment variable to fallback_appname.\n(I tried to control it by \\setenv, but failed...)\n\n> +SELECT FROM ft1 LIMIT 1;\n> \n> \"1\" should be added just after SELECT in the above statement?\n> Because postgres_fdw regression test basically uses \"SELECT 1 FROM ...\"\n> in other places.\n\nFixed.\n\n> +\tDefineCustomStringVariable(\"postgres_fdw.application_name\",\n> +\t\t\t\t\t\t\t \"Sets the application name. This is used when connects to the remote server.\",\n>\n> What about simplifying this description as follows?\n>\n> ---------------\n> Sets the application name to be used on the remote server.\n> ---------------\n\n+1.\n\n> + <title> Configuration Parameters </title>\n> + <variablelist>\n> \n> The empty characters just after <title> and before </title> should be removed?\n\nI checked other sgml file and agreed. Fixed.\n\nAnd I found that including string.h is no more needed. Hence it is removed.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Fri, 3 Sep 2021 05:56:21 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "On 2021/09/03 14:56, kuroda.hayato@fujitsu.com wrote:\n> Dear Fujii-san,\n> \n> Thank you for your great works. Attached is the latest version.\n\nThanks a lot!\n\n\n> I set four testcases:\n> \n> (1) Sets neither GUC nor server option\n> (2) Sets server option, but not GUC\n> (3) Sets GUC but not server option\n> (4) Sets both GUC and server option\n\nOK.\n\n\n> I confirmed it almost works fine, but I found that\n> fallback_application_name will be never used in our test enviroment.\n> It is caused because our test runner pg_regress sets PGAPPNAME to \"pg_regress\" and\n> libpq prefer the environment variable to fallback_appname.\n> (I tried to control it by \\setenv, but failed...)\n\nmake check uses \"pg_regress\", but I guess that make installcheck uses\n\"postgres_fdw\". So the patch would cause make installcheck to fail.\nI think that the case (1) is not so important, so can be removed. Thought?\n\nAttached is the updated version of the patch. I removed the test\nfor case (1). And I arranged the regression tests so that they are based\non debug_discard_caches, to simplify them. Also I added and updated\nsome comments and docs. Could you review this version?\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION", "msg_date": "Sat, 4 Sep 2021 01:54:39 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "Dear Fujii-san,\n\nThank you for updating! Your modification is very interesting and\nI learn something new.\n\n> Attached is the updated version of the patch. I removed the test\n> for case (1). And I arranged the regression tests so that they are based\n> on debug_discard_caches, to simplify them. Also I added and updated\n> some comments and docs. Could you review this version?\n\nI agree removing (1) because it is obvious case.\n\n```diff\n+-- If appname is set both as GUC and as options of server object,\n+-- the GUC setting overrides appname of server object and is used.\n+SET postgres_fdw.application_name TO 'fdw_guc_appname';\n+SELECT 1 FROM postgres_fdw_disconnect_all();\n+ ?column? \n+----------\n+ 1\n+(1 row)\n+\n+SELECT 1 FROM ft1 LIMIT 1;\n+ ?column? \n+----------\n+ 1\n+(1 row)\n+\n+SELECT application_name FROM pg_stat_activity\n+ WHERE application_name IN ('loopback2', 'fdw_guc_appname');\n+ application_name \n+------------------\n+ fdw_guc_appname\n+(1 row)\n```\n\nI think we should SELECT ft6 because foreign server 'loopback'\ndoesn't have application_name server option.\n\nI have no comments anymore.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED\n\n\n\n", "msg_date": "Mon, 6 Sep 2021 01:32:57 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "Hi, Kuroda-san, Fujii-san\n\nI agree that this feature is useful. Thanks for working this.\nI've tried to use the patches and read them. I have some questions.\n\n1)\n\nWhy does postgres_fdw.application_name override the server's option?\n\n> + establishes a connection to a foreign server. This overrides\n> + <varname>application_name</varname> option of the server object.\n> + Note that change of this parameter doesn't affect any existing\n> + connections until they are re-established.\n\nMy expected behavior was that application_name option of server object\noverrides the GUC because other GUCs seems behave so. For example,\nlog_statement in postgresql.conf can be overrided by ALTER ROLE for\nonly specific user. Should the narrower scope setting takes precedence?\n\n2)\n\nIs it better to specify that we can use the escaped format\nfor application_name option of the server object in the document?\nI think it's new feature too.\n\n3)\n\nIs the following expected behavior?\n\n* 1. [coorinator] configure \"postgres_fdw.application_name\" as \"[%d]\".\n* 2. [coodinator] connect *Non-ASCII* database.\n* 3. [coodinator] execute queries for remote server.\n* 4. [remote] execute the following query.\n\n```\npostgres(2654193)=# SELECT application_name FROM pg_stat_activity WHERE \nbackend_type = 'client backend' ;\n application_name\n---------------------------\n psql\n [?????????]\n```\n\nOne of the difference between log_line_prefix and application_name\nis that whether it only allow clean ASCII chars or not. So, the above\nbehavior is expected.\n\nI think there are three choices for handling the above case.\n\n1) Accept the above case because Non-ASCII rarely be used(?), and\n describe the limitation in the document.\n2) Add a new characters for oid of database.\n3) Lease the limitation of application_name and make it accept \nNon-ASCII.\n\nAs a user, 3) is best for me.\nBut it seems be out of scope this threads, so will you select 1)?\n\nRegards,\n-- \nMasahiro Ikeda\nNTT DATA CORPORATION\n\n\n", "msg_date": "Mon, 06 Sep 2021 11:17:40 +0900", "msg_from": "Masahiro Ikeda <ikedamsh@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Ikeda-san,\n\n> I agree that this feature is useful. Thanks for working this.\n\nThanks :-).\n\n> 1)\n> \n> Why does postgres_fdw.application_name override the server's option?\n> \n> > + establishes a connection to a foreign server. This overrides\n> > + <varname>application_name</varname> option of the server object.\n> > + Note that change of this parameter doesn't affect any existing\n> > + connections until they are re-established.\n> \n> My expected behavior was that application_name option of server object\n> overrides the GUC because other GUCs seems behave so. For example,\n> log_statement in postgresql.conf can be overrided by ALTER ROLE for\n> only specific user. Should the narrower scope setting takes precedence?\n\nHmm... I didn't know the policy in other options, thank you.\nI set higher priority because of the following reason.\nWhen users set app name as server option and\ncreate remote connection from same backend process,\nthey will use same even if GUC sets.\nIn this case users must execute ALTER SERVERS every session,\nand I think it is inconvenient.\n\nI think both approaches are reasonable, so I also want to ask committer.\nFujii-san, how do you think?\n\n> 2)\n> \n> Is it better to specify that we can use the escaped format\n> for application_name option of the server object in the document?\n> I think it's new feature too.\n\nYeah, I agree. I will add at `Connection Options` section in 0002 patch.\nIs it OK? Do we have more good place?\n\n> 3)\n> \n> Is the following expected behavior?\n> \n> * 1. [coorinator] configure \"postgres_fdw.application_name\" as \"[%d]\".\n> * 2. [coodinator] connect *Non-ASCII* database.\n> * 3. [coodinator] execute queries for remote server.\n> * 4. [remote] execute the following query.\n> \n> ```\n> postgres(2654193)=# SELECT application_name FROM pg_stat_activity WHERE\n> backend_type = 'client backend' ;\n> application_name\n> ---------------------------\n> psql\n> [?????????]\n> ```\n> \n> One of the difference between log_line_prefix and application_name\n> is that whether it only allow clean ASCII chars or not. So, the above\n> behavior is expected.\n> \n> I think there are three choices for handling the above case.\n> \n> 1) Accept the above case because Non-ASCII rarely be used(?), and\n> describe the limitation in the document.\n> 2) Add a new characters for oid of database.\n> 3) Lease the limitation of application_name and make it accept\n> Non-ASCII.\n> \n> As a user, 3) is best for me.\n> But it seems be out of scope this threads, so will you select 1)?\n\nActually I did not considering about such a situation...\nBut I want to choose (1) because the limitation is caused by libpq layer\nand the modification is almost unrelated to this patch.\nI'm not sure why appname have such a limitation\nso at first we should investigate it. How do you think?\n\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED\n\n\n\n", "msg_date": "Mon, 6 Sep 2021 04:21:26 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "On 2021-09-06 13:21, kuroda.hayato@fujitsu.com wrote:\n> Dear Ikeda-san,\n> \n>> I agree that this feature is useful. Thanks for working this.\n> \n> Thanks :-).\n> \n>> 1)\n>> \n>> Why does postgres_fdw.application_name override the server's option?\n>> \n>> > + establishes a connection to a foreign server. This overrides\n>> > + <varname>application_name</varname> option of the server object.\n>> > + Note that change of this parameter doesn't affect any existing\n>> > + connections until they are re-established.\n>> \n>> My expected behavior was that application_name option of server object\n>> overrides the GUC because other GUCs seems behave so. For example,\n>> log_statement in postgresql.conf can be overrided by ALTER ROLE for\n>> only specific user. Should the narrower scope setting takes \n>> precedence?\n> \n> Hmm... I didn't know the policy in other options, thank you.\n> I set higher priority because of the following reason.\n> When users set app name as server option and\n> create remote connection from same backend process,\n> they will use same even if GUC sets.\n> In this case users must execute ALTER SERVERS every session,\n> and I think it is inconvenient.\n\nThanks for explaining what you thought. I understood your idea.\n\nIIUC, we can execute \"ALTER SERVERS\" commands automatically using \nscripts?\nIf so, to have finer control seems to be more important than to reduce \nthe effort of\noverwriting every configuration.\n\nBut this is just my feeling.\nI agree to hear comments from Fujii-san and so on.\n\n> I think both approaches are reasonable, so I also want to ask \n> committer.\n> Fujii-san, how do you think?\n>> 2)\n>> \n>> Is it better to specify that we can use the escaped format\n>> for application_name option of the server object in the document?\n>> I think it's new feature too.\n> \n> Yeah, I agree. I will add at `Connection Options` section in 0002 \n> patch.\n> Is it OK? Do we have more good place?\n\n+1\n\nI found that '%%' need to be described in the documents\nof postgres_fdw.application_name. What do you think?\n\n>> 3)\n>> \n>> Is the following expected behavior?\n>> \n>> * 1. [coorinator] configure \"postgres_fdw.application_name\" as \"[%d]\".\n>> * 2. [coodinator] connect *Non-ASCII* database.\n>> * 3. [coodinator] execute queries for remote server.\n>> * 4. [remote] execute the following query.\n>> \n>> ```\n>> postgres(2654193)=# SELECT application_name FROM pg_stat_activity \n>> WHERE\n>> backend_type = 'client backend' ;\n>> application_name\n>> ---------------------------\n>> psql\n>> [?????????]\n>> ```\n>> \n>> One of the difference between log_line_prefix and application_name\n>> is that whether it only allow clean ASCII chars or not. So, the above\n>> behavior is expected.\n>> \n>> I think there are three choices for handling the above case.\n>> \n>> 1) Accept the above case because Non-ASCII rarely be used(?), and\n>> describe the limitation in the document.\n>> 2) Add a new characters for oid of database.\n>> 3) Lease the limitation of application_name and make it accept\n>> Non-ASCII.\n>> \n>> As a user, 3) is best for me.\n>> But it seems be out of scope this threads, so will you select 1)?\n> \n> Actually I did not considering about such a situation...\n> But I want to choose (1) because the limitation is caused by libpq \n> layer\n> and the modification is almost unrelated to this patch.\n> I'm not sure why appname have such a limitation\n> so at first we should investigate it. How do you think?\n\nOK. I agree that (1) is enough for the first step.\nIf I have any time, I'll investigate it too.\n\nRegards,\n-- \nMasahiro Ikeda\nNTT DATA CORPORATION\n\n\n", "msg_date": "Mon, 06 Sep 2021 16:48:35 +0900", "msg_from": "Masahiro Ikeda <ikedamsh@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "On 2021/09/06 10:32, kuroda.hayato@fujitsu.com wrote:\n> I think we should SELECT ft6 because foreign server 'loopback'\n> doesn't have application_name server option.\n\nYes. I forgot to update that... Thanks for the review!\nAttached is the updated version of the patch.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION", "msg_date": "Mon, 6 Sep 2021 20:52:45 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "\n\nOn 2021/09/06 16:48, Masahiro Ikeda wrote:\n> On 2021-09-06 13:21, kuroda.hayato@fujitsu.com wrote:\n>> Dear Ikeda-san,\n>>\n>>> I agree that this feature is useful. Thanks for working this.\n>>\n>> Thanks :-).\n>>\n>>> 1)\n>>>\n>>> Why does postgres_fdw.application_name override the server's option?\n>>>\n>>> > +      establishes a connection to a foreign server.  This overrides\n>>> > +      <varname>application_name</varname> option of the server object.\n>>> > +      Note that change of this parameter doesn't affect any existing\n>>> > +      connections until they are re-established.\n>>>\n>>> My expected behavior was that application_name option of server object\n>>> overrides the GUC because other GUCs seems behave so. For example,\n>>> log_statement in postgresql.conf can be overrided by ALTER ROLE for\n>>> only specific user. Should the narrower scope setting takes precedence?\n\nAn option of a role doesn't always override a GUC setting. For example,\nGUC with PGC_USERSET like work_mem, work_mem setting of a role overrides\nthat set in postgresql.conf, as you told. But if work_mem is set by\nSET command, its value overrides the option of a role. So if we should treat\nan option of foreign server object like an option of a role, we should handle\napplicaion_name option for postgres_fdw in that way.\n\nIf we want to implement this, we need to check the context of\npostgres_fdw.application_name when using it. If its context is PGC_SIGHUP\nor PGC_POSTMASTER, it needs to be added the connection arrays that\nPQconnectParams() uses before options of server object are processed,\ni.e., application_name of server object overrides the other in this case.\nOn the other hand, if its context is higher than PGC_SIGHUP, it needs to\nbe added to the arrays after options of server object are processed.\n\nI'm OK with the current proposal for now (i.e., postgres_fdw.application_name\nalways overrides that of server object) at least as the first step beucase\nit's simple. But if you want that feature and can simply implement it, I don't\nobject to that.\n\n> IIUC, we can execute \"ALTER SERVERS\" commands automatically using scripts?\n> If so, to have finer control seems to be more important than to reduce the effort of\n> overwriting every configuration.\n\nYou mean to execute ALTER SERVER automatically via script whenever\na client connects to the server (i.e., a client passes its application_name\nto the server, the server automatically sets it to the foreign server object,\nthen the server uses it as application_name of the remote connection)?\n\n\n>>> Is it better to specify that we can use the escaped format\n>>> for application_name option of the server object in the document?\n>>> I think it's new feature too.\n>>\n>> Yeah, I agree. I will add at `Connection Options` section in 0002 patch.\n>> Is it OK? Do we have more good place?\n> \n> +1\n\n+1\n\n>> Actually I did not considering about such a situation...\n>> But I want to choose (1) because the limitation is caused by libpq layer\n>> and the modification is almost unrelated to this patch.\n>> I'm not sure why appname have such a limitation\n>> so at first we should investigate it. How do you think?\n> \n> OK. I agree that (1) is enough for the first step.\n\n+1\n\n> If I have any time, I'll investigate it too.\n\nMaybe we need to consider what happens if different clients use\napplication_name with different encodings. How should\npg_stat_activity.application_name and log_line_prefix, etc handle such case?\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Mon, 6 Sep 2021 21:28:20 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "\nOn 2021/09/06 21:28, Fujii Masao wrote:\n>\n>\n> On 2021/09/06 16:48, Masahiro Ikeda wrote:\n>> On 2021-09-06 13:21, kuroda.hayato@fujitsu.com wrote:\n>>> Dear Ikeda-san,\n>>>\n>>>> I agree that this feature is useful. Thanks for working this.\n>>>\n>>> Thanks .\n>>>\n>>>> 1)\n>>>>\n>>>> Why does postgres_fdw.application_name override the server's option?\n>>>>\n>>>>> + establishes a connection to a foreign server. This overrides\n>>>>> + <varname>application_name</varname> option of the server object.\n>>>>> + Note that change of this parameter doesn't affect any existing\n>>>>> + connections until they are re-established.\n>>>>\n>>>> My expected behavior was that application_name option of server object\n>>>> overrides the GUC because other GUCs seems behave so. For example,\n>>>> log_statement in postgresql.conf can be overrided by ALTER ROLE for\n>>>> only specific user. Should the narrower scope setting takes precedence?\n>\n> An option of a role doesn't always override a GUC setting. For example,\n> GUC with PGC_USERSET like work_mem, work_mem setting of a role overrides\n> that set in postgresql.conf, as you told. But if work_mem is set by\n> SET command, its value overrides the option of a role. So if we should treat\n> an option of foreign server object like an option of a role, we should handle\n> applicaion_name option for postgres_fdw in that way.\n>\n> If we want to implement this, we need to check the context of\n> postgres_fdw.application_name when using it. If its context is PGC_SIGHUP\n> or PGC_POSTMASTER, it needs to be added the connection arrays that\n> PQconnectParams() uses before options of server object are processed,\n> i.e., application_name of server object overrides the other in this case.\n> On the other hand, if its context is higher than PGC_SIGHUP, it needs to\n> be added to the arrays after options of server object are processed.\n>\n> I'm OK with the current proposal for now (i.e., postgres_fdw.application_name\n> always overrides that of server object) at least as the first step beucase\n> it's simple. But if you want that feature and can simply implement it, I don't\n> object to that.\n\nThanks for explaining.\n\nI forgot to consider about SET command. I understood that SET command should\noverride the old value, and it's difficult to manage the contexts for server\noptions and the GUC. Sorry for my impractical proposal.\n\n>> IIUC, we can execute \"ALTER SERVERS\" commands automatically using scripts?\n>> If so, to have finer control seems to be more important than to reduce the\n>> effort of\n>> overwriting every configuration.\n>\n> You mean to execute ALTER SERVER automatically via script whenever\n> a client connects to the server (i.e., a client passes its application_name\n> to the server, the server automatically sets it to the foreign server object,\n> then the server uses it as application_name of the remote connection)?\n\nSorry, Kuroda-san and Fujii-san are right.\nIf SET command is used, ALTER SERVER doesn't work.\n\n>>>> Is it better to specify that we can use the escaped format\n>>>> for application_name option of the server object in the document?\n>>>> I think it's new feature too.\n>>>\n>>> Yeah, I agree. I will add at `Connection Options` section in 0002 patch.\n>>> Is it OK? Do we have more good place?\n>>\n>> +1\n>\n> +1\n>\n>>> Actually I did not considering about such a situation...\n>>> But I want to choose (1) because the limitation is caused by libpq layer\n>>> and the modification is almost unrelated to this patch.\n>>> I'm not sure why appname have such a limitation\n>>> so at first we should investigate it. How do you think?\n>>\n>> OK. I agree that (1) is enough for the first step.\n>\n> +1\n>\n>> If I have any time, I'll investigate it too.\n>\n> Maybe we need to consider what happens if different clients use\n> application_name with different encodings. How should\n> pg_stat_activity.application_name and log_line_prefix, etc handle such case?\n\nThanks. That makes sense.\nI'll check them.\n\nRegards,\n-- \nMasahiro Ikeda\nNTT DATA CORPORATION\n\n\n\n", "msg_date": "Tue, 7 Sep 2021 10:00:06 +0900", "msg_from": "Masahiro Ikeda <ikedamsh@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san,\n\nI confirmed it and I think it's OK.\nOther comments should be included in 0002.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED\n\n\n\n", "msg_date": "Tue, 7 Sep 2021 01:32:43 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "\n\nOn 2021/09/07 10:32, kuroda.hayato@fujitsu.com wrote:\n> Dear Fujii-san,\n> \n> I confirmed it and I think it's OK.\n> Other comments should be included in 0002.\n\nPushed 0001 patch. Thanks!\nCould you rebase 0002 patch?\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Tue, 7 Sep 2021 12:30:00 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "Dear Fujii-san, Ikeda-san,\n\n> Pushed 0001 patch. Thanks!\n\nI confirmed your commit. Thanks!\nI attached the rebased version. Tests and descriptions were added.\nIn my understanding Ikeda-san's indication is included.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Tue, 7 Sep 2021 11:30:27 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "Fujii Masao <masao.fujii@oss.nttdata.com> writes:\n> Pushed 0001 patch. Thanks!\n\nThe buildfarm shows that this test case isn't terribly reliable.\n\nTBH, I think you should just remove the test case altogether.\nIt does not look useful enough to justify a permanent expenditure of\ntesting cycles, never mind the amount of effort that would be needed to\nstabilize it.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 07 Sep 2021 18:46:06 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "\n\nOn 2021/09/08 7:46, Tom Lane wrote:\n> Fujii Masao <masao.fujii@oss.nttdata.com> writes:\n>> Pushed 0001 patch. Thanks!\n> \n> The buildfarm shows that this test case isn't terribly reliable.\n\nYes... Thanks for reporting this!\n\n\n> TBH, I think you should just remove the test case altogether.\n> It does not look useful enough to justify a permanent expenditure of\n> testing cycles, never mind the amount of effort that would be needed to\n> stabilize it.\n\nOk, I will remove the tests.\n\nKuroda-san is proposing the additional feature which allows\npostgres_fdw.application_name to include escape characters.\nIf we commit the feature, it's worth adding the similar tests\nchecking that the escape characters there are replaced with\nexpected values. So it's better to investigate what made\nthe tests fail, not to cause the same tests failure later.\n\nThe tests use postgres_fdw_disconnect_all() to close the existing\nremote connections before establishing new remote connection\nwith new application_name setting. Then they check that\nthe expected application_name appears in pg_stat_activity.\nThe cause of the issue seems to be that it can take a bit time for\nthe existing remote connection (i.e., its corresponding backend)\nto exit after postgres_fdw_disconect_all() is called.\nSo application_name of the existing remote connection also could\nappear in pg_stat_activity when it's checked next time.\n\nIf this analysis is right, the tests that the upcoming patch adds\nshould handle the case where the existing remote connection\ncan appear in pg_stat_activity after postgres_fdw_disconect_all().\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Wed, 8 Sep 2021 09:34:14 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name (was: [postgres_fdw] add local\n pid to fallback_application_name)" }, { "msg_contents": "At Tue, 7 Sep 2021 11:30:27 +0000, \"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com> wrote in \n> I attached the rebased version. Tests and descriptions were added.\n> In my understanding Ikeda-san's indication is included.\n\nI have some comments by a quick look.\n\n+\t\t * one have higher priority. See also the previous comment.\n\nIs \"the previous comment\" \"the comment above\"?\n\n+\t\tfor (i = n -1; i >= 0; i--)\n\nYou might want a space between - and 1.\n\n+parse_application_name(StringInfo buf, const char *name)\n\nThe name seems a bit too generic as it is a function only for\npostgres_fdw.\n\n\n+\t\t/* must be a '%', so skip to the next char */\n+\t\tp++;\n+\t\tif (*p == '\\0')\n+\t\t\tbreak;\t\t\t\t/* format error - ignore it */\n\nI'm surprised by finding that undefined %-escapes and stray % behave\ndifferently between archive_command and log_line_prefix. I understand\nthis behaves like the latter.\n\n+\t\t\t\t\tconst char *username = MyProcPort->user_name;\n\nI'm not sure but even if user_name doesn't seem to be NULL, don't we\nwant to do the same thing with %u of log_line_prefix for safety?\nNamely, setting [unknown] if user_name is NULL or \"\". The same can be\nsaid for %d.\n\n+ * process_padding --- helper function for processing the format\n+ * string in log_line_prefix\n\nSince this is no longer a static helper function for a specific\nfunction, the name and the comment should be more descriptive.\n\nThat being said, in the first place the function seems reducible\nalmost to a call to atol. By a quick measurement the function is about\n38% faster (0.024us/call(the function) vs 0.039us/call(strtol) so I'm\nnot sure we want to replace process_log_prefix_padding(), but we don't\nneed to reuse the function in parse_application_name since it is\ncalled only once per connection.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Wed, 08 Sep 2021 14:59:17 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Horiguchi-san,\n\nThank you for reviewing! I attached the fixed version.\n\n> Is \"the previous comment\" \"the comment above\"?\n\nYeah, fixed.\n\n> +\t\tfor (i = n -1; i >= 0; i--)\n> \n> You might want a space between - and 1.\n\nFixed.\n\n> +parse_application_name(StringInfo buf, const char *name)\n> \n> The name seems a bit too generic as it is a function only for\n> postgres_fdw.\n\nIndeed. I renamed to parse_pgfdw_appname().\n\n> +\t\t/* must be a '%', so skip to the next char */\n> +\t\tp++;\n> +\t\tif (*p == '\\0')\n> +\t\t\tbreak;\t\t\t\t/* format error -\n> ignore it */\n> \n> I'm surprised by finding that undefined %-escapes and stray % behave\n> differently between archive_command and log_line_prefix. I understand\n> this behaves like the latter.\n\nIndeed. pgarch_archiveXlog() treats undefined escapes as nothing special,\nbut log_line_prefix() stop parsing immediately.\nThey have no description about it in docs.\nI will not treat it in this thread and follow log_line_prefix(),\nbut I agree it is strange.\n\n> +\t\t\t\t\tconst char *username =\n> MyProcPort->user_name;\n> \n> I'm not sure but even if user_name doesn't seem to be NULL, don't we\n> want to do the same thing with %u of log_line_prefix for safety?\n> Namely, setting [unknown] if user_name is NULL or \"\". The same can be\n> said for %d.\n\nI think they will be never NULL in current implementation,\nbut your suggestion is better. Checks were added in %a, %u and %d.\n\n> + * process_padding --- helper function for processing the format\n> + * string in log_line_prefix\n> \n> Since this is no longer a static helper function for a specific\n> function, the name and the comment should be more descriptive.\n> \n> That being said, in the first place the function seems reducible\n> almost to a call to atol. By a quick measurement the function is about\n> 38% faster (0.024us/call(the function) vs 0.039us/call(strtol) so I'm\n> not sure we want to replace process_log_prefix_padding(), but we don't\n> need to reuse the function in parse_application_name since it is\n> called only once per connection.\n\nMy first impression is that they use the function\nbecause they want to know the end of sequence and do error-handling,\nbut I agree this can be replaced by strtol().\nI changed the function to strtol() and restored process_log_prefix_padding().\nHow do you think? Does it follow your suggestion?\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Wed, 8 Sep 2021 12:32:50 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/09/08 21:32, kuroda.hayato@fujitsu.com wrote:\n> Dear Horiguchi-san,\n> \n> Thank you for reviewing! I attached the fixed version.\n\nThanks for updating the patch!\n\n+\t\tfor (i = n - 1; i >= 0; i--)\n+\t\t{\n+\t\t\tif (strcmp(keywords[i], \"application_name\") == 0)\n+\t\t\t{\n+\t\t\t\tparse_pgfdw_appname(&buf, values[i]);\n+\t\t\t\tvalues[i] = buf.data;\n+\t\t\t\tbreak;\n+\t\t\t}\n\npostgres_fdw gets out of the loop after processing appname even\nwhen buf.data is '\\0'. Is this expected behavior? Because of this,\nwhen postgres_fdw.application_name = '%b', unprocessed appname\nof the server object is used.\n\n\n+CREATE FUNCTION for_escapes() RETURNS bool AS $$\n+ DECLARE\n+ appname text;\n+ c bool;\n+ BEGIN\n+ SHOW application_name INTO appname;\n+ EXECUTE 'SELECT COUNT(*) FROM pg_stat_activity WHERE application_name LIKE '''\n\nCould you tell me why the statement checking\napplication_name should be wrapped in a function?\nInstead, we can just execute something like the following?\n\nSELECT COUNT(*) FROM pg_stat_activity WHERE application_name = current_setting('application_name') || current_user || current_database() || pg_backend_pid() || '%';\n\n\n+\t\t\tchar *endptr = NULL;\n+\t\t\tpadding = (int)strtol(p, &endptr, 10);\n\nstrtol() seems to work differently from process_log_prefix_padding(),\nfor example, when the input string is \"%-p\".\n\n\n+\t\t\tcase 'a':\n+\t\t\t\t{\n+\t\t\t\t\tconst char *appname = application_name;\n\nWhen log_line_prefix() processes \"%a\", \"%u\" or \"%d\" characters in\nlog_line_prefix, it checks whether MyProcPort is NULL or not.\nLikewise shouldn't parse_pgfdw_appname() do the same thing?\nFor now it's ok not to check that because only process having\nMyProcPort can use postgres_fdw. But in the future the process\nnot having that may use postgres_fdw, for example, 2PC resolver\nprocess that Sawada-san is proposing to add to support automatic\n2PC among multiple remote servers.\n\n\n+ You can use escape sequences for <literal>application_name</literal> even if\n+ it is set as a connection or a user mapping option.\n+ Please refer the later section.\n\nI was thinking that application_name cannot be set in a user mapping.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 9 Sep 2021 16:11:50 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san,\n\nThank you for reviewing!\n\n> postgres_fdw gets out of the loop after processing appname even\n> when buf.data is '\\0'. Is this expected behavior? Because of this,\n> when postgres_fdw.application_name = '%b', unprocessed appname\n> of the server object is used.\n\nIn this case, I expected to use fallback_application_name instead of appname,\nbut I missed the case where appname was set as a server option.\nMaybe we should do continue when buf.data is \\0.\n\n> +\t\t\tchar *endptr = NULL;\n> +\t\t\tpadding = (int)strtol(p, &endptr, 10);\n> \n> strtol() seems to work differently from process_log_prefix_padding(),\n> for example, when the input string is \"%-p\".\n\nYeah, and I found that \"%+5p\" is another example.\nOur padding function does not understand plus sign\n(and maybe this is the specification of printf()), but strtol() reads.\n\nI did not fix here because I lost my way. Do we treats these cases\nand continue to use strtol(), or use process_padding()?\n\n> Could you tell me why the statement checking\n> application_name should be wrapped in a function?\n> Instead, we can just execute something like the following?\n> \n> SELECT COUNT(*) FROM pg_stat_activity WHERE application_name =\n> current_setting('application_name') || current_user || current_database() ||\n> pg_backend_pid() || '%';\n\nI did not know current_setting() function...\nThe function was replaced as you expected.\n\n> When log_line_prefix() processes \"%a\", \"%u\" or \"%d\" characters in\n> log_line_prefix, it checks whether MyProcPort is NULL or not.\n> Likewise shouldn't parse_pgfdw_appname() do the same thing?\n> For now it's ok not to check that because only process having\n> MyProcPort can use postgres_fdw. But in the future the process\n> not having that may use postgres_fdw, for example, 2PC resolver\n> process that Sawada-san is proposing to add to support automatic\n> 2PC among multiple remote servers.\n\nSure, I did not consider about other patches. I added checks.\n\n> + You can use escape sequences for <literal>application_name</literal>\n> even if\n> + it is set as a connection or a user mapping option.\n> + Please refer the later section.\n> \n> I was thinking that application_name cannot be set in a user mapping.\n\nI confirmed codes and found that is_valid_option() returns false\nif libpq options are set. So removed.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Thu, 9 Sep 2021 12:36:16 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/09/09 21:36, kuroda.hayato@fujitsu.com wrote:\n> In this case, I expected to use fallback_application_name instead of appname,\n> but I missed the case where appname was set as a server option.\n> Maybe we should do continue when buf.data is \\0.\n\nYes.\n\n+\t\t\t\t/*\n+\t\t\t\t * If the input format is wrong and the string becomes '\\0',\n+\t\t\t\t * this parameter is no longer used.\n+\t\t\t\t * We conitnue searching application_name.\n+\t\t\t\t */\n+\t\t\t\tif (values[i] == '\\0')\n+\t\t\t\t\tcontinue;\n+\t\t\t\telse\n+\t\t\t\t\tbreak;\n\nWe can simplify the code as follows.\n\n if (values[i] != '\\0')\n break;\n\n> Yeah, and I found that \"%+5p\" is another example.\n> Our padding function does not understand plus sign\n> (and maybe this is the specification of printf()), but strtol() reads.\n> \n> I did not fix here because I lost my way. Do we treats these cases\n> and continue to use strtol(), or use process_padding()?\n\nIMO it's better to use process_padding() to process log_line_prefix and\npostgres_fdw.application in the same way as possible.\nWhich would be less confusing.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Fri, 10 Sep 2021 09:23:45 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san,\n\nThank you for quick reviewing!\n\n> We can simplify the code as follows.\n> \n> if (values[i] != '\\0')\n> break;\n\nFixed. And type mismatching was also fixed.\n\n> IMO it's better to use process_padding() to process log_line_prefix and\n> postgres_fdw.application in the same way as possible.\n> Which would be less confusing.\n\nOK, I followed that. Some comments were added above the function.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Fri, 10 Sep 2021 03:24:11 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "", "msg_date": "Fri, 10 Sep 2021 03:35:39 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "Dear Hou,\n\n> I found one minor thing in the patch.\n\nThanks!\n\n> Is it better to use Abs(padding) here ?\n> Although some existing codes are using \" padding > 0 ? padding : -padding \".\n\n+1, fixed.\n\nAnd I found that some comments were not added above padding calculation,\nso added.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Fri, 10 Sep 2021 04:33:53 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "At Fri, 10 Sep 2021 04:33:53 +0000, \"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com> wrote in \n> Dear Hou,\n> \n> > I found one minor thing in the patch.\n> \n> Thanks!\n> \n> > Is it better to use Abs(padding) here ?\n> > Although some existing codes are using \" padding > 0 ? padding : -padding \".\n> \n> +1, fixed.\n> \n> And I found that some comments were not added above padding calculation,\n> so added.\n\nThanks for the new version. I don't object for reusing\nprocess_log_prefix_padding, but I still find it strange that the\nfunction with the name 'process_padding' is in string.c. If we move\nit to string.c, I'd like to name it \"pg_fast_strtoi\" or something and\nchange the interface to int pg_fast_strtoi(const char *p, char\n**endptr) that is (roughly) compatible to strtol. What do (both) you\nthink about this?\n\n\n+\t\t/*\n+\t\t * Search application_name and replace it if found.\n+\t\t *\n+\t\t * We search paramters from the end because the later\n+\t\t * one have higher priority. See also the above comment.\n+\t\t */\n+\t\tfor (i = n - 1; i >= 0; i--)\n+\t\t{\n+\t\t\tif (strcmp(keywords[i], \"application_name\") == 0)\n+\t\t\t{\n+\t\t\t\tparse_pgfdw_appname(&buf, values[i]);\n+\t\t\t\tvalues[i] = buf.data;\n+\n+\t\t\t\t/*\n+\t\t\t\t * If the input format is wrong and the string becomes '\\0',\n+\t\t\t\t * this parameter is no longer used.\n+\t\t\t\t * We conitnue searching application_name.\n+\t\t\t\t */\n+\t\t\t\tif (*values[i] != '\\0')\n+\t\t\t\t\tbreak;\n+\t\t\t}\n+\t\t}\n\nI didn't fully checked in what case parse_pgfdw_appname gives \"\" as\nresult, I feel that we should use the original value in that\ncase. That is,\n\n> parse_pgfdw_appname(&buf, vaues[i]);\n>\n> /* use the result if any, otherwise use the original string */\n> if (buf.data[0] != 0)\n> values[i] = buf.data;\n>\n> /* break if it results in non-empty string */\n> if (values[0][0] != 0)\n> break;\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Mon, 13 Sep 2021 16:12:47 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Horiguchi-san,\n\nThank you for giving comments!\n\n> Thanks for the new version. I don't object for reusing\n> process_log_prefix_padding, but I still find it strange that the\n> function with the name 'process_padding' is in string.c. If we move\n> it to string.c, I'd like to name it \"pg_fast_strtoi\" or something and\n> change the interface to int pg_fast_strtoi(const char *p, char\n> **endptr) that is (roughly) compatible to strtol. What do (both) you\n> think about this?\n\nI agree that this interface might be confused.\nI changed its name and interface. How do you think?\nActually I cannot distinguish the name is good or not,\nbut I could not think of anything else...\n\n> I didn't fully checked in what case parse_pgfdw_appname gives \"\" as\n> result, I feel that we should use the original value in that\n> case. That is,\n> \n> > parse_pgfdw_appname(&buf, vaues[i]);\n> >\n> > /* use the result if any, otherwise use the original string */\n> > if (buf.data[0] != 0)\n> > values[i] = buf.data;\n> >\n> > /* break if it results in non-empty string */\n> > if (values[0][0] != 0)\n> > break;\n\nHmm. I tested log_line_prefix() by setting it as '%z'\nand I found that any prefixes were not output.\nI think we should follow it, so currently not fixed.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Tue, 14 Sep 2021 04:42:14 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/09/14 13:42, kuroda.hayato@fujitsu.com wrote:\n> Dear Horiguchi-san,\n> \n> Thank you for giving comments!\n> \n>> Thanks for the new version. I don't object for reusing\n>> process_log_prefix_padding, but I still find it strange that the\n>> function with the name 'process_padding' is in string.c. If we move\n>> it to string.c, I'd like to name it \"pg_fast_strtoi\" or something and\n>> change the interface to int pg_fast_strtoi(const char *p, char\n>> **endptr) that is (roughly) compatible to strtol. What do (both) you\n>> think about this?\n> \n> I agree that this interface might be confused.\n> I changed its name and interface. How do you think?\n> Actually I cannot distinguish the name is good or not,\n> but I could not think of anything else...\n\nThe name using the word \"strtoint\" sounds confusing to me\nbecause the behavior of the function is different from strtoint() or\npg_strtoint32(), etc. Otherwise we can easily misunderstand that\npg_fast_strtoint() can be used as alternative of strtoint() or\npg_strtoint32(). I have no better idea for the name, though..\n\n\n> \n>> I didn't fully checked in what case parse_pgfdw_appname gives \"\" as\n>> result, I feel that we should use the original value in that\n>> case. That is,\n>>\n>>> parse_pgfdw_appname(&buf, vaues[i]);\n>>>\n>>> /* use the result if any, otherwise use the original string */\n>>> if (buf.data[0] != 0)\n>>> values[i] = buf.data;\n>>>\n>>> /* break if it results in non-empty string */\n>>> if (values[0][0] != 0)\n>>> break;\n\nAgreed. It's strange to use the application_name of the server\nobject in that case. There seems to be four options:\n\n(1) Use the original postgres_fdw.application_name like \"%b\"\n(2) Use the application_name of the server object (if set)\n(3) Use fallback_application_name\n(4) Use empty string as application_name\n\n(2) and (3) look strange to me because we expect that\npostgres_fdw.application_name should override application_name\nof the server object and fallback_application_mame.\n\nAlso reporting invalid escape sequence in application_name as it is,\ni.e., (1), looks strange to me.\n\nSo (4) looks most intuitive and similar behavior to log_line_prefix.\nThought?\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Wed, 15 Sep 2021 18:05:59 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san,\n\nThanks for comments!\n\n> >> Thanks for the new version. I don't object for reusing\n> >> process_log_prefix_padding, but I still find it strange that the\n> >> function with the name 'process_padding' is in string.c. If we move\n> >> it to string.c, I'd like to name it \"pg_fast_strtoi\" or something and\n> >> change the interface to int pg_fast_strtoi(const char *p, char\n> >> **endptr) that is (roughly) compatible to strtol. What do (both) you\n> >> think about this?\n> >\n> > I agree that this interface might be confused.\n> > I changed its name and interface. How do you think?\n> > Actually I cannot distinguish the name is good or not,\n> > but I could not think of anything else...\n> \n> The name using the word \"strtoint\" sounds confusing to me\n> because the behavior of the function is different from strtoint() or\n> pg_strtoint32(), etc. Otherwise we can easily misunderstand that\n> pg_fast_strtoint() can be used as alternative of strtoint() or\n> pg_strtoint32(). I have no better idea for the name, though..\n\nyou mean that this is not strtoXXX, right? If so we should\ngo back to process_padding().... Horiguchi-san, do you have any idea?\n\nAnd I added pg_restrict keywords for compiler optimizations.\n\n> >> I didn't fully checked in what case parse_pgfdw_appname gives \"\" as\n> >> result, I feel that we should use the original value in that\n> >> case. That is,\n> >>\n> >>> parse_pgfdw_appname(&buf, vaues[i]);\n> >>>\n> >>> /* use the result if any, otherwise use the original string */\n> >>> if (buf.data[0] != 0)\n> >>> values[i] = buf.data;\n> >>>\n> >>> /* break if it results in non-empty string */\n> >>> if (values[0][0] != 0)\n> >>> break;\n> \n> Agreed. It's strange to use the application_name of the server\n> object in that case. There seems to be four options:\n> \n> (1) Use the original postgres_fdw.application_name like \"%b\"\n> (2) Use the application_name of the server object (if set)\n> (3) Use fallback_application_name\n> (4) Use empty string as application_name\n> \n> (2) and (3) look strange to me because we expect that\n> postgres_fdw.application_name should override application_name\n> of the server object and fallback_application_mame.\n> \n> Also reporting invalid escape sequence in application_name as it is,\n> i.e., (1), looks strange to me.\n> \n> So (4) looks most intuitive and similar behavior to log_line_prefix.\n> Thought?\n\nI agreed that (2) and (3) breaks the rule which should override server option.\nHence I chose (4), values[i] substituted to buf.data in any case.\n\nAttached is the latest version.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Thu, 16 Sep 2021 03:36:19 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/09/16 12:36, kuroda.hayato@fujitsu.com wrote:\n> you mean that this is not strtoXXX, right?\n\nYes, the behavior of process_log_prefix_padding() is different from\nstrtoint() or pg_strtoint32(). For example, how the heading space\ncharacters are handled is different. If we use the name like\npg_fast_strtoint(), we might be likely to replace the existing strtoint()\nor pg_strtoint32() with pg_fast_strtoint() because its name contains\n\"fast\", for better performance. But we should not do that because\ntheir behavior is different.\n\n> If so we should\n> go back to process_padding().... Horiguchi-san, do you have any idea?\n\nAt least for me process_padding() sounds like the function is actually\ndoing the padding operation. This is not what the function does.\nSo how about something like parse_padding(), parse_padding_format()?\n\n> And I added pg_restrict keywords for compiler optimizations.\n\nI'm not sure how much it's worth doing this here. If this change is helpful\nfor better performance or something, IMO it's better to propose this\nseparately.\n\n> I agreed that (2) and (3) breaks the rule which should override server option.\n> Hence I chose (4), values[i] substituted to buf.data in any case.\n> \n> Attached is the latest version.\n\nThanks! Will review the patch.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 16 Sep 2021 14:44:39 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san, Horiguchi-san,\n\nBased on your advice, I made a patch\nthat communize two parsing functions into one.\nnew internal function parse_format_string() was added.\n(This name may be too generic...)\nlog_line_prefix() and parse_pgfdw_appname() become just the wrapper function.\nMy prerpimary checking was passed for server and postgres_fdw,\nbut could you review that?\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Tue, 21 Sep 2021 06:08:29 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/09/21 15:08, kuroda.hayato@fujitsu.com wrote:\n> Dear Fujii-san, Horiguchi-san,\n> \n> Based on your advice, I made a patch\n> that communize two parsing functions into one.\n> new internal function parse_format_string() was added.\n> (This name may be too generic...)\n> log_line_prefix() and parse_pgfdw_appname() become just the wrapper function.\n> My prerpimary checking was passed for server and postgres_fdw,\n> but could you review that?\n\nYes. Thanks for updating the patch!\n\n-------------------\nelog.c:2785:14: warning: expression which evaluates to zero treated as a null pointer constant of type 'char *' [-Wnon-literal-null-conversion]\n *endptr = '\\0';\n ^~~~\n1 warning generated.\n-------------------\n\nI got the above compiler warning.\n\n\n+ * Note: StringInfo datatype cannot be accepted\n+ * because elog.h should not include postgres-original header file.\n\nHow about moving the function to guc.c from elog.c because it's for\nthe parameters, i.e., log_line_prefix and postgres_fdw.application_name?\nThis allows us to use StringInfo in the function?\n\n\n+\t\t\t\tparse_pgfdw_appname(buf, values[i]);\n+\t\t\t\t/*\n+\t\t\t\t * Note that appname may becomes an empty string\n+\t\t\t\t * if an input string has wrong format.\n+\t\t\t\t */\n+\t\t\t\tvalues[i] = *buf;\n\nIf postgres_fdw.application_name contains only invalid escape characters like\n\"%b\", parse_pgfdw_appname() returns an empty string. We discussed\nthere are four options to handle this case and we concluded (4) is better.\nRight? But ISTM that the patch uses (2).\n\n> (1) Use the original postgres_fdw.application_name like \"%b\"\n> (2) Use the application_name of the server object (if set)\n> (3) Use fallback_application_name\n> (4) Use empty string as application_name\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Fri, 24 Sep 2021 14:10:37 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san, Horiguchi-san\n\nI'm sorry for sending a bad patch...\n\n> -------------------\n> elog.c:2785:14: warning: expression which evaluates to zero treated as a null\n> pointer constant of type 'char *' [-Wnon-literal-null-conversion]\n> *endptr = '\\0';\n> ^~~~\n> 1 warning generated.\n> -------------------\n> \n> I got the above compiler warning.\n\nFixed. *endptr points (char *)p in any cases, that means\nthis parameter is invalid.\n\n> + * Note: StringInfo datatype cannot be accepted\n> + * because elog.h should not include postgres-original header file.\n> \n> How about moving the function to guc.c from elog.c because it's for\n> the parameters, i.e., log_line_prefix and postgres_fdw.application_name?\n> This allows us to use StringInfo in the function?\n\nYeah, StringInfo can be used in guc.c. Hence moved it.\nSome variables and functions for timestamp became non-static function,\nbecause they were used both normal logging and log_line_prefix.\nI think their name is not too generic so I did not fix them.\n\n> +\t\t\t\tparse_pgfdw_appname(buf, values[i]);\n> +\t\t\t\t/*\n> +\t\t\t\t * Note that appname may becomes an empty\n> string\n> +\t\t\t\t * if an input string has wrong format.\n> +\t\t\t\t */\n> +\t\t\t\tvalues[i] = *buf;\n> \n> If postgres_fdw.application_name contains only invalid escape characters like\n> \"%b\", parse_pgfdw_appname() returns an empty string. We discussed\n> there are four options to handle this case and we concluded (4) is better.\n> Right? But ISTM that the patch uses (2).\n> \n> > (1) Use the original postgres_fdw.application_name like \"%b\"\n> > (2) Use the application_name of the server object (if set)\n> > (3) Use fallback_application_name\n> > (4) Use empty string as application_name\n\nYeah, currently my patch uses case (2). I tried to implement (4),\nbut I found that libpq function(may be conninfo_array_parse()) must be modified in order to that.\nWe moved the functionality to libpq layer because we want to avoid some side effects,\nso we started to think case (4) might be wrong.\n\nNow we propose the following senario:\n1. Use postgres_fdw.application_name when it is set and the parsing result is not empty\n2. If not, use the foreign-server option when it is set and the parsing result is not empty\n3. If not, use fallback_application_name\n\nHow do you think?\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Mon, 27 Sep 2021 04:10:50 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "At Mon, 27 Sep 2021 04:10:50 +0000, \"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com> wrote in \n> I'm sorry for sending a bad patch...\n\nThank you for the new version, and sorry for making the discussion go\nback and forth:p\n\n> > + * Note: StringInfo datatype cannot be accepted\n> > + * because elog.h should not include postgres-original header file.\n> > \n> > How about moving the function to guc.c from elog.c because it's for\n> > the parameters, i.e., log_line_prefix and postgres_fdw.application_name?\n> > This allows us to use StringInfo in the function?\n> \n> Yeah, StringInfo can be used in guc.c. Hence moved it.\n> Some variables and functions for timestamp became non-static function,\n> because they were used both normal logging and log_line_prefix.\n> I think their name is not too generic so I did not fix them.\n> \n> > +\t\t\t\tparse_pgfdw_appname(buf, values[i]);\n> > +\t\t\t\t/*\n> > +\t\t\t\t * Note that appname may becomes an empty\n> > string\n> > +\t\t\t\t * if an input string has wrong format.\n> > +\t\t\t\t */\n> > +\t\t\t\tvalues[i] = *buf;\n> > \n> > If postgres_fdw.application_name contains only invalid escape characters like\n> > \"%b\", parse_pgfdw_appname() returns an empty string. We discussed\n> > there are four options to handle this case and we concluded (4) is better.\n> > Right? But ISTM that the patch uses (2).\n> > \n> > > (1) Use the original postgres_fdw.application_name like \"%b\"\n> > > (2) Use the application_name of the server object (if set)\n> > > (3) Use fallback_application_name\n> > > (4) Use empty string as application_name\n> \n> Yeah, currently my patch uses case (2). I tried to implement (4),\n> but I found that libpq function(may be conninfo_array_parse()) must be modified in order to that.\n> We moved the functionality to libpq layer because we want to avoid some side effects,\n> so we started to think case (4) might be wrong.\n> \n> Now we propose the following senario:\n> 1. Use postgres_fdw.application_name when it is set and the parsing result is not empty\n> 2. If not, use the foreign-server option when it is set and the parsing result is not empty\n> 3. If not, use fallback_application_name\n> \n> How do you think?\n\nI think we don't have a predecessor of the case like this where a\nbehavior is decided from object option and GUC.\n\nI'm a bit uncomfortable with .conf configuration overrides server\noptions, but I also think in-session-set GUC should override server\noptions. So, it's slightly against POLA but from the standpoint of\nusability +0.5 to that prioritization since I cannot come up with a\nbetter idea.\n\n\nI thought it is nice to share process_format_string but the function\nis too tightly coupled with ErrorData detail as you pointed off-list.\nSo I came to think we cannot use the function from outside. It could\nbe a possibility to make the function be just a skeleton that takes a\nlist of pairs of an escaped character and the associated callback\nfunction but that is apparently too-much complex. (It would be worth\ndoing if we share the same backbone processing with archive_command,\nrestore_command, recover_end_command and so on, but that is\nnecessarily accompanied by the need to change the behavior either\nlog_line_prefix or others.)\n\nI personally don't care even if this feature implements\npadding-reading logic differently from process_format_string, but if\nwe don't like that, I would return to suggest using strtol in both\nfunctions.\n\nAs Fujii-san pointed upthread, strtol behaves a bit different way than\nwe expect here, but that can be handled by checking the starting\ncharacters.\n\n>\t\tif (*p == '-' ? isdigit(p[1]) : isdigit(p[0]))\n>\t\t{\n>\t\t\tchar *endptr;\n>\t\t\tpadding = strtol(p, &endptr, 10);\n>\t\t\tif (p == endptr)\n>\t\t\t\tbreak;\n>\t\t\tp = endptr;\n>\t\t}\n>\t\telse\n>\t\t\tpadding = 0;\n\nThe code gets a bit more complex but simplification by removing the\nhelper function wins. strtol is slower than the original function but\nit can be thought in noise-level? isdigit on some platforms seems\nfollowing locale, but it is already widely used for example while\nnumeric parsing so I don't think that matters. (Of course we can get\nrid of isdigit by using bare comparisons.)\n\nI think it can be a separate preparatory patch of this patch.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 01 Oct 2021 11:23:33 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "At Fri, 01 Oct 2021 11:23:33 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> function but that is apparently too-much complex. (It would be worth\n> doing if we share the same backbone processing with archive_command,\n> restore_command, recover_end_command and so on, but that is\n> necessarily accompanied by the need to change the behavior either\n> log_line_prefix or others.)\n\nSo I was daydreaming over the idea and concluded as it is no-go.\n\nI said that the fdw-application name is close to archive_command\nrather than log_line_prefix, but that is totally missing the point.\nlog_line_prefix and the fdw-application name share the concept of\nformatting, which is not a part of archive_command and friends.\n\nThe latter is made very light weight and simple due to not only the\nformatless-ness but also the narrow choices of escape characters. Also\nthey work on fixed-length buffer instead of StringInfo.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 01 Oct 2021 16:40:36 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Horiguchi-san,\n\nThank you for giving many comments! I attached new patches.\nI'm sorry for the late reply.\n\n> I think we don't have a predecessor of the case like this where a\n> behavior is decided from object option and GUC.\n> \n> I'm a bit uncomfortable with .conf configuration overrides server\n> options, but I also think in-session-set GUC should override server\n> options. So, it's slightly against POLA but from the standpoint of\n> usability +0.5 to that prioritization since I cannot come up with a\n> better idea.\n\nOK, I keep the current spec. Please tell me if you come up with something.\n\n> I thought it is nice to share process_format_string but the function\n> is too tightly coupled with ErrorData detail as you pointed off-list.\n> So I came to think we cannot use the function from outside. It could\n> be a possibility to make the function be just a skeleton that takes a\n> list of pairs of an escaped character and the associated callback\n> function but that is apparently too-much complex. (It would be worth\n> doing if we share the same backbone processing with archive_command,\n> restore_command, recover_end_command and so on, but that is\n> necessarily accompanied by the need to change the behavior either\n> log_line_prefix or others.)\n\nI agree that combining them makes source too complex.\nAnd we have an another problem about native language support.\nSometimes espaces becomes \"[unkown]\" string in log_line_prefix(),\nand they are gettext()'s target. So if we combine log_line_prefix() and parse_pgfdw_appname(),\nsome non-ascii characters may be set to postgres_fdw.applicaiton_name.\nOf cause we can implement callback function, but I think it is the next step.\n\n> I personally don't care even if this feature implements\n> padding-reading logic differently from process_format_string, but if\n> we don't like that, I would return to suggest using strtol in both\n> functions.\n> \n> As Fujii-san pointed upthread, strtol behaves a bit different way than\n> we expect here, but that can be handled by checking the starting\n> characters.\n\n>\t\tif (*p == '-' ? isdigit(p[1]) : isdigit(p[0]))\n>\t\t{\n>\t\t\tchar *endptr;\n>\t\t\tpadding = strtol(p, &endptr, 10);\n>\t\t\tif (p == endptr)\n>\t\t\t\tbreak;\n>\t\t\tp = endptr;\n>\t\t}\n>\t\telse\n>\t\t\tpadding = 0;\n\nI removed the support function based on your suggestion,\nbut added some if-statement in order to treats the special case: '%-p'.\n\nAnd I found and fixed another bug. If users set application_name \nboth in server option and GUC, concatenated string was set as appname.\nThis is caused because we reused same StringInfo and parsing all appname string\neven if we sucsess it. Now the array search will stop if sucseed,\nand in failure case do resetStringInfo() and re-search.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Mon, 4 Oct 2021 12:53:49 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/10/04 21:53, kuroda.hayato@fujitsu.com wrote:\n>> \t\tif (*p == '-' ? isdigit(p[1]) : isdigit(p[0]))\n>> \t\t{\n>> \t\t\tchar *endptr;\n>> \t\t\tpadding = strtol(p, &endptr, 10);\n>> \t\t\tif (p == endptr)\n>> \t\t\t\tbreak;\n>> \t\t\tp = endptr;\n>> \t\t}\n>> \t\telse\n>> \t\t\tpadding = 0;\n> \n> I removed the support function based on your suggestion,\n> but added some if-statement in order to treats the special case: '%-p'.\n\n+\t\telse if (*p == '-' ? isdigit(p[1]) : isdigit(p[0]))\n+\t\t{\n+\t\t\tchar *endptr;\n+\t\t\tpadding = strtol(p, &endptr, 10);\n\nMaybe isdigit() and strtol() work differently depending on locale setting?\nIf so, I'm afraid that the behavior of this new code would be different from\nprocess_log_prefix_padding().\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Wed, 6 Oct 2021 01:25:00 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san,\n\nThank you for reviewing!\n\n> +\t\telse if (*p == '-' ? isdigit(p[1]) : isdigit(p[0]))\n> +\t\t{\n> +\t\t\tchar *endptr;\n> +\t\t\tpadding = strtol(p, &endptr, 10);\n> \n> Maybe isdigit() and strtol() work differently depending on locale setting?\n> If so, I'm afraid that the behavior of this new code would be different from\n> process_log_prefix_padding().\n\n(Maybe strtol() should be strtoint(). This is my fault... but anyway)\nYou afraid that these functions may return non-zero value if locale is not \"C\"\nand inputs are non-ascii characters?\nI read the POSIX specification(isdigit: [1], strtol: [2]) and I found that\nit suggests such functions are affected by locale settings.\n\nFor isdigit():\n> The isdigit() and isdigit_l() functions shall test whether c is a character of class digit in the current locale, \n> or in the locale represented by locale, respectively; see XBD Locale.\n\nFor strtol()\n> In other than the C or POSIX locale, additional locale-specific subject sequence forms may be accepted.\n\nI seeked other sources, but I thought that they did not consider about\nlocale settings. For example, functions in numutils.c are use such functions\nwithout any locale consideration.\n\nAnd I considered executing setlocale(LC_CTYPE, \"C\"), but I found\nthe following comment pg_locale.c and I did not want to violate the policy.\n\n> * Here is how the locale stuff is handled: LC_COLLATE and LC_CTYPE\n> * are fixed at CREATE DATABASE time, stored in pg_database, and cannot\n> * be changed. Thus, the effects of strcoll(), strxfrm(), isupper(),\n> * toupper(), etc. are always in the same fixed locale.\n\nBut isdigit() and strtol() cannot accept multi byte character,\nso I also thought we don't have to consider\nthat some unexpected character is set in LC_CTYPE digit category.\n\nSo now we can choose from followings:\n\n* ignore such differences and use isdigit() and strtol()\n* give up using them and implement two static support functions\n\nHow do you think? Someone knows any other knowledge about locale?\n\n[1]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/isdigit.html\n[2]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtol.html\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED\n\n\n\n", "msg_date": "Thu, 7 Oct 2021 02:46:36 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/10/07 11:46, kuroda.hayato@fujitsu.com wrote:\n> So now we can choose from followings:\n> \n> * ignore such differences and use isdigit() and strtol()\n> * give up using them and implement two static support functions\n> \n> How do you think? Someone knows any other knowledge about locale?\n\nReplacing process_log_prefix_padding() with isdigit()+strtol() is\njust refactoring and doesn't provide any new feature. So they\nbasically should work in the same way. If the behavior of isdigit()+strtol()\ncan be different from process_log_prefix_padding(), I'd prefer to\nthe latter option you suggested, i.e., give up using isdigit()+strtol().\n\nOTOH, of course if the behaviors of them are the same,\nI'm ok to use isdigit()+strtol(), though.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Tue, 12 Oct 2021 13:25:01 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "At Tue, 12 Oct 2021 13:25:01 +0900, Fujii Masao <masao.fujii@oss.nttdata.com> wrote in \n> \n> \n> On 2021/10/07 11:46, kuroda.hayato@fujitsu.com wrote:\n> > So now we can choose from followings:\n> >* ignore such differences and use isdigit() and strtol()\n> > * give up using them and implement two static support functions\n> >How do you think? Someone knows any other knowledge about locale?\n> \n> Replacing process_log_prefix_padding() with isdigit()+strtol() is\n> just refactoring and doesn't provide any new feature. So they\n> basically should work in the same way. If the behavior of\n> isdigit()+strtol()\n> can be different from process_log_prefix_padding(), I'd prefer to\n> the latter option you suggested, i.e., give up using\n> isdigit()+strtol().\n> \n> OTOH, of course if the behaviors of them are the same,\n> I'm ok to use isdigit()+strtol(), though.\n\nHmm. It look like behaving a bit xdifferently. At least for example,\nfor \"%-X\", current code treats it as 0 padding but the patch treats it\nas -1.\n\nBy the way, the current code is already a kind of buggy. I think I\nshowed an example like:\n\n\"%4%5%6%7p\" is converted to \"57p\". Do we need to imitate that bug\nwith this patch?\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Tue, 12 Oct 2021 15:06:11 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "At Tue, 12 Oct 2021 15:06:11 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> \"%4%5%6%7p\" is converted to \"57p\". Do we need to imitate that bug\n> with this patch?\n\nSo.. I try to describe the behavior for exhaustive patterns..\n\ncurrent:\n A. \"^-?[0-9]+.*\" : returns valid padding. p goes after the last digit.\n B. \"^[^0-9-].*\" : padding = 0, p doesn't advance.\n C. \"^-[^0-9].*\" : padding = 0, p advances by 1 byte.\n D. \"^-\" : padding = 0, p advances by 1 byte.\n (if *p == 0 then breaks)\n\nI think the patterns covers the all possibilities.\n\nIf we code as the following:\n if (*p == '-' ? isdigit(p[1]) : isdigit(p[0]))\n\t\t{\n\t\t\tchar *endptr;\n\t\t\tpadding = strtol(p, &endptr, 10);\n\t\t\tAssert(endptr > p);\n\t\t\tif (*endptr == '\\0')\n\t\t\t\tbreak;\n\t\t\tp = endptr;\n\t\t}\n\t\telse\n padding = 0;\n\n A. \"^-?[0-9]+.*\" : same to the current\n B. \"^[^0-9-].*\" : same to the current\n C. \"^-[^0-9].*\" : padding = 0, p doesn't advance.\n D. \"^-\" : padding = 0, p doesn't advance.\n\nIf we wan to make the behaviors C and D same with the current, the\nelse clause should be like the follows, but I don't think we need to\ndo that.\n\n\t\telse\n\t\t{\n padding = 0;\n\t\t if (*p == '-')\n\t\t p++;\n \t }\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Tue, 12 Oct 2021 15:42:23 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "At Tue, 12 Oct 2021 15:42:23 +0900 (JST), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in \n> If we code as the following:\n...\n> A. \"^-?[0-9]+.*\" : same to the current\n> B. \"^[^0-9-].*\" : same to the current\n> C. \"^-[^0-9].*\" : padding = 0, p doesn't advance.\n> D. \"^-\" : padding = 0, p doesn't advance.\n\nOne possible cause of a difference in behavior is character class\nhandling including multibyte characters of isdigit and strtol. If\nisdigit accepts '一' as a digit (some platforms might do this) , and\nstrtol doesn't (I believe it is universal behavior), '%一0p' is\nconverted to '%' and the pointer moves onto '一'. But I don't think we\nneed to do something for such a crazy specification.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Tue, 12 Oct 2021 15:59:23 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Horiguchi-san, Fujii-san,\n\nPerfect work... Thank you for replying and analyzing! \n\n> A. \"^-?[0-9]+.*\" : returns valid padding. p goes after the last digit.\n> B. \"^[^0-9-].*\" : padding = 0, p doesn't advance.\n> C. \"^-[^0-9].*\" : padding = 0, p advances by 1 byte.\n> D. \"^-\" : padding = 0, p advances by 1 byte.\n> (if *p == 0 then breaks)\n\nI confirmed them and your patterns are correct.\n\n> If we wan to make the behaviors C and D same with the current, the\n> else clause should be like the follows, but I don't think we need to\n> do that.\n> \t\telse\n> \t\t{\n> padding = 0;\n> \t\t if (*p == '-')\n> \t\t p++;\n> \t }\n\nThis treatments is not complex so I want to add them if possible.\n\n> One possible cause of a difference in behavior is character class\n> handling including multibyte characters of isdigit and strtol. If\n> isdigit accepts '一' as a digit (some platforms might do this) , and\n> strtol doesn't (I believe it is universal behavior), '%一0p' is\n> converted to '%' and the pointer moves onto '一'. But I don't think we\n> need to do something for such a crazy specification.\n\nDoes isdigit() understand multi-byte character correctly? The arguments\nof isdigit() is just a unsigned char, and this is 1byte.\nHence I thought that they cannot distinguish 'ー'. \nActually I considered about another thing. Maybe isdigit() just checks \nwhether the value of the argument is in (int)48 and (int)57, and that means that\nthe first part of some multi-byte characters may be accepted as digit in some locales.\nBut, of cause I agreed this is the crazy case.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED\n\n\n\n", "msg_date": "Wed, 13 Oct 2021 11:05:19 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "> Does isdigit() understand multi-byte character correctly? The arguments\n> of isdigit() is just a unsigned char, and this is 1byte.\n> Hence I thought that they cannot distinguish 'ー'.\n\nSorry, but I referred some wrong doc. Please ignore here...\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED\n\n\n\n", "msg_date": "Wed, 13 Oct 2021 16:17:42 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "At Wed, 13 Oct 2021 11:05:19 +0000, \"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com> wrote in \n> Dear Horiguchi-san, Fujii-san,\n> \n> Perfect work... Thank you for replying and analyzing! \n> \n> > A. \"^-?[0-9]+.*\" : returns valid padding. p goes after the last digit.\n> > B. \"^[^0-9-].*\" : padding = 0, p doesn't advance.\n> > C. \"^-[^0-9].*\" : padding = 0, p advances by 1 byte.\n> > D. \"^-\" : padding = 0, p advances by 1 byte.\n> > (if *p == 0 then breaks)\n> \n> I confirmed them and your patterns are correct.\n\nThanks for the confirmation.\n\n> > If we wan to make the behaviors C and D same with the current, the\n> > else clause should be like the follows, but I don't think we need to\n> > do that.\n> > \t\telse\n> > \t\t{\n> > padding = 0;\n> > \t\t if (*p == '-')\n> > \t\t p++;\n> > \t }\n> \n> This treatments is not complex so I want to add them if possible.\n\nAlso I don't oppose to do that.\n\n> > One possible cause of a difference in behavior is character class\n> > handling including multibyte characters of isdigit and strtol. If\n> > isdigit accepts '一' as a digit (some platforms might do this) , and\n> > strtol doesn't (I believe it is universal behavior), '%一0p' is\n> > converted to '%' and the pointer moves onto '一'. But I don't think we\n> > need to do something for such a crazy specification.\n> \n> Does isdigit() understand multi-byte character correctly? The arguments\n> of isdigit() is just a unsigned char, and this is 1byte.\n> Hence I thought that they cannot distinguish 'ー'.\n..\n> Sorry, but I referred some wrong doc. Please ignore here...\n\nI'm not sure. All of it is a if-story. z/OS's isdigit is defined as\n\"Test for a decimal digit, as defined in the digit locale source file\nand in the digit class of the LC_CTYPE category of the current\nlocale.\", which I read it as \"it accepts multibyte strings\" but of\ncourse I'm not sure that's correct.\n\nOn CentOS8, and for Japanese letters, both iswdigit(L'ー') and\niswdigit(L'0') return false so, assuming the same character\nclassfication scheme that is implementation dependent, I guess z/OS's\nisdigit would behave the same way with CentOS's isdigit.\n\nHoever, regardless of the precise behavior,\n\n> But, of cause I agreed this is the crazy case.\n\nYes, I meant that that doesn't matter.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Thu, 14 Oct 2021 10:09:56 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Horiguchi-san,\n\n> I'm not sure. All of it is a if-story. z/OS's isdigit is defined as\n> \"Test for a decimal digit, as defined in the digit locale source file\n> and in the digit class of the LC_CTYPE category of the current\n> locale.\", which I read it as \"it accepts multibyte strings\" but of\n> course I'm not sure that's correct.\n> \n> On CentOS8, and for Japanese letters, both iswdigit(L'ー') and\n> iswdigit(L'0') return false so, assuming the same character\n> classfication scheme that is implementation dependent, I guess z/OS's\n> isdigit would behave the same way with CentOS's isdigit.\n> \n> Hoever, regardless of the precise behavior,\n> \n> > But, of cause I agreed this is the crazy case.\n> \n> Yes, I meant that that doesn't matter.\n\nHmm.. of cause I want to do because I believe this is corner case,\nbut we should avoid regression...\nIf no one can say it completely some existing methods probably should be used. \nTherefore, I would like to suggest using the export and support functions again.\nThe name is converted to parse_XXX and it locates in elog.c. How is it?\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Fri, 15 Oct 2021 08:45:10 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/10/15 17:45, kuroda.hayato@fujitsu.com wrote:\n> Dear Horiguchi-san,\n> \n>> I'm not sure. All of it is a if-story. z/OS's isdigit is defined as\n>> \"Test for a decimal digit, as defined in the digit locale source file\n>> and in the digit class of the LC_CTYPE category of the current\n>> locale.\", which I read it as \"it accepts multibyte strings\" but of\n>> course I'm not sure that's correct.\n>>\n>> On CentOS8, and for Japanese letters, both iswdigit(L'\u001b$B!<\u001b(B') and\n>> iswdigit(L'\u001b$B#0\u001b(B') return false so, assuming the same character\n>> classfication scheme that is implementation dependent, I guess z/OS's\n>> isdigit would behave the same way with CentOS's isdigit.\n>>\n>> Hoever, regardless of the precise behavior,\n>>\n>>> But, of cause I agreed this is the crazy case.\n>>\n>> Yes, I meant that that doesn't matter.\n> \n> Hmm.. of cause I want to do because I believe this is corner case,\n> but we should avoid regression...\n> If no one can say it completely some existing methods probably should be used.\n> Therefore, I would like to suggest using the export and support functions again.\n\nOn second thought, do we really need padding support for application_name\nin postgres_fdw? I just thought that when I read the description\n\"Padding can be useful to aid human readability in log files.\" in the docs\nabout log_line_prefix.\n\n\n+\t\t\tcase 'a':\n+\t\t\t\tif (MyProcPort)\n+\t\t\t\t{\n\nI commented that the check of MyProcPort is necessary because background\nworker not having MyProcPort may access to the remote server. The example\nof such process is the resolver process that Sawada-san was proposing for\natomic commit feature. But the proposal was withdrawn and for now\nthere seems no such process. If this is true, we can safely remove the check\nof MyProcPort? If so, something like Assert(MyProcPort != NULL) may need\nto be added, instead.\n\n\n+\t\t\t\t\tif (username == NULL || *username == '\\0')\n+\t\t\t\t\t\tusername = \"[unknown]\";\n\nIf user name or database name is not set, the name is replaced with\n\"[unknown]\". log_line_prefix needs this because log message may be\noutput when they have not been set yet, e.g., at early stage of backend\nstartup. But I wonder if application_name in postgres_fdw actually\nneed that.. Thought?\n\n\n+\t\t\t\t\tif (appname == NULL || *appname == '\\0')\n+\t\t\t\t\t\tappname = \"[unknown]\";\n\nDo we really want to replace the application name with \"[unknown]\"\nwhen application_name in the local server is not set? At least for me,\nit's intuitive to replace it with empty string in that case,\nin postgres_fdw application_name.\n\n\nThe patch now fails to be applied to the master. Could you rebase it?\n\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Tue, 2 Nov 2021 17:27:35 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san,\n\nThank you for giving comments! I attached new patches.\n\n> On second thought, do we really need padding support for application_name\n> in postgres_fdw? I just thought that when I read the description\n> \"Padding can be useful to aid human readability in log files.\" in the docs\n> about log_line_prefix.\n\nMy feelings was that we don't have any reasons not to support,\nbut I cannot found some good use-cases.\nNow I decided to keep supporting that,\nbut if we face another problem I will cut that.\n\n> +\t\t\tcase 'a':\n> +\t\t\t\tif (MyProcPort)\n> +\t\t\t\t{\n> \n> I commented that the check of MyProcPort is necessary because background\n> worker not having MyProcPort may access to the remote server. The example\n> of such process is the resolver process that Sawada-san was proposing for\n> atomic commit feature. But the proposal was withdrawn and for now\n> there seems no such process. If this is true, we can safely remove the check\n> of MyProcPort? If so, something like Assert(MyProcPort != NULL) may need\n> to be added, instead.\n\nMy understating was that we don't have to assume committing the Sawada-san's patch.\nI think that FDW is only available from backend processes in the current implementation,\nand MyProcPort will be substituted when processes are initialized() - in BackendInitialize().\nSince the backend will execute BackendInitialize() after forking() from the postmaster,\nwe can assume that everyone who operates FDW has a valid value for MyProcPort.\nI removed if statement and added assertion.\nWe can force parse_pgfdw_appname() not to be called if MyProcPort does not exist,\nbut I don't think it is needed now.\n\n> If user name or database name is not set, the name is replaced with\n> \"[unknown]\". log_line_prefix needs this because log message may be\n> output when they have not been set yet, e.g., at early stage of backend\n> startup. But I wonder if application_name in postgres_fdw actually\n> need that.. Thought?\n\nHmm, I think all of backend processes have username and database, but\nhere has been followed from Horiguchi-san's suggestion:\n\n```\nI'm not sure but even if user_name doesn't seem to be NULL, don't we\nwant to do the same thing with %u of log_line_prefix for safety?\nNamely, setting [unknown] if user_name is NULL or \"\". The same can be\nsaid for %d.\n```\n\nBut actually I don't have strong opinions.\n\n> +\t\t\t\t\tif (appname == NULL || *appname\n> == '\\0')\n> +\t\t\t\t\t\tappname = \"[unknown]\";\n> \n> Do we really want to replace the application name with \"[unknown]\"\n> when application_name in the local server is not set? At least for me,\n> it's intuitive to replace it with empty string in that case,\n> in postgres_fdw application_name.\n\nYeah, I agreed that empty string should be keep here.\nCurrently I kept NULL case because of the above reason.\n\n> The patch now fails to be applied to the master. Could you rebase it?\n\nThanks, rebased. I just moved test to the end of the sql file.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Thu, 4 Nov 2021 11:42:37 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/11/04 20:42, kuroda.hayato@fujitsu.com wrote:\n> Dear Fujii-san,\n> \n> Thank you for giving comments! I attached new patches.\n\nThanks for updating the patch!\n\n+ <para>\n+ Note that if embedded strings have Non-ASCII,\n+ these characters will be replaced with the question marks (<literal>?</literal>).\n+ This limitation is caused by <literal>application_name</literal>.\n+ </para>\n\nIsn't this descripton confusing because postgres_fdw actually doesn't do this?\npostgres_fdw just passses the application_name as it is to the remote server.\n\n\n>> On second thought, do we really need padding support for application_name\n>> in postgres_fdw? I just thought that when I read the description\n>> \"Padding can be useful to aid human readability in log files.\" in the docs\n>> about log_line_prefix.\n> \n> My feelings was that we don't have any reasons not to support,\n> but I cannot found some good use-cases.\n> Now I decided to keep supporting that,\n> but if we face another problem I will cut that.\n\nI'd like to hear more opinions about this from others.\nBut *if* there is actually no use case, I'd like not to add\nthe feature, to make the code simpler.\n\n\n>> +\t\t\tcase 'a':\n>> +\t\t\t\tif (MyProcPort)\n>> +\t\t\t\t{\n>>\n>> I commented that the check of MyProcPort is necessary because background\n>> worker not having MyProcPort may access to the remote server. The example\n>> of such process is the resolver process that Sawada-san was proposing for\n>> atomic commit feature. But the proposal was withdrawn and for now\n>> there seems no such process. If this is true, we can safely remove the check\n>> of MyProcPort? If so, something like Assert(MyProcPort != NULL) may need\n>> to be added, instead.\n> \n> My understating was that we don't have to assume committing the Sawada-san's patch.\n> I think that FDW is only available from backend processes in the current implementation,\n> and MyProcPort will be substituted when processes are initialized() - in BackendInitialize().\n> Since the backend will execute BackendInitialize() after forking() from the postmaster,\n> we can assume that everyone who operates FDW has a valid value for MyProcPort.\n> I removed if statement and added assertion.\n\n+\t\t\tcase 'u':\n+\t\t\t\tAssert(MyProcPort != NULL);\n\nIsn't it enough to perform this assertion check only once\nat the top of parse_pgfdw_appname()?\n\n\n> We can force parse_pgfdw_appname() not to be called if MyProcPort does not exist,\n> but I don't think it is needed now.\n\nYes.\n\n\n>> If user name or database name is not set, the name is replaced with\n>> \"[unknown]\". log_line_prefix needs this because log message may be\n>> output when they have not been set yet, e.g., at early stage of backend\n>> startup. But I wonder if application_name in postgres_fdw actually\n>> need that.. Thought?\n> \n> Hmm, I think all of backend processes have username and database, but\n> here has been followed from Horiguchi-san's suggestion:\n> \n> ```\n> I'm not sure but even if user_name doesn't seem to be NULL, don't we\n> want to do the same thing with %u of log_line_prefix for safety?\n> Namely, setting [unknown] if user_name is NULL or \"\". The same can be\n> said for %d.\n> ```\n> \n> But actually I don't have strong opinions.\n\nOk, we can wait for more opinions about this to come.\nBut if user name and database name should NOT be NULL\nin postgres_fdw, I think that it's better to add the assertion\ncheck for those conditions and get rid of \"[unknown]\" part.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Fri, 5 Nov 2021 03:14:00 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "At Fri, 5 Nov 2021 03:14:00 +0900, Fujii Masao <masao.fujii@oss.nttdata.com> wrote in \n> \n> \n> On 2021/11/04 20:42, kuroda.hayato@fujitsu.com wrote:\n> > Dear Fujii-san,\n> >Thank you for giving comments! I attached new patches.\n> \n> Thanks for updating the patch!\n> \n> + <para>\n> + Note that if embedded strings have Non-ASCII,\n> + these characters will be replaced with the question marks\n> (<literal>?</literal>).\n> + This limitation is caused by <literal>application_name</literal>.\n> + </para>\n> \n> Isn't this descripton confusing because postgres_fdw actually doesn't\n> do this?\n> postgres_fdw just passses the application_name as it is to the remote\n> server.\n\nI'm not sure that that distinction is so clear for users. So I feel we\nwant a notice something like this. But it doesn't seem correct as it\nis. When the user name of the session consists of non-ascii\ncharacters, %u is finally seen as a sequence of '?'. It is not a\nembedded strings in pgfdw_application_name. I didn't notice this\nbehavior.\n\n\"pgfdw_application_name is set to application_name of a pgfdw\nconnection after placeholder conversion, thus the resulting string is\nsubject to the same restrictions to application_names.\". Maybe\nfollowed by \"If session user name or database name contains non-ascii\ncharacters, they are replaced by question marks \"?\"\".\n\nSidetracking a bit, considering this restriction, we might need to\nreconsider about %u and %d. session-id might be useful as it is\nascii-string that can identify a session exactly.\n\n> >> On second thought, do we really need padding support for\n> >> application_name\n> >> in postgres_fdw? I just thought that when I read the description\n> >> \"Padding can be useful to aid human readability in log files.\" in the\n> >> docs\n> >> about log_line_prefix.\n> >My feelings was that we don't have any reasons not to support,\n> > but I cannot found some good use-cases.\n> > Now I decided to keep supporting that,\n> > but if we face another problem I will cut that.\n> \n> I'd like to hear more opinions about this from others.\n> But *if* there is actually no use case, I'd like not to add\n> the feature, to make the code simpler.\n\nI think padding is useful because it alingns the significant content\nof log lines by equating the length of the leading fixed\ncomponents. application_name doesn't make any other visible components\nunaligned even when shown in the pg_stat_activity view. It is not\nuseful in that sense.\n\nPadding make the string itself make look maybe nicer, but gives no\nother advantage.\n\nI doubt people complain to the lack of the padding feature. Addition\nto that, since pgfdw_application_name and log_line_prefix work\ndifferent way in regard to multibyte characters, we don't need to\nstruggle so hard to consilidate them in their behavior.\n\n# I noticed that the paddig feature doesn't consider multibyte\n# characters. (I'm not suggesting them ought to be handled\n# \"prpoerly\").\n\nIn short, I'm for to removing it by +0.7.\n\n> >> +\t\t\tcase 'a':\n> >> +\t\t\t\tif (MyProcPort)\n> >> +\t\t\t\t{\n> >>\n> >> I commented that the check of MyProcPort is necessary because\n> >> background\n> >> worker not having MyProcPort may access to the remote server. The\n> >> example\n> >> of such process is the resolver process that Sawada-san was proposing\n> >> for\n> >> atomic commit feature. But the proposal was withdrawn and for now\n> >> there seems no such process. If this is true, we can safely remove the\n> >> check\n> >> of MyProcPort? If so, something like Assert(MyProcPort != NULL) may\n> >> need\n> >> to be added, instead.\n> >My understating was that we don't have to assume committing the\n> >Sawada-san's patch.\n> > I think that FDW is only available from backend processes in the\n> > current implementation,\n> > and MyProcPort will be substituted when processes are initialized() -\n> > in BackendInitialize().\n> > Since the backend will execute BackendInitialize() after forking()\n> > from the postmaster,\n> > we can assume that everyone who operates FDW has a valid value for\n> > MyProcPort.\n> > I removed if statement and added assertion.\n\nI think it is right.\n\n> +\t\t\tcase 'u':\n> +\t\t\t\tAssert(MyProcPort != NULL);\n> \n> Isn't it enough to perform this assertion check only once\n> at the top of parse_pgfdw_appname()?\n\nYeah, in either way, we should treat them in the same way.\n\n> > We can force parse_pgfdw_appname() not to be called if MyProcPort does\n> > not exist,\n> > but I don't think it is needed now.\n> \n> Yes.\n\n(I assume you said \"it is needed now\".) I'm not sure how to force\nthat but if it means a NULL MyProcPort cuases a crash, I think\ncrashing server is needlessly too aggressive as the penatly.\n\n> >> If user name or database name is not set, the name is replaced with\n> >> \"[unknown]\". log_line_prefix needs this because log message may be\n> >> output when they have not been set yet, e.g., at early stage of\n> >> backend\n> >> startup. But I wonder if application_name in postgres_fdw actually\n> >> need that.. Thought?\n> >Hmm, I think all of backend processes have username and database, but\n> > here has been followed from Horiguchi-san's suggestion:\n> >```\n> > I'm not sure but even if user_name doesn't seem to be NULL, don't we\n> > want to do the same thing with %u of log_line_prefix for safety?\n> > Namely, setting [unknown] if user_name is NULL or \"\". The same can be\n> > said for %d.\n> > ```\n> >But actually I don't have strong opinions.\n> \n> Ok, we can wait for more opinions about this to come.\n> But if user name and database name should NOT be NULL\n> in postgres_fdw, I think that it's better to add the assertion\n> check for those conditions and get rid of \"[unknown]\" part.\n\nIt seems to me that postgres-fdw asumes a valid user id, but doesn't\nmake no use of databsae, server port, and process id. What I thought\nhere is that making it an assertion is too much. So just ignoring the\nreplacement is also fine to me.\n\nThat being said, if we are eager not to have unused code paths, it is\nreasonable enough. I don't object strongly to replace it with an\nassertion.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 05 Nov 2021 12:17:31 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/11/05 12:17, Kyotaro Horiguchi wrote:\n> I'm not sure that that distinction is so clear for users. So I feel we\n> want a notice something like this. But it doesn't seem correct as it\n> is. When the user name of the session consists of non-ascii\n> characters, %u is finally seen as a sequence of '?'. It is not a\n> embedded strings in pgfdw_application_name. I didn't notice this\n> behavior.\n> \n> \"pgfdw_application_name is set to application_name of a pgfdw\n> connection after placeholder conversion, thus the resulting string is\n> subject to the same restrictions to application_names.\". Maybe\n> followed by \"If session user name or database name contains non-ascii\n> characters, they are replaced by question marks \"?\"\".\n\nIf we add something to the docs about this, we should clearly\ndescribe what postgres_fdw.application_name does and\nwhat postgres_fdw in a foreign server does. BTW, this kind of\ninformation was already commented in option.c.\nProbably it's better to mention the limitations on not only\nASCII characters but also the length of application name.\n\n * Unlike application_name GUC, don't set GUC_IS_NAME flag nor check_hook\n\t * to allow postgres_fdw.application_name to be any string more than\n\t * NAMEDATALEN characters and to include non-ASCII characters. Instead,\n\t * remote server truncates application_name of remote connection to less\n\t * than NAMEDATALEN and replaces any non-ASCII characters in it with a '?'\n\t * character.\n\nIf possible, I'd like to see this change as a separate patch\nand commt it first because this is the description for\nthe existing parameter postgres_fdw.application_name.\n\n\n>> I'd like to hear more opinions about this from others.\n>> But *if* there is actually no use case, I'd like not to add\n>> the feature, to make the code simpler.\n> \n> I think padding is useful because it alingns the significant content\n> of log lines by equating the length of the leading fixed\n> components. application_name doesn't make any other visible components\n> unaligned even when shown in the pg_stat_activity view. It is not\n> useful in that sense.\n> \n> Padding make the string itself make look maybe nicer, but gives no\n> other advantage.\n> \n> I doubt people complain to the lack of the padding feature. Addition\n> to that, since pgfdw_application_name and log_line_prefix work\n> different way in regard to multibyte characters, we don't need to\n> struggle so hard to consilidate them in their behavior.\n> \n> # I noticed that the paddig feature doesn't consider multibyte\n> # characters. (I'm not suggesting them ought to be handled\n> # \"prpoerly\").\n> \n> In short, I'm for to removing it by +0.7.\n\nSo our current consensus is to remove the padding part\nfrom postgres_fdw.application_name.\n\n\n>> +\t\t\tcase 'u':\n>> +\t\t\t\tAssert(MyProcPort != NULL);\n>>\n>> Isn't it enough to perform this assertion check only once\n>> at the top of parse_pgfdw_appname()?\n> \n> Yeah, in either way, we should treat them in the same way.\n> \n>>> We can force parse_pgfdw_appname() not to be called if MyProcPort does\n>>> not exist,\n>>> but I don't think it is needed now.\n>>\n>> Yes.\n> \n> (I assume you said \"it is needed now\".) I'm not sure how to force\n> that but if it means a NULL MyProcPort cuases a crash, I think\n> crashing server is needlessly too aggressive as the penatly.\n\nI said \"Yes\" for Kuroda-san's comment \"I don't think it is\nneeded now\". So I meant that \"it is NOT needed now\".\nSorry for unclear comment..\n\nHis idea was to skip calling parse_pgfdw_appname() if\nMyProcPort is NULL, so as to prevent parse_pgfdw_appname()\nfrom seeing NULL pointer of MyProcPort. But he thought\nit's not necessary now, and I agree with him because\nthe idea would cause more confusing behavior.\n\n\n> It seems to me that postgres-fdw asumes a valid user id, but doesn't\n> make no use of databsae, server port, and process id. What I thought\n> here is that making it an assertion is too much. So just ignoring the\n> replacement is also fine to me.\n> \n> That being said, if we are eager not to have unused code paths, it is\n> reasonable enough. I don't object strongly to replace it with an\n> assertion.\n\nSo no one strongly objects to the addition of assertion?\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Sun, 7 Nov 2021 13:35:39 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "At Sun, 7 Nov 2021 13:35:39 +0900, Fujii Masao <masao.fujii@oss.nttdata.com> wrote in \n> \n> \n> On 2021/11/05 12:17, Kyotaro Horiguchi wrote:\n> If possible, I'd like to see this change as a separate patch\n> and commt it first because this is the description for\n> the existing parameter postgres_fdw.application_name.\n\nFair enough.\n\n> >> I'd like to hear more opinions about this from others.\n> >> But *if* there is actually no use case, I'd like not to add\n> >> the feature, to make the code simpler.\n> > I think padding is useful because it alingns the significant content\n> > of log lines by equating the length of the leading fixed\n> > In short, I'm for to removing it by +0.7.\n> \n> So our current consensus is to remove the padding part\n> from postgres_fdw.application_name.\n\nI think so.\n\n> >> +\t\t\tcase 'u':\n> >> +\t\t\t\tAssert(MyProcPort != NULL);\n> >>\n> >> Isn't it enough to perform this assertion check only once\n> >> at the top of parse_pgfdw_appname()?\n> > Yeah, in either way, we should treat them in the same way.\n> > \n> >>> We can force parse_pgfdw_appname() not to be called if MyProcPort does\n> >>> not exist,\n> >>> but I don't think it is needed now.\n> >>\n> >> Yes.\n> > (I assume you said \"it is needed now\".) I'm not sure how to force\n> > that but if it means a NULL MyProcPort cuases a crash, I think\n> > crashing server is needlessly too aggressive as the penatly.\n> \n> I said \"Yes\" for Kuroda-san's comment \"I don't think it is\n> needed now\". So I meant that \"it is NOT needed now\".\n> Sorry for unclear comment..\n> \n> His idea was to skip calling parse_pgfdw_appname() if\n> MyProcPort is NULL, so as to prevent parse_pgfdw_appname()\n> from seeing NULL pointer of MyProcPort. But he thought\n> it's not necessary now, and I agree with him because\n> the idea would cause more confusing behavior.\n> \n> \n> > It seems to me that postgres-fdw asumes a valid user id, but doesn't\n> > make no use of databsae, server port, and process id. What I thought\n> > here is that making it an assertion is too much. So just ignoring the\n> > replacement is also fine to me.\n> > That being said, if we are eager not to have unused code paths, it is\n> > reasonable enough. I don't object strongly to replace it with an\n> > assertion.\n> \n> So no one strongly objects to the addition of assertion?\n\nIt seems to me so.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Mon, 08 Nov 2021 10:36:23 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Horiguchi-san, Fujii-san\n\nThank you for discussing!\n\n> Isn't it enough to perform this assertion check only once\n> at the top of parse_pgfdw_appname()?\n\nFixed.\n\n> If possible, I'd like to see this change as a separate patch\n> and commt it first because this is the description for\n> the existing parameter postgres_fdw.application_name.\n\nI attached a small doc patch for this.\n\n> \"pgfdw_application_name is set to application_name of a pgfdw\n> connection after placeholder conversion, thus the resulting string is\n> subject to the same restrictions to application_names.\". Maybe\n> followed by \"If session user name or database name contains non-ascii\n> characters, they are replaced by question marks \"?\"\".\n\nThis part was also added. Thanks!\n\n> So our current consensus is to remove the padding part\n> from postgres_fdw.application_name.\n\nYeah I removed.\n\nAttached patches are the latest version.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Mon, 8 Nov 2021 13:40:45 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/11/08 22:40, kuroda.hayato@fujitsu.com wrote:\n> Attached patches are the latest version.\n\nThanks for updating the patch!\n\n+\t\tbuf = makeStringInfo();\n\nThis is necessary only when application_name is set. So it's better to avoid this if appname is not set.\n\nCurrently StringInfo variable is defined in connect_pg_server() and passed to parse_pgfdw_appname(). But there is no strong reason why the variable needs to be defined connect_pg_server(). Right? If so how about refactoring parse_pgfdw_appname() so that it defines StringInfoData variable and returns the processed character string? You can see such coding at, for example, escape_param_str() in dblink.c.\n\nIf this refactoring is done, probably we can get rid of \"#include \"lib/stringinfo.h\"\" line from connection.c because connect_pg_server() no longer needs to use StringInfo.\n\n+\t\tint\t\t\ti;\n<snip>\n+\t\tfor (i = n - 1; i >= 0; i--)\n\nI'm tempted to simplify these into \"for (int i = n - 1; i >= 0; i--)\".\n\n+\t\t/*\n+\t\t * Search application_name and replace it if found.\n+\t\t *\n+\t\t * We search paramters from the end because the later\n+\t\t * one have higher priority. See also the above comment.\n+\t\t */\n\nHow about updating these comments into the following?\n\n-----------------------\nSearch the parameter arrays to find application_name setting,\nand replace escape sequences in it with status information if found.\nThe arrays are searched backwards because the last value\nis used if application_name is repeatedly set.\n-----------------------\n\n+\t\t\t\tif (strcmp(buf->data, \"\") != 0)\n\nIs this condition the same as \"data[0] == '\\0'\"?\n\n+ * parse postgres_fdw.application_name and set escaped string.\n+ * This function is almost same as log_line_prefix(), but\n+ * accepted escape sequence is different and this cannot understand\n+ * padding integer.\n+ *\n+ * Note that argument buf must be initialized.\n\nHow about updating these comments into the following?\nI thought that using the term \"parse\" was a bit confusing because what the function actually does is to replace escape seequences in application_name. Probably it's also better to rename the function, e.g., to process_pgfdw_appname .\n\n-----------------------------\nReplace escape sequences beginning with % character in the given\napplication_name with status information, and return it.\n-----------------------------\n\n+\t\t\t\t\tif (appname == NULL)\n+\t\t\t\t\t\tappname = \"[unknown]\";\n+\t\t\t\t\tif (username == NULL || *username == '\\0')\n+\t\t\t\t\t\tusername = \"[unknown]\";\n+\t\t\t\t\tif (dbname == NULL || *dbname == '\\0')\n+\t\t\t\t\t\tdbname = \"[unknown]\";\n\nI'm still not sure why these are necessary. Could you clarify that?\n\n+ Same as <xref linkend=\"guc-log-line-prefix\"/>, this is a\n+ <function>printf</function>-style string. Accepted escapes are\n+ bit different from <xref linkend=\"guc-log-line-prefix\"/>,\n+ but padding can be used like as it.\n\nThis description needs to be updated.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Sat, 4 Dec 2021 00:07:05 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "At Sat, 4 Dec 2021 00:07:05 +0900, Fujii Masao <masao.fujii@oss.nttdata.com> wrote in \n> \n> \n> On 2021/11/08 22:40, kuroda.hayato@fujitsu.com wrote:\n> > Attached patches are the latest version.\n> \n> Thanks for updating the patch!\n> \n> +\t\tbuf = makeStringInfo();\n> \n> This is necessary only when application_name is set. So it's better to\n> avoid this if appname is not set.\n> \n> Currently StringInfo variable is defined in connect_pg_server() and\n> passed to parse_pgfdw_appname(). But there is no strong reason why the\n> variable needs to be defined connect_pg_server(). Right? If so how\n> about refactoring parse_pgfdw_appname() so that it defines\n> StringInfoData variable and returns the processed character string?\n> You can see such coding at, for example, escape_param_str() in\n> dblink.c.\n> \n> If this refactoring is done, probably we can get rid of \"#include\n> \"lib/stringinfo.h\"\" line from connection.c because connect_pg_server()\n> no longer needs to use StringInfo.\n> \n> +\t\tint\t\t\ti;\n> <snip>\n> +\t\tfor (i = n - 1; i >= 0; i--)\n> \n> I'm tempted to simplify these into \"for (int i = n - 1; i >= 0; i--)\".\n> \n> +\t\t/*\n> +\t\t * Search application_name and replace it if found.\n> +\t\t *\n> +\t\t * We search paramters from the end because the later\n> +\t\t * one have higher priority. See also the above comment.\n> +\t\t */\n> \n> How about updating these comments into the following?\n> \n> -----------------------\n> Search the parameter arrays to find application_name setting,\n> and replace escape sequences in it with status information if found.\n> The arrays are searched backwards because the last value\n> is used if application_name is repeatedly set.\n> -----------------------\n> \n> +\t\t\t\tif (strcmp(buf->data, \"\") != 0)\n> \n> Is this condition the same as \"data[0] == '\\0'\"?\n\nFWIW, I agree to these.\n\n> + * parse postgres_fdw.application_name and set escaped string.\n> + * This function is almost same as log_line_prefix(), but\n> + * accepted escape sequence is different and this cannot understand\n> + * padding integer.\n> + *\n> + * Note that argument buf must be initialized.\n> \n> How about updating these comments into the following?\n> I thought that using the term \"parse\" was a bit confusing because what\n> the function actually does is to replace escape seequences in\n> application_name. Probably it's also better to rename the function,\n> e.g., to process_pgfdw_appname .\n\nIt is consistent to how we have described the similar features.\n\n> -----------------------------\n> Replace escape sequences beginning with % character in the given\n> application_name with status information, and return it.\n> -----------------------------\n> \n> +\t\t\t\t\tif (appname == NULL)\n> +\t\t\t\t\t\tappname = \"[unknown]\";\n> +\t\t\t\t\tif (username == NULL || *username == '\\0')\n> +\t\t\t\t\t\tusername = \"[unknown]\";\n> +\t\t\t\t\tif (dbname == NULL || *dbname == '\\0')\n> +\t\t\t\t\t\tdbname = \"[unknown]\";\n> \n> I'm still not sure why these are necessary. Could you clarify that?\n\nIt probably comes from my request, just for safety for uncertain\nfuture. They are actually not needed under the current usage of the\nfunction, so *I* would not object to removing them if you are strongly\nfeel them out of place. In that case, since NULL's leads to SEGV\noutright, we would even not need assertions instead.\n\n> + Same as <xref linkend=\"guc-log-line-prefix\"/>, this is a\n> + <function>printf</function>-style string. Accepted escapes are\n> + bit different from <xref linkend=\"guc-log-line-prefix\"/>,\n> + but padding can be used like as it.\n> \n> This description needs to be updated.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Mon, 06 Dec 2021 15:02:50 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san,\r\n\r\nThank you for reviewing! I'll post the latest version.\r\n\r\n> Currently StringInfo variable is defined in connect_pg_server() and passed to\r\n> parse_pgfdw_appname(). But there is no strong reason why the variable needs to\r\n> be defined connect_pg_server(). Right? If so how about refactoring\r\n> parse_pgfdw_appname() so that it defines StringInfoData variable and returns the\r\n> processed character string? You can see such coding at, for example,\r\n> escape_param_str() in dblink.c.\r\n> If this refactoring is done, probably we can get rid of \"#include \"lib/stringinfo.h\"\"\r\n> line from connection.c because connect_pg_server() no longer needs to use\r\n> StringInfo.\r\n\r\nI refactored that. Thanks!\r\n\r\n> +\t\tint\t\t\ti;\r\n> <snip>\r\n> +\t\tfor (i = n - 1; i >= 0; i--)\r\n> \r\n> I'm tempted to simplify these into \"for (int i = n - 1; i >= 0; i--)\".\r\n> \r\n> +\t\t/*\r\n> +\t\t * Search application_name and replace it if found.\r\n> +\t\t *\r\n> +\t\t * We search paramters from the end because the later\r\n> +\t\t * one have higher priority. See also the above comment.\r\n> +\t\t */\r\n> \r\n> How about updating these comments into the following?\r\n> \r\n> -----------------------\r\n> Search the parameter arrays to find application_name setting,\r\n> and replace escape sequences in it with status information if found.\r\n> The arrays are searched backwards because the last value\r\n> is used if application_name is repeatedly set.\r\n\r\nPrefer yours. Fixed.\r\n\r\n> +\t\t\t\tif (strcmp(buf->data, \"\") != 0)\r\n> \r\n> Is this condition the same as \"data[0] == '\\0'\"?\r\n\r\nMaybe \"data[0] != '\\0'\", but fixed.\r\n\r\n> + * parse postgres_fdw.application_name and set escaped string.\r\n> + * This function is almost same as log_line_prefix(), but\r\n> + * accepted escape sequence is different and this cannot understand\r\n> + * padding integer.\r\n> + *\r\n> + * Note that argument buf must be initialized.\r\n> \r\n> How about updating these comments into the following?\r\n> I thought that using the term \"parse\" was a bit confusing because what the\r\n> function actually does is to replace escape seequences in application_name.\r\n> Probably it's also better to rename the function, e.g., to process_pgfdw_appname .\r\n> \r\n> -----------------------------\r\n> Replace escape sequences beginning with % character in the given\r\n> application_name with status information, and return it.\r\n> -----------------------------\r\n\r\nThank you for suggestions. I confused the word \"parse.\"\r\nFixed and renamed.\r\n\r\n> + Same as <xref linkend=\"guc-log-line-prefix\"/>, this is a\r\n> + <function>printf</function>-style string. Accepted escapes are\r\n> + bit different from <xref linkend=\"guc-log-line-prefix\"/>,\r\n> + but padding can be used like as it.\r\n> \r\n> This description needs to be updated.\r\n\r\nI missed there. Fixed.\r\n\r\nBest Regards,\r\nHayato Kuroda\r\nFUJITSU LIMITED\r\n\r\n", "msg_date": "Tue, 7 Dec 2021 08:55:59 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "Dear Horiguchi-san\n\nThank you for giving comments! I attached new patches.\n\n> > +\t\t\t\t\tif (appname == NULL)\n> > +\t\t\t\t\t\tappname = \"[unknown]\";\n> > +\t\t\t\t\tif (username == NULL || *username\n> == '\\0')\n> > +\t\t\t\t\t\tusername = \"[unknown]\";\n> > +\t\t\t\t\tif (dbname == NULL || *dbname ==\n> '\\0')\n> > +\t\t\t\t\t\tdbname = \"[unknown]\";\n> >\n> > I'm still not sure why these are necessary. Could you clarify that?\n> \n> It probably comes from my request, just for safety for uncertain\n> future. They are actually not needed under the current usage of the\n> function, so *I* would not object to removing them if you are strongly\n> feel them out of place. In that case, since NULL's leads to SEGV\n> outright, we would even not need assertions instead.\n\nYeah, I followed your suggestion. But we deiced to keep codes clean,\nhence I removed the if-statements.\n\nBest Regards,\nHayato Kuroda\nFUJITSU LIMITED", "msg_date": "Tue, 7 Dec 2021 09:48:21 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/12/07 18:48, kuroda.hayato@fujitsu.com wrote:\n> Yeah, I followed your suggestion. But we deiced to keep codes clean,\n> hence I removed the if-statements.\n\n+1 because neither application_name, user_name nor database_name should be NULL for current usage. But if it's better to check whether they are NULL or not for some reasons or future usage, e.g., background worker not logging into any specified database may set application_name to '%d' and connect to a foreign server in the future, let's change the code later with comments.\n\nThanks for updating the patch!\n\nRegarding 0001 patch, IMO it's better to explain that postgres_fdw.application_name can be any string of any length and contain even non-ASCII characters, unlike application_name. So how about using the following description, instead?\n\n-----------------\n<varname>postgres_fdw.application_name</varname> can be any string of any length and contain even non-ASCII characters. However when it's passed to and used as <varname>application_name</varname> in a foreign server, note that it will be truncated to less than <symbol>NAMEDATALEN</symbol> characters and any characters other than printable ASCII ones in it will be replaced with question marks (<literal>?</literal>).\n-----------------\n\n+\t\tint\t\t\ti;\n+\t\tfor (i = n - 1; i >= 0; i--)\n\nAs I told before, it's better to simplify this to \"for (int i = n - 1; i >= 0; i--)\".\n\nSeems you removed the calls to pfree() from the patch. That's because the memory context used for the replaced application_name string will be released soon? Or it's better to call pfree()?\n\n+ Same as <xref linkend=\"guc-log-line-prefix\"/>, this is a\n+ <function>printf</function>-style string. Unlike <xref linkend=\"guc-log-line-prefix\"/>,\n+ paddings are not allowed. Accepted escapes are as follows:\n\nIsn't it better to explain escape sequences in postgres_fdw.application_name more explicitly, as follows?\n\n-----------------\n<literal>%</literal> characters begin <quote>escape sequences</quote> that are replaced with status information as outlined below. Unrecognized escapes are ignored. Other characters are copied straight to the application name. Note that it's not allowed to specify a plus/minus sign or a numeric literal after the <literal>%</literal> and before the option, for alignment and padding.\n-----------------\n\n+ <entry><literal>%u</literal></entry>\n+ <entry>Local user name</entry>\n\nAverage users can understand what \"Local\" here means?\n\n+ postgres_fdw.application_name is set to application_name of a pgfdw\n+ connection after placeholder conversion, thus the resulting string is\n+ subject to the same restrictions alreadby mentioned above.\n\nThis description doesn't need to be added if 0001 patch is applied, is it? Because 0001 patch adds very similar description into the docs.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 9 Dec 2021 02:34:21 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san\r\n\r\nThank you for quick reviewing! I attached new ones.\r\n\r\n> Regarding 0001 patch, IMO it's better to explain that\r\n> postgres_fdw.application_name can be any string of any length and contain even\r\n> non-ASCII characters, unlike application_name. So how about using the following\r\n> description, instead?\r\n> \r\n> -----------------\r\n> <varname>postgres_fdw.application_name</varname> can be any string of any\r\n> length and contain even non-ASCII characters. However when it's passed to and\r\n> used as <varname>application_name</varname> in a foreign server, note that it\r\n> will be truncated to less than <symbol>NAMEDATALEN</symbol> characters\r\n> and any characters other than printable ASCII ones in it will be replaced with\r\n> question marks (<literal>?</literal>).\r\n> -----------------\r\n\r\n+1, Fixed.\r\n\r\n> +\t\tint\t\t\ti;\r\n> +\t\tfor (i = n - 1; i >= 0; i--)\r\n> \r\n> As I told before, it's better to simplify this to \"for (int i = n - 1; i >= 0; i--)\".\r\n\r\nSorry, I missed. Fixed.\r\n\r\n> Seems you removed the calls to pfree() from the patch. That's because the\r\n> memory context used for the replaced application_name string will be released\r\n> soon? Or it's better to call pfree()?\r\n\r\nBecause I used escape_param_str() and get_connect_string() as reference,\r\nthey did not release the memory. I reconsidered here, however, and I agreed\r\nit is confusing that only keywords and values are pfree()'d.\r\nI exported char* data and execute pfree() if it is used.\r\n\r\n> + Same as <xref linkend=\"guc-log-line-prefix\"/>, this is a\r\n> + <function>printf</function>-style string. Unlike <xref\r\n> linkend=\"guc-log-line-prefix\"/>,\r\n> + paddings are not allowed. Accepted escapes are as follows:\r\n> \r\n> Isn't it better to explain escape sequences in postgres_fdw.application_name\r\n> more explicitly, as follows?\r\n> \r\n> -----------------\r\n> <literal>%</literal> characters begin <quote>escape sequences</quote> that\r\n> are replaced with status information as outlined below. Unrecognized escapes are\r\n> ignored. Other characters are copied straight to the application name. Note that\r\n> it's not allowed to specify a plus/minus sign or a numeric literal after the\r\n> <literal>%</literal> and before the option, for alignment and padding.\r\n> -----------------\r\n\r\nFixed.\r\n\r\n> + <entry><literal>%u</literal></entry>\r\n> + <entry>Local user name</entry>\r\n> \r\n> Average users can understand what \"Local\" here means?\r\n\r\nMaybe not. I added descriptions and an example.\t\r\n\r\n> + postgres_fdw.application_name is set to application_name of a pgfdw\r\n> + connection after placeholder conversion, thus the resulting string is\r\n> + subject to the same restrictions alreadby mentioned above.\r\n> \r\n> This description doesn't need to be added if 0001 patch is applied, is it? Because\r\n> 0001 patch adds very similar description into the docs.\r\n\r\n+1, removed.\r\n\r\nBest Regards,\r\nHayato Kuroda\r\nFUJITSU LIMITED", "msg_date": "Thu, 9 Dec 2021 10:52:38 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/12/09 19:52, kuroda.hayato@fujitsu.com wrote:\n> Dear Fujii-san\n> \n> Thank you for quick reviewing! I attached new ones.\n\nThanks for updating the patches!\n\n>> Regarding 0001 patch, IMO it's better to explain that\n>> postgres_fdw.application_name can be any string of any length and contain even\n>> non-ASCII characters, unlike application_name. So how about using the following\n>> description, instead?\n>>\n>> -----------------\n>> <varname>postgres_fdw.application_name</varname> can be any string of any\n>> length and contain even non-ASCII characters. However when it's passed to and\n>> used as <varname>application_name</varname> in a foreign server, note that it\n>> will be truncated to less than <symbol>NAMEDATALEN</symbol> characters\n>> and any characters other than printable ASCII ones in it will be replaced with\n>> question marks (<literal>?</literal>).\n>> -----------------\n> \n> +1, Fixed.\n\nCould you tell me why you added new paragraph into the middle of existing paragraph? This change caused the following error when compiling the docs.\n\npostgres-fdw.sgml:952: parser error : Opening and ending tag mismatch: listitem line 934 and para\n </para>\n\nHow about adding that new paragraph just after the existing one, instead?\n\n\n>> Seems you removed the calls to pfree() from the patch. That's because the\n>> memory context used for the replaced application_name string will be released\n>> soon? Or it's better to call pfree()?\n> \n> Because I used escape_param_str() and get_connect_string() as reference,\n> they did not release the memory. I reconsidered here, however, and I agreed\n> it is confusing that only keywords and values are pfree()'d.\n> I exported char* data and execute pfree() if it is used.\n\nUnderstood.\n\n+\t\t\t\t/*\n+\t\t\t\t * The parsing result became an empty string,\n+\t\t\t\t * and that means other \"application_name\" will be used\n+\t\t\t\t * for connecting to the remote server.\n+\t\t\t\t * So we must set values[i] to an empty string\n+\t\t\t\t * and search the array again.\n+\t\t\t\t */\n+\t\t\t\tvalues[i] = \"\";\n\nIsn't pfree() necessary inside the loop also when data[0]=='\\0' case? If so, probably \"data\" would need to be set to NULL just after pfree(). Otherwise pfree()'d \"data\" can be pfree()'d again at the end of connect_pg_server().\n\n>> + <entry><literal>%u</literal></entry>\n>> + <entry>Local user name</entry>\n>>\n>> Average users can understand what \"Local\" here means?\n> \n> Maybe not. I added descriptions and an example.\n\nThanks! But, since the term \"local server\" is already used in the docs, we can use \"the setting value of application_name in local server\" etc?\n\nI agree that it's good idea to add the example about how escape sequences are replaced.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Fri, 10 Dec 2021 03:20:02 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san,\r\n\r\nI apologize for sending bad patches...\r\nI confirmed that it can be built and passed a test.\r\n\r\n> Could you tell me why you added new paragraph into the middle of existing\r\n> paragraph? This change caused the following error when compiling the docs.\r\n> \r\n> postgres-fdw.sgml:952: parser error : Opening and ending tag mismatch: listitem\r\n> line 934 and para\r\n> </para>\r\n> \r\n> How about adding that new paragraph just after the existing one, instead?\r\n\r\nFixed.\r\n\r\n> +\t\t\t\t/*\r\n> +\t\t\t\t * The parsing result became an empty string,\r\n> +\t\t\t\t * and that means other \"application_name\"\r\n> will be used\r\n> +\t\t\t\t * for connecting to the remote server.\r\n> +\t\t\t\t * So we must set values[i] to an empty string\r\n> +\t\t\t\t * and search the array again.\t\r\n> +\t\t\t\t */\r\n> +\t\t\t\tvalues[i] = \"\";\r\n> \r\n> Isn't pfree() necessary inside the loop also when data[0]=='\\0' case? If so,\r\n> probably \"data\" would need to be set to NULL just after pfree(). Otherwise\r\n> pfree()'d \"data\" can be pfree()'d again at the end of connect_pg_server().\r\n\r\nI confirmed the source, and I agreed your argument because\r\ninitStringInfo() allocates memory firstly. Hence pfree() was added.\r\n\r\n> Thanks! But, since the term \"local server\" is already used in the docs, we can use\r\n> \"the setting value of application_name in local server\" etc?\r\n\r\nI like the word \"local server,\" so I reworte descriptions.\r\n\r\nBest Regards,\r\nHayato Kuroda\r\nFUJITSU LIMITED", "msg_date": "Fri, 10 Dec 2021 07:35:04 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "On 2021/12/10 16:35, kuroda.hayato@fujitsu.com wrote:\n>> How about adding that new paragraph just after the existing one, instead?\n> \n> Fixed.\n\nThanks for the fix! Attached is the updated version of 0001 patch.\nI added \"See <xref linkend=\"guc-application-name\"/> for details.\"\ninto the description. Barring any objection, I will commit\nthis patch at first.\n\n>> Thanks! But, since the term \"local server\" is already used in the docs, we can use\n>> \"the setting value of application_name in local server\" etc?\n> \n> I like the word \"local server,\" so I reworte descriptions.\n\nThanks! Attached is the updated version of 0002 patch. I applied\nsome cosmetic changes, improved comments and docs. Could you review\nthis version?\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION", "msg_date": "Thu, 16 Dec 2021 02:23:23 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san,\r\n\r\nThank you for updating! I read your patches and I have\r\nonly one comment.\r\n\r\n> \t\t\tif (strcmp(keywords[i], \"application_name\") == 0 &&\r\n> \t\t\t\tvalues[i] != NULL && *(values[i]) != '\\0')\r\n\r\nI'm not sure but do we have a case that values[i] becomes NULL\r\neven if keywords[i] is \"application_name\"?\r\n\r\nI think other parts are perfect.\r\n\r\nBest Regards,\r\nHayato Kuroda\r\nFUJITSU LIMITED\r\n\r\n", "msg_date": "Thu, 16 Dec 2021 02:53:44 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/12/16 11:53, kuroda.hayato@fujitsu.com wrote:\n> Dear Fujii-san,\n> \n> Thank you for updating! I read your patches and I have\n> only one comment.\n> \n>> \t\t\tif (strcmp(keywords[i], \"application_name\") == 0 &&\n>> \t\t\t\tvalues[i] != NULL && *(values[i]) != '\\0')\n> \n> I'm not sure but do we have a case that values[i] becomes NULL\n> even if keywords[i] is \"application_name\"?\n\nNo for now, I guess. But isn't it safer to check that, too? I also could not find strong reason why that check should be dropped. But you'd like to drop that?\n\n> I think other parts are perfect.\n\nThanks for the review! At first I pushed 0001 patch.\n\nBTW, 0002 patch adds the regression test that checks pg_stat_activity.application_name. But three months before, we added the similar test when introducing postgres_fdw.application_name GUC and reverted/removed it because it's not stable [1]. So we should review carefully whether the test 0002 patch adds may have the same issue or not. As far as I read the patch, ISTM that the patch has no same issue. But could you double check that?\n\n[1]\nhttps://postgr.es/m/848ff477-effd-42b9-8b25-3f7cfe289398@oss.nttdata.com\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 16 Dec 2021 15:33:56 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san,\r\n\r\n> Thanks for the review! At first I pushed 0001 patch.\r\n\r\nI found your commit. Thanks!\r\n\r\n> BTW, 0002 patch adds the regression test that checks\r\n> pg_stat_activity.application_name. But three months before, we added the similar\r\n> test when introducing postgres_fdw.application_name GUC and\r\n> reverted/removed it because it's not stable [1]. So we should review carefully\r\n> whether the test 0002 patch adds may have the same issue or not. As far as I read\r\n> the patch, ISTM that the patch has no same issue. But could you double check\r\n> that?\r\n\r\nI agreed we will not face the problem.\r\nWhen postgres_fdw_disconnect_all() is performed, we just send a character 'X' to\r\nremote backends(in sendTerminateConn() and lower functions) and return without any blockings.\r\nAfter receiving 'X' message in remote backends, proc_exit() is performed and processes\r\nwill be died. The test failure is caused because SELECT statement is performed\r\nbefore dying backends perfectly. \r\nCurrently we search pg_stat_activity and this is not affected by residual rows\r\nbecause the condition is too strict to exist others.\r\nHence I think this test is stable. How do you think?\r\n\r\nBest Regards,\r\nHayato Kuroda\r\nFUJITSU LIMITED\r\n\r\n", "msg_date": "Fri, 17 Dec 2021 01:58:36 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san,\r\n\r\nSorry I forgot replying your messages.\r\n\r\n> >> \t\t\tif (strcmp(keywords[i], \"application_name\") == 0 &&\r\n> >> \t\t\t\tvalues[i] != NULL && *(values[i]) != '\\0')\r\n> >\r\n> > I'm not sure but do we have a case that values[i] becomes NULL\r\n> > even if keywords[i] is \"application_name\"?\r\n> \r\n> No for now, I guess. But isn't it safer to check that, too? I also could not find strong\r\n> reason why that check should be dropped. But you'd like to drop that?\r\n\r\nNo, I agreed the new checking. I'm just afraid of my code missing.\r\n\r\nBest Regards,\r\nHayato Kuroda\r\nFUJITSU LIMITED\r\n\r\n", "msg_date": "Fri, 17 Dec 2021 02:42:25 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "At Fri, 17 Dec 2021 02:42:25 +0000, \"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com> wrote in \n> Dear Fujii-san,\n> \n> Sorry I forgot replying your messages.\n> \n> > >> \t\t\tif (strcmp(keywords[i], \"application_name\") == 0 &&\n> > >> \t\t\t\tvalues[i] != NULL && *(values[i]) != '\\0')\n> > >\n> > > I'm not sure but do we have a case that values[i] becomes NULL\n> > > even if keywords[i] is \"application_name\"?\n> > \n> > No for now, I guess. But isn't it safer to check that, too? I also could not find strong\n> > reason why that check should be dropped. But you'd like to drop that?\n> \n> No, I agreed the new checking. I'm just afraid of my code missing.\n\nFWIW, I don't understand why we care of the case where the function\nitself changes its mind to set values[i] to null while we ignore the\npossibility that some module at remote is modified so that some global\nvariables to be NULL. I don't mind wheter we care for NULLs or not\nbut I think we should be consistent at least in a single patch.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 17 Dec 2021 12:06:12 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/12/17 12:06, Kyotaro Horiguchi wrote:\n> At Fri, 17 Dec 2021 02:42:25 +0000, \"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com> wrote in\n>> Dear Fujii-san,\n>>\n>> Sorry I forgot replying your messages.\n>>\n>>>>> \t\t\tif (strcmp(keywords[i], \"application_name\") == 0 &&\n>>>>> \t\t\t\tvalues[i] != NULL && *(values[i]) != '\\0')\n>>>>\n>>>> I'm not sure but do we have a case that values[i] becomes NULL\n>>>> even if keywords[i] is \"application_name\"?\n>>>\n>>> No for now, I guess. But isn't it safer to check that, too? I also could not find strong\n>>> reason why that check should be dropped. But you'd like to drop that?\n>>\n>> No, I agreed the new checking. I'm just afraid of my code missing.\n> \n> FWIW, I don't understand why we care of the case where the function\n> itself changes its mind to set values[i] to null\n\nWhether we add this check or not, the behavior is the same, i.e., that setting value is not used. But by adding the check we can avoid unnecessary call of process_pgfdw_appname() when the value is NULL. OTOH, of course we can also remove the check. So I'm ok to remove that if you're thinking it's more consistent to remove that.\n\n\n> while we ignore the\n> possibility that some module at remote is modified so that some global\n> variables to be NULL. I don't mind wheter we care for NULLs or not\n> but I think we should be consistent at least in a single patch.\n\nProbably you're mentioning that we got rid of something like the following code from process_pgfdw_appname(). In this case whether we add the check or not can affect the behavior (i.e., escape sequence is replace with \"[unknown]\" or not). So ISTM that the situations are similar but not the same.\n\n+ if (appname == NULL || *appname == '\\0')\n+ appname = \"[unknown]\";\n\nProbably now it's good chance to revisit this issue. As I commented at [1], at least for me it's intuitive to use empty string rather than \"[unknown]\" when appname or username, etc was NULL or '\\0'. To implement this behavior, I argued to remove the check itself. But there are several options:\n\n#1. use \"[unknown]\"\n#2. add the check but not use \"[unknown]\"\n#3. don't add the check (i.e., what the current patch does)\n\nFor now, I'm ok to choose #2 or #3.\n\n[1]\nhttps://postgr.es/m/0dbe50c3-c528-74b1-c577-035a4a68fc61@oss.nttdata.com\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Fri, 17 Dec 2021 14:50:37 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "At Fri, 17 Dec 2021 14:50:37 +0900, Fujii Masao <masao.fujii@oss.nttdata.com> wrote in \n> > FWIW, I don't understand why we care of the case where the function\n> > itself changes its mind to set values[i] to null\n> \n> Whether we add this check or not, the behavior is the same, i.e., that\n> setting value is not used. But by adding the check we can avoid\n> unnecessary call of process_pgfdw_appname() when the value is\n> NULL. OTOH, of course we can also remove the check. So I'm ok to\n> remove that if you're thinking it's more consistent to remove that.\n\nThat depends. It seems to me defGetString is assumed to return a valid\npointer, since (AFAIS) all of the callers don't check against NULL. On\nthe other hand the length of the string may be zero. Actually\ncheck_conn_params() called just after makes the same assumption (only\non \"password\", though). On the other hand PQconnectdbParams assumes\nNULL value as not-set.\n\nSo assumption on the NULL value differs in some places and at least\npostgres_fdw doesn't use NULL to represent \"not exists\".\n\nThus rewriting the code we're focusing on like the following would\nmake sense to me.\n\n>\tif (strcmp(keywords[i], \"application_name\") == 0)\n>\t{\n>\t\tvalues[i] = process_pgfdw_appname(values[i]);\n>\n>\t\t/*\n>\t\t * Break if we have a non-empty string. If we end up failing with\n>\t\t * all candidates, fallback_application_name would work.\n>\t\t */\n>\t\tif (appanme[0] != '\\0')\n>\t\t\tbreak;\n>\t}\t\t\n\n\n> Probably now it's good chance to revisit this issue. As I commented at\n> [1], at least for me it's intuitive to use empty string rather than\n> \"[unknown]\" when appname or username, etc was NULL or '\\0'. To\n> implement this behavior, I argued to remove the check itself. But\n> there are several options:\n\nThanks for revisiting.\n\n> #1. use \"[unknown]\"\n> #2. add the check but not use \"[unknown]\"\n> #3. don't add the check (i.e., what the current patch does)\n> \n> For now, I'm ok to choose #2 or #3.\n\nAs I said before, given that we don't show \"unkown\" or somethig like\nas the fallback, I'm fine with not having a NULL check since anyway it\nbumps into SEGV immediately. In short I'm fine with #3 here.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 17 Dec 2021 16:50:58 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/12/17 16:50, Kyotaro Horiguchi wrote:\n> Thus rewriting the code we're focusing on like the following would\n> make sense to me.\n> \n>> \tif (strcmp(keywords[i], \"application_name\") == 0)\n>> \t{\n>> \t\tvalues[i] = process_pgfdw_appname(values[i]);\n>>\n>> \t\t/*\n>> \t\t * Break if we have a non-empty string. If we end up failing with\n>> \t\t * all candidates, fallback_application_name would work.\n>> \t\t */\n>> \t\tif (appanme[0] != '\\0')\n>> \t\t\tbreak;\n>> \t}\t\t\n\nI'm ok to remove the check \"values[i] != NULL\", but think that it's better to keep the other check \"*(values[i]) != '\\0'\" as it is. Because *(values[i]) can be null character and it's a waste of cycles to call process_pgfdw_appname() in that case.\n\n> Thanks for revisiting.\n> \n>> #1. use \"[unknown]\"\n>> #2. add the check but not use \"[unknown]\"\n>> #3. don't add the check (i.e., what the current patch does)\n>>\n>> For now, I'm ok to choose #2 or #3.\n> \n> As I said before, given that we don't show \"unkown\" or somethig like\n> as the fallback, I'm fine with not having a NULL check since anyway it\n> bumps into SEGV immediately. In short I'm fine with #3 here.\n\nYep, let's use #3 approach.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 23 Dec 2021 23:10:38 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "At Thu, 23 Dec 2021 23:10:38 +0900, Fujii Masao <masao.fujii@oss.nttdata.com> wrote in \n> \n> \n> On 2021/12/17 16:50, Kyotaro Horiguchi wrote:\n> > Thus rewriting the code we're focusing on like the following would\n> > make sense to me.\n> > \n> >> \tif (strcmp(keywords[i], \"application_name\") == 0)\n> >> \t{\n> >> \t\tvalues[i] = process_pgfdw_appname(values[i]);\n> >>\n> >> \t\t/*\n> >> \t\t * Break if we have a non-empty string. If we end up failing with\n> >> \t\t * all candidates, fallback_application_name would work.\n> >> \t\t */\n> >> \t\tif (appanme[0] != '\\0')\n\n(appname?)\n\n> >> \t\t\tbreak;\n> >> \t}\t\t\n> \n> I'm ok to remove the check \"values[i] != NULL\", but think that it's\n> better to keep the other check \"*(values[i]) != '\\0'\" as it\n> is. Because *(values[i]) can be null character and it's a waste of\n> cycles to call process_pgfdw_appname() in that case.\n\nRight. I removed too much.\n\n> > Thanks for revisiting.\n> > \n> >> #1. use \"[unknown]\"\n> >> #2. add the check but not use \"[unknown]\"\n> >> #3. don't add the check (i.e., what the current patch does)\n> >>\n> >> For now, I'm ok to choose #2 or #3.\n> > As I said before, given that we don't show \"unkown\" or somethig like\n> > as the fallback, I'm fine with not having a NULL check since anyway it\n> > bumps into SEGV immediately. In short I'm fine with #3 here.\n> \n> Yep, let's use #3 approach.\n\nAgreed.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 24 Dec 2021 13:49:15 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "\n\nOn 2021/12/24 13:49, Kyotaro Horiguchi wrote:\n>> I'm ok to remove the check \"values[i] != NULL\", but think that it's\n>> better to keep the other check \"*(values[i]) != '\\0'\" as it\n>> is. Because *(values[i]) can be null character and it's a waste of\n>> cycles to call process_pgfdw_appname() in that case.\n> \n> Right. I removed too much.\n\nThanks for the check! So I kept the check \"*(values[i]) != '\\0'\" as it is\nand pushed the patch. Thanks!\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Fri, 24 Dec 2021 17:01:55 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san, Horiguchi-san,\r\n\r\nI confirmed that the feature was committed but reverted the test.\r\nNow I'm checking buildfarm.\r\n\r\nBut anyway I want to say thank you for your contribution!\r\n\r\nBest Regards,\r\nHayato Kuroda\r\nFUJITSU LIMITED\r\n\r\n", "msg_date": "Mon, 27 Dec 2021 01:40:00 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "On 2021/12/27 10:40, kuroda.hayato@fujitsu.com wrote:\n> Dear Fujii-san, Horiguchi-san,\n> \n> I confirmed that the feature was committed but reverted the test.\n> Now I'm checking buildfarm.\n\nAttached is the patch that adds the regression test for postgres_fdw.application_name. Could you review this?\n\nAs Horiguchi-san suggested at [1], I split the test into two, and then tweaked them as follows.\n\n1. Set application_name option of a server option to 'fdw_%d%p'\n2. Set postgres_fdw.application_name to 'fdw_%a%u%%'\n\n'fdw_%d%p' and 'fdw_%a%u%%' still may be larger than NAMEDATALEN depending on the regression test environment. To make the test stable even in that case, the patch uses substring() is truncate application_name string in the test query's condition to less than NAMEDATALEN.\n\n[1]\nhttps://postgr.es/m/20211224.184406.814784272581964942.horikyota.ntt@gmail.com\n\n\n> But anyway I want to say thank you for your contribution!\n\nThanks!\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION", "msg_date": "Mon, 27 Dec 2021 13:39:54 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Fujii-san,\r\n\r\n> Attached is the patch that adds the regression test for\r\n> postgres_fdw.application_name. Could you review this?\r\n> \r\n> As Horiguchi-san suggested at [1], I split the test into two, and then tweaked them\r\n> as follows.\r\n> \r\n> 1. Set application_name option of a server option to 'fdw_%d%p'\r\n> 2. Set postgres_fdw.application_name to 'fdw_%a%u%%'\r\n> \r\n> 'fdw_%d%p' and 'fdw_%a%u%%' still may be larger than NAMEDATALEN\r\n> depending on the regression test environment. To make the test stable even in\r\n> that case, the patch uses substring() is truncate application_name string in the\r\n> test query's condition to less than NAMEDATALEN.\r\n\r\nI think it's good because we can care about max_identifier_length,\r\nand both of setting methods are used.\r\nAlso it's smart using pg_terminate_backend().\r\n(Actually I'm writing a test that separates test cases into five parts, but\r\nyour patch is better.)\r\n\r\nI think the test failure should be noticed by me, but I missed, sorry.\r\nDo you know how to apply my patch and test by buildfarm animals?\r\n\r\nBest Regards,\r\nHayato Kuroda\r\nFUJITSU LIMITED\r\n\r\n", "msg_date": "Mon, 27 Dec 2021 06:19:10 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "On Mon, Dec 27, 2021 at 1:40 PM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n>\n>\n>\n> On 2021/12/27 10:40, kuroda.hayato@fujitsu.com wrote:\n> > Dear Fujii-san, Horiguchi-san,\n> >\n> > I confirmed that the feature was committed but reverted the test.\n> > Now I'm checking buildfarm.\n>\n> Attached is the patch that adds the regression test for postgres_fdw.application_name. Could you review this?\n>\n> As Horiguchi-san suggested at [1], I split the test into two, and then tweaked them as follows.\n>\n> 1. Set application_name option of a server option to 'fdw_%d%p'\n> 2. Set postgres_fdw.application_name to 'fdw_%a%u%%'\n>\n> 'fdw_%d%p' and 'fdw_%a%u%%' still may be larger than NAMEDATALEN depending on the regression test environment. To make the test stable even in that case, the patch uses substring() is truncate application_name string in the test query's condition to less than NAMEDATALEN.\n\nGood idea. But the application_name is actually truncated to 63\ncharacters (NAMEDATALEN - 1)? If so, we need to do substring(... for\n63) instead.\n\nRegards,\n\n--\nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Mon, 27 Dec 2021 20:18:18 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "Dear Sawada-san,\r\n\r\n> Good idea. But the application_name is actually truncated to 63\r\n> characters (NAMEDATALEN - 1)? If so, we need to do substring(... for\r\n> 63) instead.\r\n\r\nYeah, the parameter will be truncated as one less than NAMEDATALEN:\r\n\r\n```\r\nmax_identifier_length (integer)\r\nReports the maximum identifier length. It is determined as one less than the value of NAMEDATALEN when building the server.\r\nThe default value of NAMEDATALEN is 64; therefore the default max_identifier_length is 63 bytes,\r\nwhich can be less than 63 characters when using multibyte encodings.\r\n```\r\n\r\nBut in Fujii-san's patch length is picked up by the following SQL, so I think it works well.\r\n\r\n```\r\nSELECT max_identifier_length FROM pg_control_init()\r\n```\r\n\r\nBest Regards,\r\nHayato Kuroda\r\nFUJITSU LIMITED\r\n\r\n", "msg_date": "Mon, 27 Dec 2021 23:57:15 +0000", "msg_from": "\"kuroda.hayato@fujitsu.com\" <kuroda.hayato@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: Allow escape in application_name" }, { "msg_contents": "On Tue, Dec 28, 2021 at 8:57 AM kuroda.hayato@fujitsu.com\n<kuroda.hayato@fujitsu.com> wrote:\n>\n> Dear Sawada-san,\n>\n> > If so, we need to do substring(... for\n> > 63) instead.\n\nJust to be clear, I meant substring(... for NAMEDATALEN - 1).\n\n>\n> Yeah, the parameter will be truncated as one less than NAMEDATALEN:\n>\n> ```\n> max_identifier_length (integer)\n> Reports the maximum identifier length. It is determined as one less than the value of NAMEDATALEN when building the server.\n> The default value of NAMEDATALEN is 64; therefore the default max_identifier_length is 63 bytes,\n> which can be less than 63 characters when using multibyte encodings.\n> ```\n\nI think this is the description of the max_identifier_length GUC parameter.\n\n>\n> But in Fujii-san's patch length is picked up by the following SQL, so I think it works well.\n>\n> ```\n> SELECT max_identifier_length FROM pg_control_init()\n> ```\n\nDoesn't this query return 64? So the expression \"substring(str for\n(SELECT max_identifier_length FROM pg_control_init()))\" returns the\nfirst 64 characters of the given string while the application_name is\ntruncated to be 63 (NAMEDATALEN - 1) characters. It also seems to be\nfine to use current_setting('max_identifier_length') instead of\nmax_identifier_length of pg_control_init().\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Tue, 28 Dec 2021 09:32:13 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "On 2021/12/28 9:32, Masahiko Sawada wrote:\n> Doesn't this query return 64? So the expression \"substring(str for\n> (SELECT max_identifier_length FROM pg_control_init()))\" returns the\n> first 64 characters of the given string while the application_name is\n> truncated to be 63 (NAMEDATALEN - 1) characters. It also seems to be\n> fine to use current_setting('max_identifier_length') instead of\n> max_identifier_length of pg_control_init().\n\nInteresting! I agree that current_setting('max_identifier_length') should be used instead. Attached is the updated version of the patch. It uses current_setting('max_identifier_length').\n\nBTW it seems confusing that pg_control_init() (also pg_controldata) and GUC report different values as max_identifier_length. Probably they should return the same value such as NAMEDATALEN - 1. But this change might be overkill...\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION", "msg_date": "Tue, 28 Dec 2021 15:29:21 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "On Tue, Dec 28, 2021 at 3:29 PM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n>\n>\n>\n> On 2021/12/28 9:32, Masahiko Sawada wrote:\n> > Doesn't this query return 64? So the expression \"substring(str for\n> > (SELECT max_identifier_length FROM pg_control_init()))\" returns the\n> > first 64 characters of the given string while the application_name is\n> > truncated to be 63 (NAMEDATALEN - 1) characters. It also seems to be\n> > fine to use current_setting('max_identifier_length') instead of\n> > max_identifier_length of pg_control_init().\n>\n> Interesting! I agree that current_setting('max_identifier_length') should be used instead. Attached is the updated version of the patch. It uses current_setting('max_identifier_length').\n\nThank you for updating the patch! It looks good to me.\n\n>\n> BTW it seems confusing that pg_control_init() (also pg_controldata) and GUC report different values as max_identifier_length. Probably they should return the same value such as NAMEDATALEN - 1. But this change might be overkill...\n\nAgreed. Probably we can fix it in a separate patch if necessary.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Wed, 29 Dec 2021 10:34:31 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "At Wed, 29 Dec 2021 10:34:31 +0900, Masahiko Sawada <sawada.mshk@gmail.com> wrote in \n> On Tue, Dec 28, 2021 at 3:29 PM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n> >\n> >\n> >\n> > On 2021/12/28 9:32, Masahiko Sawada wrote:\n> > > Doesn't this query return 64? So the expression \"substring(str for\n> > > (SELECT max_identifier_length FROM pg_control_init()))\" returns the\n> > > first 64 characters of the given string while the application_name is\n> > > truncated to be 63 (NAMEDATALEN - 1) characters. It also seems to be\n> > > fine to use current_setting('max_identifier_length') instead of\n> > > max_identifier_length of pg_control_init().\n> >\n> > Interesting! I agree that current_setting('max_identifier_length') should be used instead. Attached is the updated version of the patch. It uses current_setting('max_identifier_length').\n> \n> Thank you for updating the patch! It looks good to me.\n\npg_terminate_backend returns just after kill() returns. So I'm afraid\nthat there's a case where the next access to ft6 happens before the\nold connection actually ends on slow machines or under heavy load.\n\n> > BTW it seems confusing that pg_control_init() (also pg_controldata) and GUC report different values as max_identifier_length. Probably they should return the same value such as NAMEDATALEN - 1. But this change might be overkill...\n> \n> Agreed. Probably we can fix it in a separate patch if necessary.\n\nAgree to another patch, but I think we should at least add a caution\nthat they are different. I'm not sure we can change the context of\nControlFileData.nameDataLen.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Tue, 04 Jan 2022 12:04:58 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "On Tue, Jan 4, 2022 at 12:05 PM Kyotaro Horiguchi\n<horikyota.ntt@gmail.com> wrote:\n>\n> At Wed, 29 Dec 2021 10:34:31 +0900, Masahiko Sawada <sawada.mshk@gmail.com> wrote in\n> > On Tue, Dec 28, 2021 at 3:29 PM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n> > >\n> > >\n> > >\n> > > On 2021/12/28 9:32, Masahiko Sawada wrote:\n> > > > Doesn't this query return 64? So the expression \"substring(str for\n> > > > (SELECT max_identifier_length FROM pg_control_init()))\" returns the\n> > > > first 64 characters of the given string while the application_name is\n> > > > truncated to be 63 (NAMEDATALEN - 1) characters. It also seems to be\n> > > > fine to use current_setting('max_identifier_length') instead of\n> > > > max_identifier_length of pg_control_init().\n> > >\n> > > Interesting! I agree that current_setting('max_identifier_length') should be used instead. Attached is the updated version of the patch. It uses current_setting('max_identifier_length').\n> >\n> > Thank you for updating the patch! It looks good to me.\n>\n> pg_terminate_backend returns just after kill() returns. So I'm afraid\n> that there's a case where the next access to ft6 happens before the\n> old connection actually ends on slow machines or under heavy load.\n\nThe test does pg_terminate_backend() with a timeout, and in this case,\ndon't we wait for the backend to end after sending the signal?\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Tue, 4 Jan 2022 12:36:32 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" }, { "msg_contents": "At Tue, 4 Jan 2022 12:36:32 +0900, Masahiko Sawada <sawada.mshk@gmail.com> wrote in \n> On Tue, Jan 4, 2022 at 12:05 PM Kyotaro Horiguchi\n> <horikyota.ntt@gmail.com> wrote:\n> > pg_terminate_backend returns just after kill() returns. So I'm afraid\n> > that there's a case where the next access to ft6 happens before the\n> > old connection actually ends on slow machines or under heavy load.\n> \n> The test does pg_terminate_backend() with a timeout, and in this case,\n> don't we wait for the backend to end after sending the signal?\n\nOops! I missed that part. I agree that it works. Thanks!\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Tue, 04 Jan 2022 14:03:57 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow escape in application_name" } ]
[ { "msg_contents": "If we drop a column we cascade that drop to all indexes and all\nconstraints that mention that column, even if they include other\ncolumns also. We might expect that indexes should be dropped\nautomatically, but the latter behavior for constraints seems like a\nbug, since it can silently remove constraints that might still be\nvalid without the dropped column. (Example below). This is even more\nsurprising if the user specifies RESTRICT explicitly. I note that this\nis acting as documented, it's just the docs don't explain the full\nimplications, so I'm guessing we didn't think about this before.\n\nThe effect of accidentally removing a constraint can be fairly\ndramatic, for example, tables suddenly start refusing updates/deletes\nif they are part of a publication, or partitioning schemes that depend\nupon check constraints can suddenly stop working. As well as the more\nobvious loss of protection from bad input data.\n\nISTM that we should refuse to drop constraints, if the constraint is\nalso dependent upon other columns that will remain in the table,\nunless the user requests CASCADE.\n\n- - -\n\ncreate table abc (a int, b int, c int, primary key (a,b,c), check (a >\n5 and b is not null and c > 10));\n\ncreate index bc on abc (b, c);\n\n\\d abc\n Table \"public.abc\"\n Column | Type | Collation | Nullable | Default\n--------+---------+-----------+----------+---------\n a | integer | | not null |\n b | integer | | not null |\n c | integer | | not null |\n\nIndexes:\n \"abc_pkey\" PRIMARY KEY, btree (a, b, c)\n \"bc\" btree (b, c)\nCheck constraints:\n \"abc_c_check\" CHECK (c > 9)\n \"abc_check\" CHECK (a > 5 AND b IS NOT NULL AND c > 10)\n\nalter table abc drop column c restrict;\n\n\\d abc\n Table \"public.abc\"\n Column | Type | Collation | Nullable | Default\n--------+---------+-----------+----------+---------\n a | integer | | not null |\n b | integer | | not null |\n\nNoting that all constraints have been removed, not just the ones\nwholly dependent on dropped columns.\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/\n\n\n", "msg_date": "Thu, 5 Aug 2021 08:35:46 +0100", "msg_from": "Simon Riggs <simon.riggs@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Accidentally dropped constraints: bug?" }, { "msg_contents": "On Thu, Aug 5, 2021 at 08:35:46AM +0100, Simon Riggs wrote:\n> If we drop a column we cascade that drop to all indexes and all\n> constraints that mention that column, even if they include other\n> columns also. We might expect that indexes should be dropped\n> automatically, but the latter behavior for constraints seems like a\n> bug, since it can silently remove constraints that might still be\n> valid without the dropped column. (Example below). This is even more\n> surprising if the user specifies RESTRICT explicitly. I note that this\n> is acting as documented, it's just the docs don't explain the full\n> implications, so I'm guessing we didn't think about this before.\n\nWow, I certainly never thought of it or heard anyone complain about it.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Thu, 5 Aug 2021 16:09:01 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Accidentally dropped constraints: bug?" }, { "msg_contents": "\n\n> On Aug 5, 2021, at 12:35 AM, Simon Riggs <simon.riggs@enterprisedb.com> wrote:\n> \n> Noting that all constraints have been removed, not just the ones\n> wholly dependent on dropped columns.\n\nI don't find this all that surprising. If CHECK (a > 5 AND b IS NOT NULL AND c > 10) is really meant as three independent checks, it should be written that way. However, for any row where c is null, the entire expression will either be null or false, and the check will fail precisely when (a > 5 AND b IS NOT NULL) is false. So if you imagine the dropped column as a column of phantom null values, you'd expect the check to still reject rows where a <= 5 or b is null.\n\nIs it reasonable to imagine the dropped column as implicitly full of nulls? That's how an added column works, but do we think about dropped columns that way?\n\nIn any event, the documentation is pretty clear about this:\n\n> DROP COLUMN [ IF EXISTS ]\n> This form drops a column from a table. Indexes and table constraints involving the column will be automatically dropped as well.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Thu, 5 Aug 2021 15:30:20 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Accidentally dropped constraints: bug?" } ]
[ { "msg_contents": "In expanded mode psql calculates the width of the longest field in all the output rows,\nand prints the header line according to it. This often results in record header wrapping\nover several lines (see example below).\n\nThis huge record header is printed the same way before each record, even if all the fields\nin current record are small and fit into terminal width. This often leads to situations\nwhen record header occupies the entirety of the screen, for all records, even though there are\nonly a few records with huge fields in a record set.\n\nMaybe we can avoid making the header line longer than terminal width for \\pset border 0\nand \\pset border 1? We already have terminal width calculated. Please see attached a patch\nwith the proposed implementation.\n\nExample output before the modification, in a terminal with a 100-column width:\n\n$ psql template1 -c \"\\x on\" -c \"\\pset border 1;\" -c \"select n, repeat('x', n) as long_column_name from unnest(array[42,210]) as n\"\nExpanded display is on.\nBorder style is 1.\n─[ RECORD 1 ]────┬──────────────────────────────────────────────────────────────────────────────────\n────────────────────────────────────────────────────────────────────────────────────────────────────\n─────────────────────────────\nn │ 42\nlong_column_name │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n─[ RECORD 2 ]────┼──────────────────────────────────────────────────────────────────────────────────\n────────────────────────────────────────────────────────────────────────────────────────────────────\n─────────────────────────────\nn │ 210\nlong_column_name │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\nAnd here's the same command after the patch:\n\n$ psql template1 -c \"\\x on\" -c \"\\pset border 1;\" -c \"select n, repeat('x', n) as long_column_name from unnest(array[42,210]) as n\"\nExpanded display is on.\nBorder style is 1.\n─[ RECORD 1 ]────┬──────────────────────────────────────────────────────────────────────────────────\nn │ 42\nlong_column_name │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n─[ RECORD 2 ]────┼──────────────────────────────────────────────────────────────────────────────────\nn │ 210\nlong_column_name │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\nBest regards,\nPlaton Pronko", "msg_date": "Thu, 5 Aug 2021 13:36:45 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "very long record lines in expanded psql output" }, { "msg_contents": "Hi\r\n\r\nčt 5. 8. 2021 v 12:36 odesílatel Platon Pronko <platon7pronko@gmail.com>\r\nnapsal:\r\n\r\n> In expanded mode psql calculates the width of the longest field in all the\r\n> output rows,\r\n> and prints the header line according to it. This often results in record\r\n> header wrapping\r\n> over several lines (see example below).\r\n>\r\n> This huge record header is printed the same way before each record, even\r\n> if all the fields\r\n> in current record are small and fit into terminal width. This often leads\r\n> to situations\r\n> when record header occupies the entirety of the screen, for all records,\r\n> even though there are\r\n> only a few records with huge fields in a record set.\r\n>\r\n> Maybe we can avoid making the header line longer than terminal width for\r\n> \\pset border 0\r\n> and \\pset border 1? We already have terminal width calculated. Please see\r\n> attached a patch\r\n> with the proposed implementation.\r\n>\r\n> Example output before the modification, in a terminal with a 100-column\r\n> width:\r\n>\r\n> $ psql template1 -c \"\\x on\" -c \"\\pset border 1;\" -c \"select n, repeat('x',\r\n> n) as long_column_name from unnest(array[42,210]) as n\"\r\n> Expanded display is on.\r\n> Border style is 1.\r\n> ─[ RECORD 1\r\n> ]────┬──────────────────────────────────────────────────────────────────────────────────\r\n>\r\n> ────────────────────────────────────────────────────────────────────────────────────────────────────\r\n> ─────────────────────────────\r\n> n │ 42\r\n> long_column_name │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n> ─[ RECORD 2\r\n> ]────┼──────────────────────────────────────────────────────────────────────────────────\r\n>\r\n> ────────────────────────────────────────────────────────────────────────────────────────────────────\r\n> ─────────────────────────────\r\n> n │ 210\r\n> long_column_name │\r\n> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n>\r\n> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n> xxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n>\r\n> And here's the same command after the patch:\r\n>\r\n> $ psql template1 -c \"\\x on\" -c \"\\pset border 1;\" -c \"select n, repeat('x',\r\n> n) as long_column_name from unnest(array[42,210]) as n\"\r\n> Expanded display is on.\r\n> Border style is 1.\r\n> ─[ RECORD 1\r\n> ]────┬──────────────────────────────────────────────────────────────────────────────────\r\n> n │ 42\r\n> long_column_name │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n> ─[ RECORD 2\r\n> ]────┼──────────────────────────────────────────────────────────────────────────────────\r\n> n │ 210\r\n> long_column_name │\r\n> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n>\r\n> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n> xxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n>\r\n>\r\nthe length of lines should be consistent.\r\n\r\nYour proposal breaks pspg\r\n\r\nhttps://github.com/okbob/pspg\r\n\r\nIt can be separate option, but it should not be default\r\n\r\nPavel\r\n\r\n\r\nBest regards,\r\n> Platon Pronko\r\n>\r\n\nHičt 5. 8. 2021 v 12:36 odesílatel Platon Pronko <platon7pronko@gmail.com> napsal:In expanded mode psql calculates the width of the longest field in all the output rows,\r\nand prints the header line according to it. This often results in record header wrapping\r\nover several lines (see example below).\n\r\nThis huge record header is printed the same way before each record, even if all the fields\r\nin current record are small and fit into terminal width. This often leads to situations\r\nwhen record header occupies the entirety of the screen, for all records, even though there are\r\nonly a few records with huge fields in a record set.\n\r\nMaybe we can avoid making the header line longer than terminal width for \\pset border 0\r\nand \\pset border 1? We already have terminal width calculated. Please see attached a patch\r\nwith the proposed implementation.\n\r\nExample output before the modification, in a terminal with a 100-column width:\n\r\n$ psql template1 -c \"\\x on\" -c \"\\pset border 1;\" -c \"select n, repeat('x', n) as long_column_name from unnest(array[42,210]) as n\"\r\nExpanded display is on.\r\nBorder style is 1.\r\n─[ RECORD 1 ]────┬──────────────────────────────────────────────────────────────────────────────────\r\n────────────────────────────────────────────────────────────────────────────────────────────────────\r\n─────────────────────────────\r\nn                │ 42\r\nlong_column_name │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n─[ RECORD 2 ]────┼──────────────────────────────────────────────────────────────────────────────────\r\n────────────────────────────────────────────────────────────────────────────────────────────────────\r\n─────────────────────────────\r\nn                │ 210\r\nlong_column_name │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\r\nAnd here's the same command after the patch:\n\r\n$ psql template1 -c \"\\x on\" -c \"\\pset border 1;\" -c \"select n, repeat('x', n) as long_column_name from unnest(array[42,210]) as n\"\r\nExpanded display is on.\r\nBorder style is 1.\r\n─[ RECORD 1 ]────┬──────────────────────────────────────────────────────────────────────────────────\r\nn                │ 42\r\nlong_column_name │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n─[ RECORD 2 ]────┼──────────────────────────────────────────────────────────────────────────────────\r\nn                │ 210\r\nlong_column_name │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nthe length of lines should be consistent.Your proposal breaks pspghttps://github.com/okbob/pspgIt can be separate option, but it should not be defaultPavel \r\nBest regards,\r\nPlaton Pronko", "msg_date": "Thu, 5 Aug 2021 12:56:17 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "Hi!\n\npspg looks nice :)\n\n> Your proposal breaks pspg\n> \n> https://github.com/okbob/pspg\n\nI tried the following (after the patch):\n\n./psql template1 -c \"select n, repeat('x', n) as long_column_name from unnest(array[42,210]) as n\" | pspg\n\nAnd it seems that pspg handled the situation without any issue. Also I tried inserting newlines into the output, and pspg still performed without issue. Can you give an example of scenario which should break after changing the record header length?\n\nBest regards,\nPlaton Pronko\n\n\n", "msg_date": "Thu, 5 Aug 2021 14:14:18 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "čt 5. 8. 2021 v 13:14 odesílatel Platon Pronko <platon7pronko@gmail.com>\nnapsal:\n\n> Hi!\n>\n> pspg looks nice :)\n>\n> > Your proposal breaks pspg\n> >\n> > https://github.com/okbob/pspg\n>\n> I tried the following (after the patch):\n>\n> ./psql template1 -c \"select n, repeat('x', n) as long_column_name from\n> unnest(array[42,210]) as n\" | pspg\n>\n> And it seems that pspg handled the situation without any issue. Also I\n> tried inserting newlines into the output, and pspg still performed without\n> issue. Can you give an example of scenario which should break after\n> changing the record header length?\n>\n\nI think so there can be two basic problems:\n\na) with line cursor\n\nb) format detection - I try to detect the header line - and I expect this\nline has the most length of all lines. I use a line with the same length as\nthe column's type info (data, border).\n\nDid you test the wrapped format? It is working\n\n\\pset format wrapped\n\\x\nselect * from pg_class;\n\n\n\nRegards\n\nPavel\n\n\n\n\n> Best regards,\n> Platon Pronko\n>\n\nčt 5. 8. 2021 v 13:14 odesílatel Platon Pronko <platon7pronko@gmail.com> napsal:Hi!\n\npspg looks nice :)\n\n> Your proposal breaks pspg\n> \n> https://github.com/okbob/pspg\n\nI tried the following (after the patch):\n\n./psql template1 -c \"select n, repeat('x', n) as long_column_name from unnest(array[42,210]) as n\" | pspg\n\nAnd it seems that pspg handled the situation without any issue. Also I tried inserting newlines into the output, and pspg still performed without issue. Can you give an example of scenario which should break after changing the record header length?I think so there can be two basic problems:a) with line cursorb) format detection - I try to detect the header line - and I expect this line has the most length of all lines. I use a line with the same length as the column's type info (data, border).Did you test the wrapped format? It is working\\pset format wrapped\\xselect  * from pg_class;RegardsPavel\n\nBest regards,\nPlaton Pronko", "msg_date": "Thu, 5 Aug 2021 13:46:14 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "Hi!\n\n> a) with line cursor\n\nTried in different configurations, seems that line cursor works fine.\n\n> b) format detection - I try to detect the header line - and I expect this\n> line has the most length of all lines. I use a line with the same length as\n> the column's type info (data, border).\n\nI looked at pspg source, and here's what I found (please correct me if some/all\nof my assumptions are wrong):\n\n1. Input handling and format detection happens in table.c readfile().\n\n2. There's some variables in DataDesc - maxx and maxbytes - that store the\nlongest line seen so far. But they are re-updated on each new row, so the fact\nthat header is shorter shouldn't affect them.\n\n3. Expanded header detection is handled by is_expanded_header function. It has\nei_minx and ei_maxx return pointers, but when it is used from readfile() these\npointers are set to NULL in both cases - so header length is simply ignored.\n\n> Did you test the wrapped format? It is working\n> \n> \\pset format wrapped\n> \\x\n> select * from pg_class;\n\nThere's no difference in outputs in wrapped format, so pspg behavior is also unaffected.\n\nBy the way, it seems that pspg recommends setting \\pset border 2 anyway, so in vast\nmajority of cases there should be no possibility of difference at all - proposed patch\ndoesn't change output for \\pset border 2 (because there's no sane way of making it\nlook okay in presence of long fields anyway).\n\nBest regards,\nPlaton Pronko\n\n\n", "msg_date": "Thu, 5 Aug 2021 16:30:48 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "čt 5. 8. 2021 v 15:30 odesílatel Platon Pronko <platon7pronko@gmail.com>\nnapsal:\n\n> Hi!\n>\n> > a) with line cursor\n>\n> Tried in different configurations, seems that line cursor works fine.\n>\n> > b) format detection - I try to detect the header line - and I expect this\n> > line has the most length of all lines. I use a line with the same length\n> as\n> > the column's type info (data, border).\n>\n> I looked at pspg source, and here's what I found (please correct me if\n> some/all\n> of my assumptions are wrong):\n>\n> 1. Input handling and format detection happens in table.c readfile().\n>\n> 2. There's some variables in DataDesc - maxx and maxbytes - that store the\n> longest line seen so far. But they are re-updated on each new row, so the\n> fact\n> that header is shorter shouldn't affect them.\n>\n> 3. Expanded header detection is handled by is_expanded_header function. It\n> has\n> ei_minx and ei_maxx return pointers, but when it is used from readfile()\n> these\n> pointers are set to NULL in both cases - so header length is simply\n> ignored.\n>\n\nThe problem can be in translate_headline in bad desc->headline_size\n\n\n> > Did you test the wrapped format? It is working\n> >\n> > \\pset format wrapped\n> > \\x\n> > select * from pg_class;\n>\n> There's no difference in outputs in wrapped format, so pspg behavior is\n> also unaffected.\n>\n> By the way, it seems that pspg recommends setting \\pset border 2 anyway,\n> so in vast\n> majority of cases there should be no possibility of difference at all -\n> proposed patch\n> doesn't change output for \\pset border 2 (because there's no sane way of\n> making it\n> look okay in presence of long fields anyway).\n>\n\nAlthough pspg prefers border 2, it is working for all configurations now.\n\nI think your proposal is not good, because it is breaking consistency and\nif people want similar output, then they can use a wrapped format.\n\nRegards\n\nPavel\n\n\n\n\n>\n> Best regards,\n> Platon Pronko\n>\n\nčt 5. 8. 2021 v 15:30 odesílatel Platon Pronko <platon7pronko@gmail.com> napsal:Hi!\n\n> a) with line cursor\n\nTried in different configurations, seems that line cursor works fine.\n\n> b) format detection - I try to detect the header line - and I expect this\n> line has the most length of all lines. I use a line with the same length as\n> the column's type info (data, border).\n\nI looked at pspg source, and here's what I found (please correct me if some/all\nof my assumptions are wrong):\n\n1. Input handling and format detection happens in table.c readfile().\n\n2. There's some variables in DataDesc - maxx and maxbytes - that store the\nlongest line seen so far. But they are re-updated on each new row, so the fact\nthat header is shorter shouldn't affect them.\n\n3. Expanded header detection is handled by is_expanded_header function. It has\nei_minx and ei_maxx return pointers, but when it is used from readfile() these\npointers are set to NULL in both cases - so header length is simply ignored.The problem can be in translate_headline in bad desc->headline_size \n\n> Did you test the wrapped format? It is working\n> \n> \\pset format wrapped\n> \\x\n> select  * from pg_class;\n\nThere's no difference in outputs in wrapped format, so pspg behavior is also unaffected.\n\nBy the way, it seems that pspg recommends setting \\pset border 2 anyway, so in vast\nmajority of cases there should be no possibility of difference at all - proposed patch\ndoesn't change output for \\pset border 2 (because there's no sane way of making it\nlook okay in presence of long fields anyway).Although pspg prefers border 2, it is working for all configurations now.I think your proposal is not good, because it is breaking consistency and if people want similar output, then they can use a wrapped format.RegardsPavel  \n\nBest regards,\nPlaton Pronko", "msg_date": "Thu, 5 Aug 2021 16:03:04 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "Hi!\n\nMy apologies - I was using pspg incorrectly. If it's called via the pipe\nthen all the column wrapping is ignored, and that's why I couldn't reproduce\nthe issues. If instead pspg is used via \"\\setenv PAGER pspg\", then I indeed can't\nscroll the table horizontally more than 1 character, and that's definitely\nbroken.\n\nI'll be using \"\\pset format wrapped\" from now on, it's good enough. My only\nissue would be with copying the long cell contents, but that's an uncommon\ncase and can be worked around without too much trouble.\n\nBest regards,\nPlaton Pronko\n\n\n", "msg_date": "Thu, 5 Aug 2021 17:32:17 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "čt 5. 8. 2021 v 16:32 odesílatel Platon Pronko <platon7pronko@gmail.com>\nnapsal:\n\n> Hi!\n>\n> My apologies - I was using pspg incorrectly. If it's called via the pipe\n> then all the column wrapping is ignored, and that's why I couldn't\n> reproduce\n> the issues. If instead pspg is used via \"\\setenv PAGER pspg\", then I\n> indeed can't\n> scroll the table horizontally more than 1 character, and that's definitely\n> broken.\n>\n> I'll be using \"\\pset format wrapped\" from now on, it's good enough. My only\n> issue would be with copying the long cell contents, but that's an uncommon\n> case and can be worked around without too much trouble.\n>\n\npspg supports copy cell to clipboard - you can copy complete cell, although\nsome parts are invisible\n\nhttps://github.com/okbob/pspg#export--clipboard\n\nbut I am not sure if it is working well in extended mode. This mode is not\nextra tested in pspg\n\nRegards\n\nPavel\n\n\n\n\n\n> Best regards,\n> Platon Pronko\n>\n\nčt 5. 8. 2021 v 16:32 odesílatel Platon Pronko <platon7pronko@gmail.com> napsal:Hi!\n\nMy apologies - I was using pspg incorrectly. If it's called via the pipe\nthen all the column wrapping is ignored, and that's why I couldn't reproduce\nthe issues. If instead pspg is used via \"\\setenv PAGER pspg\", then I indeed can't\nscroll the table horizontally more than 1 character, and that's definitely\nbroken.\n\nI'll be using \"\\pset format wrapped\" from now on, it's good enough. My only\nissue would be with copying the long cell contents, but that's an uncommon\ncase and can be worked around without too much trouble.pspg supports copy cell to clipboard - you can copy complete cell, although some parts are invisiblehttps://github.com/okbob/pspg#export--clipboardbut I am not sure if it is working well in extended mode. This mode is not extra tested in pspgRegardsPavel \n\nBest regards,\nPlaton Pronko", "msg_date": "Thu, 5 Aug 2021 16:38:04 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "Hi!\n\n> pspg supports copy cell to clipboard - you can copy complete cell\n> \n> but I am not sure if it is working well in extended mode. This mode is not\n> extra tested in pspg\n\nThanks for the tip!\n\nI tried it out, in non-extended mode copy indeed works well, in extended mode vertical cursor\nselects both columns (and copies both), and in extended+wrapped mode copy includes wrapping\nsymbol.\n\nBest regards,\nPlaton Pronko\n\n\n", "msg_date": "Thu, 5 Aug 2021 17:50:50 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "čt 5. 8. 2021 v 16:50 odesílatel Platon Pronko <platon7pronko@gmail.com>\nnapsal:\n\n> Hi!\n>\n> > pspg supports copy cell to clipboard - you can copy complete cell\n> >\n> > but I am not sure if it is working well in extended mode. This mode is\n> not\n> > extra tested in pspg\n>\n> Thanks for the tip!\n>\n> I tried it out, in non-extended mode copy indeed works well, in extended\n> mode vertical cursor\n> selects both columns (and copies both), and in extended+wrapped mode copy\n> includes wrapping\n> symbol.\n>\n\nYes, this is probably not finished yet. It was a surprise for me, so I am\nable to use the clipboard from the terminal application, so support for\ncopy is relatively new feature. I'll check it when I have time.\n\nPavel\n\n\n\n\n\n\n\n> Best regards,\n> Platon Pronko\n>\n\nčt 5. 8. 2021 v 16:50 odesílatel Platon Pronko <platon7pronko@gmail.com> napsal:Hi!\n\n> pspg supports copy cell to clipboard - you can copy complete cell\n> \n> but I am not sure if it is working well in extended mode. This mode is not\n> extra tested in pspg\n\nThanks for the tip!\n\nI tried it out, in non-extended mode copy indeed works well, in extended mode vertical cursor\nselects both columns (and copies both), and in extended+wrapped mode copy includes wrapping\nsymbol.Yes, this is probably not finished yet. It was a surprise for me, so I am able to use the clipboard from the terminal application, so support for copy is relatively new feature. I'll check it when I have time.Pavel\n\nBest regards,\nPlaton Pronko", "msg_date": "Thu, 5 Aug 2021 17:13:54 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "\nOn 8/5/21 6:56 AM, Pavel Stehule wrote:\n> Hi\n>\n> čt 5. 8. 2021 v 12:36 odesílatel Platon Pronko\n> <platon7pronko@gmail.com <mailto:platon7pronko@gmail.com>> napsal:\n>\n> In expanded mode psql calculates the width of the longest field in\n> all the output rows,\n> and prints the header line according to it. This often results in\n> record header wrapping\n> over several lines (see example below).\n>\n> This huge record header is printed the same way before each\n> record, even if all the fields\n> in current record are small and fit into terminal width. This\n> often leads to situations\n> when record header occupies the entirety of the screen, for all\n> records, even though there are\n> only a few records with huge fields in a record set.\n>\n> Maybe we can avoid making the header line longer than terminal\n> width for \\pset border 0\n> and \\pset border 1? We already have terminal width calculated.\n> Please see attached a patch\n> with the proposed implementation.\n>\n> Example output before the modification, in a terminal with a\n> 100-column width:\n>\n> $ psql template1 -c \"\\x on\" -c \"\\pset border 1;\" -c \"select n,\n> repeat('x', n) as long_column_name from unnest(array[42,210]) as n\"\n> Expanded display is on.\n> Border style is 1.\n> ─[ RECORD 1\n> ]────┬──────────────────────────────────────────────────────────────────────────────────\n> ────────────────────────────────────────────────────────────────────────────────────────────────────\n> ─────────────────────────────\n> n                │ 42\n> long_column_name │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n> ─[ RECORD 2\n> ]────┼──────────────────────────────────────────────────────────────────────────────────\n> ────────────────────────────────────────────────────────────────────────────────────────────────────\n> ─────────────────────────────\n> n                │ 210\n> long_column_name │\n> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n> xxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n>\n> And here's the same command after the patch:\n>\n> $ psql template1 -c \"\\x on\" -c \"\\pset border 1;\" -c \"select n,\n> repeat('x', n) as long_column_name from unnest(array[42,210]) as n\"\n> Expanded display is on.\n> Border style is 1.\n> ─[ RECORD 1\n> ]────┬──────────────────────────────────────────────────────────────────────────────────\n> n                │ 42\n> long_column_name │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n> ─[ RECORD 2\n> ]────┼──────────────────────────────────────────────────────────────────────────────────\n> n                │ 210\n> long_column_name │\n> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n> xxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n>\n>\n> the length of lines should be consistent.\n>\n> Your proposal breaks pspg\n>\n> https://github.com/okbob/pspg <https://github.com/okbob/pspg>\n>\n> It can be separate option, but it should not be default\n>\n>\n\n\nI also find this annoying and would be happy to be rid of it.  I could\nsee setting an option like\n\n\n\\pset xheader_width column|page|nnn\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Thu, 5 Aug 2021 11:58:09 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "Hi!\n\n> I also find this annoying and would be happy to be rid of it.\n\nHave you tried \"\\pset format wrapped\"? Pavel suggested it, and it solved most of the problem for me, for example.\n\nBest regards,\nPlaton Pronko\n\n\n", "msg_date": "Thu, 5 Aug 2021 19:04:37 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "\nOn 8/5/21 12:04 PM, Platon Pronko wrote:\n> Hi!\n>\n>> I also find this annoying and would be happy to be rid of it.\n>\n> Have you tried \"\\pset format wrapped\"? Pavel suggested it, and it\n> solved most of the problem for me, for example.\n\n\nYes, but it changes the data line output. Ideally, you should be able\nto  modify these independently.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Thu, 5 Aug 2021 12:26:42 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "Hi!\n>>> I also find this annoying and would be happy to be rid of it.\n>>\n>> Have you tried \"\\pset format wrapped\"? Pavel suggested it, and it\n>> solved most of the problem for me, for example.\n> \n> Yes, but it changes the data line output. Ideally, you should be able\n> to  modify these independently.\n\nI agree, and I think this can be implemented, but I'm a bit afraid of\nintroducing an additional psql option (there's already quite a lot of them).\nI suspect primary PostgreSQL maintainers won't be happy with such an approach.\n\nBest regards,\nPlaton Pronko\n\n\n", "msg_date": "Thu, 5 Aug 2021 19:48:13 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "čt 5. 8. 2021 v 18:48 odesílatel Platon Pronko <platon7pronko@gmail.com>\nnapsal:\n\n> Hi!\n> >>> I also find this annoying and would be happy to be rid of it.\n> >>\n> >> Have you tried \"\\pset format wrapped\"? Pavel suggested it, and it\n> >> solved most of the problem for me, for example.\n> >\n> > Yes, but it changes the data line output. Ideally, you should be able\n> > to modify these independently.\n>\n> I agree, and I think this can be implemented, but I'm a bit afraid of\n> introducing an additional psql option (there's already quite a lot of\n> them).\n> I suspect primary PostgreSQL maintainers won't be happy with such an\n> approach.\n>\n\nit can be a fully new format - designed for simple copy from terminal. Some\nlike\n\n====== record: 10 ======\n------------ proname ------------\nleft\n------------ prosrc ------------\n$lalalal\newqrwqerw\newqrwqerqrewq\n$\n===============\n\nRegards\n\nPavel\n\n\n> Best regards,\n> Platon Pronko\n>\n\nčt 5. 8. 2021 v 18:48 odesílatel Platon Pronko <platon7pronko@gmail.com> napsal:Hi!\n>>> I also find this annoying and would be happy to be rid of it.\n>>\n>> Have you tried \"\\pset format wrapped\"? Pavel suggested it, and it\n>> solved most of the problem for me, for example.\n> \n> Yes, but it changes the data line output. Ideally, you should be able\n> to  modify these independently.\n\nI agree, and I think this can be implemented, but I'm a bit afraid of\nintroducing an additional psql option (there's already quite a lot of them).\nI suspect primary PostgreSQL maintainers won't be happy with such an approach.it can be a fully new format - designed for simple copy from terminal. Some like====== record: 10 ====== ------------ proname ------------left ------------ prosrc  ------------$lalalal ewqrwqerwewqrwqerqrewq$===============RegardsPavel\n\nBest regards,\nPlaton Pronko", "msg_date": "Thu, 5 Aug 2021 20:25:36 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "Hi!\n\n>>>>> I also find this annoying and would be happy to be rid of it.\n>>>>\n>>>> Have you tried \"\\pset format wrapped\"? Pavel suggested it, and it\n>>>> solved most of the problem for me, for example.\n>>>\n>>> Yes, but it changes the data line output. Ideally, you should be able\n>>> to modify these independently.\n>>\n>> I agree, and I think this can be implemented, but I'm a bit afraid of\n>> introducing an additional psql option (there's already quite a lot of\n>> them).\n>> I suspect primary PostgreSQL maintainers won't be happy with such an\n>> approach.\n>>\n> \n> it can be a fully new format - designed for simple copy from terminal. Some\n> like\n> \n> ====== record: 10 ======\n> ------------ proname ------------\n> left\n> ------------ prosrc ------------\n> $lalalal\n> ewqrwqerw\n> ewqrwqerqrewq\n> $\n> ===============\n\nI don't think that would be a good idea. If somebody really just needs to copy,\nthen wrapping the query in \"copy (...) to stdout\" already works nicely,\nno need to create a special mode just for that.\nI think the question was more about being able to copy in an ad-hoc way,\nin the middle of scrolling trough \"normal\" output.\n\nBest regards,\nPlaton Pronko\n\n\n", "msg_date": "Thu, 5 Aug 2021 21:30:43 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "čt 5. 8. 2021 v 20:30 odesílatel Platon Pronko <platon7pronko@gmail.com>\nnapsal:\n\n> Hi!\n>\n> >>>>> I also find this annoying and would be happy to be rid of it.\n> >>>>\n> >>>> Have you tried \"\\pset format wrapped\"? Pavel suggested it, and it\n> >>>> solved most of the problem for me, for example.\n> >>>\n> >>> Yes, but it changes the data line output. Ideally, you should be able\n> >>> to modify these independently.\n> >>\n> >> I agree, and I think this can be implemented, but I'm a bit afraid of\n> >> introducing an additional psql option (there's already quite a lot of\n> >> them).\n> >> I suspect primary PostgreSQL maintainers won't be happy with such an\n> >> approach.\n> >>\n> >\n> > it can be a fully new format - designed for simple copy from terminal.\n> Some\n> > like\n> >\n> > ====== record: 10 ======\n> > ------------ proname ------------\n> > left\n> > ------------ prosrc ------------\n> > $lalalal\n> > ewqrwqerw\n> > ewqrwqerqrewq\n> > $\n> > ===============\n>\n> I don't think that would be a good idea. If somebody really just needs to\n> copy,\n> then wrapping the query in \"copy (...) to stdout\" already works nicely,\n> no need to create a special mode just for that.\n>\n\nIt is working well, but it is copy to file, not copy to clipboard.\n\nI think the question was more about being able to copy in an ad-hoc way,\n> in the middle of scrolling trough \"normal\" output.\n>\n\nI understand your motivation, but I don't feel a significant benefit to\nincrease the complexity of the main format (more, when it breaks pspg,\nwithout possibility to fix it). but it can depend on usual data, and it is\ntrue, so when I use pspg, I don't use extended mode too often.\n\n\n> Best regards,\n> Platon Pronko\n>\n\nčt 5. 8. 2021 v 20:30 odesílatel Platon Pronko <platon7pronko@gmail.com> napsal:Hi!\n\n>>>>> I also find this annoying and would be happy to be rid of it.\n>>>>\n>>>> Have you tried \"\\pset format wrapped\"? Pavel suggested it, and it\n>>>> solved most of the problem for me, for example.\n>>>\n>>> Yes, but it changes the data line output. Ideally, you should be able\n>>> to  modify these independently.\n>>\n>> I agree, and I think this can be implemented, but I'm a bit afraid of\n>> introducing an additional psql option (there's already quite a lot of\n>> them).\n>> I suspect primary PostgreSQL maintainers won't be happy with such an\n>> approach.\n>>\n> \n> it can be a fully new format - designed for simple copy from terminal. Some\n> like\n> \n> ====== record: 10 ======\n> ------------ proname ------------\n> left\n> ------------ prosrc  ------------\n> $lalalal\n> ewqrwqerw\n> ewqrwqerqrewq\n> $\n> ===============\n\nI don't think that would be a good idea. If somebody really just needs to copy,\nthen wrapping the query in \"copy (...) to stdout\" already works nicely,\nno need to create a special mode just for that.It is working well, but it is copy to file, not copy to clipboard. \nI think the question was more about being able to copy in an ad-hoc way,\nin the middle of scrolling trough \"normal\" output.I understand your motivation, but I don't feel a significant benefit to increase the complexity of the main format (more, when it breaks pspg, without possibility to fix it). but it can depend on usual data, and it is true, so when I use pspg, I don't use extended mode too often. \n\nBest regards,\nPlaton Pronko", "msg_date": "Thu, 5 Aug 2021 20:37:47 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "Hi!\n\n>> I don't think that would be a good idea. If somebody really just needs to\n>> copy,\n>> then wrapping the query in \"copy (...) to stdout\" already works nicely,\n>> no need to create a special mode just for that.\n>>\n> \n> It is working well, but it is copy to file, not copy to clipboard.\n\nMaybe I misunderstood - are you suggesting this a special mode in pspg? I thought\nthat you were suggesting to implement a mode in psql, something like\n\"\\pset format_for_clipboard\".\n \n>> I think the question was more about being able to copy in an ad-hoc way,\n>> in the middle of scrolling trough \"normal\" output.\n> \n> I understand your motivation, but I don't feel a significant benefit to\n> increase the complexity of the main format (more, when it breaks pspg,\n> without possibility to fix it). but it can depend on usual data, and it is\n> true, so when I use pspg, I don't use extended mode too often.\n\nTo clarify: I'm not suggesting my patch anymore - it definitely breaks pspg and this\nis completely unacceptable.\nWe're just discussing the possible alternate solutions, I think.\n\nBest regards,\nPlaton Pronko\n\n\n", "msg_date": "Thu, 5 Aug 2021 21:48:30 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "čt 5. 8. 2021 v 20:48 odesílatel Platon Pronko <platon7pronko@gmail.com>\nnapsal:\n\n> Hi!\n>\n> >> I don't think that would be a good idea. If somebody really just needs\n> to\n> >> copy,\n> >> then wrapping the query in \"copy (...) to stdout\" already works nicely,\n> >> no need to create a special mode just for that.\n> >>\n> >\n> > It is working well, but it is copy to file, not copy to clipboard.\n>\n> Maybe I misunderstood - are you suggesting this a special mode in pspg? I\n> thought\n> that you were suggesting to implement a mode in psql, something like\n> \"\\pset format_for_clipboard\".\n>\n\nno, it was proposed for psql\n\n\n> >> I think the question was more about being able to copy in an ad-hoc way,\n> >> in the middle of scrolling trough \"normal\" output.\n> >\n> > I understand your motivation, but I don't feel a significant benefit to\n> > increase the complexity of the main format (more, when it breaks pspg,\n> > without possibility to fix it). but it can depend on usual data, and it\n> is\n> > true, so when I use pspg, I don't use extended mode too often.\n>\n> To clarify: I'm not suggesting my patch anymore - it definitely breaks\n> pspg and this\n> is completely unacceptable.\n> We're just discussing the possible alternate solutions, I think.\n>\n\nyes\n\nPavel\n\n\n> Best regards,\n> Platon Pronko\n>\n\nčt 5. 8. 2021 v 20:48 odesílatel Platon Pronko <platon7pronko@gmail.com> napsal:Hi!\n\n>> I don't think that would be a good idea. If somebody really just needs to\n>> copy,\n>> then wrapping the query in \"copy (...) to stdout\" already works nicely,\n>> no need to create a special mode just for that.\n>>\n> \n> It is working well, but it is copy to file, not copy to clipboard.\n\nMaybe I misunderstood - are you suggesting this a special mode in pspg? I thought\nthat you were suggesting to implement a mode in psql, something like\n\"\\pset format_for_clipboard\".no, it was proposed for psql \n\n>> I think the question was more about being able to copy in an ad-hoc way,\n>> in the middle of scrolling trough \"normal\" output.\n> \n> I understand your motivation, but I don't feel a significant benefit to\n> increase the complexity of the main format (more, when it breaks pspg,\n> without possibility to fix it). but it can depend on usual data, and it is\n> true, so when I use pspg, I don't use extended mode too often.\n\nTo clarify: I'm not suggesting my patch anymore - it definitely breaks pspg and this\nis completely unacceptable.\nWe're just discussing the possible alternate solutions, I think.yesPavel\n\nBest regards,\nPlaton Pronko", "msg_date": "Thu, 5 Aug 2021 20:50:09 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "> it can be a fully new format - designed for simple copy from terminal. Some\n> like\n> \n> ====== record: 10 ======\n> ------------ proname ------------\n> left\n> ------------ prosrc ------------\n> $lalalal\n> ewqrwqerw\n> ewqrwqerqrewq\n> $\n> ===============\n\n> no, it was proposed for psql\n\nHow is this better than \"copy (...) to stdout\"? E.g.:\n\n$ copy (select * from pg_class limit 1) to stdout;\n2619\tpg_statistic\t11\t12016\t0\t10\t2\t2619\t0\t18\t402\t18\t2840\tt\tf\tp\tr\t31\t0\tf\tf\tf\tf\tf\tt\tn\tf0\t478\t1\t{postgres=arwdDxt/postgres}\t\\N\t\\N\n\nYou can still copy the necessary parts (using mouse selection) -\nseems that it achieves the the same goal.\n\nBest regards,\nPlaton Pronko\n\n\n", "msg_date": "Thu, 5 Aug 2021 21:56:20 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "čt 5. 8. 2021 v 20:56 odesílatel Platon Pronko <platon7pronko@gmail.com>\nnapsal:\n\n> > it can be a fully new format - designed for simple copy from terminal.\n> Some\n> > like\n> >\n> > ====== record: 10 ======\n> > ------------ proname ------------\n> > left\n> > ------------ prosrc ------------\n> > $lalalal\n> > ewqrwqerw\n> > ewqrwqerqrewq\n> > $\n> > ===============\n>\n> > no, it was proposed for psql\n>\n> How is this better than \"copy (...) to stdout\"? E.g.:\n>\n> $ copy (select * from pg_class limit 1) to stdout;\n> 2619 pg_statistic 11 12016 0 10 2 2619 0\n> 18 402 18 2840 t f p r 31\n> 0 f f f f f t n f0\n> 478 1 {postgres=arwdDxt/postgres} \\N \\N\n>\n> You can still copy the necessary parts (using mouse selection) -\n> seems that it achieves the the same goal.\n>\n\nI think copy format can be pretty unclean when the line will be longer with\nmultiline values or with a lot of values. When the length of the line will\nbe longer than the terminal width, then searching the wanted column can be\npretty difficult.\n\nWhen you know, so any value is on separate line or lines, then selection is\njust primitive, and there is good enough information to find wanted data\nquickly.\n\nFor this case I am working with hypothetical longer records with possible\nmultiline fields - just something that does chaos on the terminal, and you\nwant to select some part of data by mouse from the terminal screen.\n\nRegards\n\nPavel\n\n\n\n\n\n> Best regards,\n> Platon Pronko\n>\n\nčt 5. 8. 2021 v 20:56 odesílatel Platon Pronko <platon7pronko@gmail.com> napsal:> it can be a fully new format - designed for simple copy from terminal. Some\n> like\n> \n> ====== record: 10 ======\n> ------------ proname ------------\n> left\n> ------------ prosrc  ------------\n> $lalalal\n> ewqrwqerw\n> ewqrwqerqrewq\n> $\n> ===============\n\n> no, it was proposed for psql\n\nHow is this better than \"copy (...) to stdout\"? E.g.:\n\n$ copy (select * from pg_class limit 1) to stdout;\n2619    pg_statistic    11      12016   0       10      2       2619    0       18      402     18      2840    t       f       p       r       31      0       f       f       f       f       f       t       n       f0      478     1       {postgres=arwdDxt/postgres}     \\N      \\N\n\nYou can still copy the necessary parts (using mouse selection) -\nseems that it achieves the the same goal.I think copy format can be pretty unclean when the line will be longer with multiline values or with a lot of values.  When the length of the line will be longer than the terminal width, then searching the wanted column can be pretty difficult.When you know, so any value is on separate line or lines, then selection is just primitive, and there is good enough information to find wanted data quickly.For this case I am working with hypothetical longer records with possible multiline fields - just something that does chaos on the terminal, and you want to select some part of data by mouse from the terminal screen.RegardsPavel\n\nBest regards,\nPlaton Pronko", "msg_date": "Thu, 5 Aug 2021 21:08:56 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "\tPlaton Pronko wrote:\n\n> Maybe we can avoid making the header line longer than terminal width\n> for \\pset border 0 and \\pset border 1? We already have terminal\n> width calculated. Please see attached a patch with the proposed\n> implementation.\n\n+1 for doing something against these long lines.\n\nRather than padding up to the terminal's width, we could simply end\nthe line after the \"-[RECORD N]-\" marker, with the idea that the\nrest of it does not add much to readability anyway. \nAnd when writing into a file as opposed to a terminal, getting rid of\nthese lines is useful too.\n\nIn that case, your example could be displayed like this:\n\n=> \\pset expanded on\n=> \\pset border 1\n\n=> select n, repeat('x', n) as long_column_name from unnest(array[42,210])\n as n;\n\n-[ RECORD 1 ]-\nn\t\t | 42\nlong_column_name | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n-[ RECORD 2 ]-\nn\t\t | 210\nlong_column_name |\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n=> \\pset border 0\n=> select n, repeat('x', n) as long_column_name from unnest(array[42,210])\n as n;\n\n* Record 1\nn\t\t 42\nlong_column_name xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n* Record 2\nn\t\t 210\nlong_column_name\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n\n\nBest regards,\n-- \nDaniel Vérité\nPostgreSQL-powered mailer: https://www.manitou-mail.org\nTwitter: @DanielVerite\n\n\n", "msg_date": "Thu, 05 Aug 2021 21:40:01 +0200", "msg_from": "\"Daniel Verite\" <daniel@manitou-mail.org>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "\nOn 8/5/21 2:25 PM, Pavel Stehule wrote:\n>\n>\n> čt 5. 8. 2021 v 18:48 odesílatel Platon Pronko\n> <platon7pronko@gmail.com <mailto:platon7pronko@gmail.com>> napsal:\n>\n> Hi!\n> >>> I also find this annoying and would be happy to be rid of it.\n> >>\n> >> Have you tried \"\\pset format wrapped\"? Pavel suggested it, and it\n> >> solved most of the problem for me, for example.\n> >\n> > Yes, but it changes the data line output. Ideally, you should be\n> able\n> > to  modify these independently.\n>\n> I agree, and I think this can be implemented, but I'm a bit afraid of\n> introducing an additional psql option (there's already quite a lot\n> of them).\n> I suspect primary PostgreSQL maintainers won't be happy with such\n> an approach.\n>\n>\n> it can be a fully new format - designed for simple copy from terminal.\n> Some like\n>\n> ====== record: 10 ======\n> ------------ proname ------------\n> left\n> ------------ prosrc  ------------\n> $lalalal\n> ewqrwqerw\n> ewqrwqerqrewq\n> $\n> ===============\n>\n>\n\nI think that's really a different idea. The original proposal was simply\nto deal with insanely long header lines. This seems like massive scope\ncreep.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Thu, 5 Aug 2021 16:18:05 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "\nOn 8/5/21 12:48 PM, Platon Pronko wrote:\n> Hi!\n>>>> I also find this annoying and would be happy to be rid of it.\n>>>\n>>> Have you tried \"\\pset format wrapped\"? Pavel suggested it, and it\n>>> solved most of the problem for me, for example.\n>>\n>> Yes, but it changes the data line output. Ideally, you should be able\n>> to  modify these independently.\n>\n> I agree, and I think this can be implemented, but I'm a bit afraid of\n> introducing an additional psql option (there's already quite a lot of\n> them).\n> I suspect primary PostgreSQL maintainers won't be happy with such an\n> approach.\n>\n>\n\nI think I qualify as one of those ... :-)\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Thu, 5 Aug 2021 16:19:03 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "Hi!\n\n>>>>> I also find this annoying and would be happy to be rid of it.\n>>>>\n>>>> Have you tried \"\\pset format wrapped\"? Pavel suggested it, and it\n>>>> solved most of the problem for me, for example.\n>>>\n>>> Yes, but it changes the data line output. Ideally, you should be able\n>>> to  modify these independently.\n>>\n>> I agree, and I think this can be implemented, but I'm a bit afraid of\n>> introducing an additional psql option (there's already quite a lot of\n>> them).\n>> I suspect primary PostgreSQL maintainers won't be happy with such an\n>> approach.\n>>\n>>\n> \n> I think I qualify as one of those ... :-)\n\nSorry, I'm new here, don't know who's who :)\n\nI'll start working on a new patch then. A couple questions about specifics:\n\n1. Can we add \"expanded\" in the option name, like \"xheader_expanded_width\"?\nI think adjusting the header row width doesn't make sense on any other modes,\nand placing that in the option name makes intent a bit clearer.\n\n2. What was \"column\" option in your original suggestion supposed to do?\n(\"\\pset xheader_width column|page|nnn\")\n\n3. Should we bother with using this option when in \"\\pset border 2\" mode?\nI can do it for consistency, but it will still look bad.\n\nBest regards,\nPlaton Pronko\n\n\n", "msg_date": "Sat, 7 Aug 2021 17:56:22 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "\nOn 8/7/21 10:56 AM, Platon Pronko wrote:\n> Hi!\n>\n>>>>>> I also find this annoying and would be happy to be rid of it.\n>>>>>\n>>>>> Have you tried \"\\pset format wrapped\"? Pavel suggested it, and it\n>>>>> solved most of the problem for me, for example.\n>>>>\n>>>> Yes, but it changes the data line output. Ideally, you should be able\n>>>> to  modify these independently.\n>>>\n>>> I agree, and I think this can be implemented, but I'm a bit afraid of\n>>> introducing an additional psql option (there's already quite a lot of\n>>> them).\n>>> I suspect primary PostgreSQL maintainers won't be happy with such an\n>>> approach.\n>>>\n>>>\n>>\n>> I think I qualify as one of those ... :-)\n>\n> Sorry, I'm new here, don't know who's who :)\n\n\nNo problem. Welcome! We're always very glad to see new contributors.\n\n\n>\n> I'll start working on a new patch then. A couple questions about\n> specifics:\n>\n> 1. Can we add \"expanded\" in the option name, like\n> \"xheader_expanded_width\"?\n> I think adjusting the header row width doesn't make sense on any other\n> modes,\n> and placing that in the option name makes intent a bit clearer.\n\n\n\n\"xheader\" was meant to be shorthand for \"expanded output header\"\n\n\n>\n> 2. What was \"column\" option in your original suggestion supposed to do?\n> (\"\\pset xheader_width column|page|nnn\")\n\n\nIt's meant to say don't print anything past the column spec, e.g.:\n\n\n-[ RECORD 1 ]----+\nn | 42\nlong_column_name | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n-[ RECORD 2 ]----+\nn | 210\nlong_column_name | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n\n>\n> 3. Should we bother with using this option when in \"\\pset border 2\" mode?\n> I can do it for consistency, but it will still look bad.\n>\n>\n\nProbably not, but since I never use it I'll let others who do weigh in\non the subject.\n\n\ncheers\n\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Sat, 7 Aug 2021 18:18:10 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "čt 5. 8. 2021 v 17:13 odesílatel Pavel Stehule <pavel.stehule@gmail.com>\nnapsal:\n\n>\n>\n> čt 5. 8. 2021 v 16:50 odesílatel Platon Pronko <platon7pronko@gmail.com>\n> napsal:\n>\n>> Hi!\n>>\n>> > pspg supports copy cell to clipboard - you can copy complete cell\n>> >\n>> > but I am not sure if it is working well in extended mode. This mode is\n>> not\n>> > extra tested in pspg\n>>\n>> Thanks for the tip!\n>>\n>> I tried it out, in non-extended mode copy indeed works well, in extended\n>> mode vertical cursor\n>> selects both columns (and copies both), and in extended+wrapped mode copy\n>> includes wrapping\n>> symbol.\n>>\n>\n> Yes, this is probably not finished yet. It was a surprise for me, so I am\n> able to use the clipboard from the terminal application, so support for\n> copy is relatively new feature. I'll check it when I have time.\n>\n\nI fixed this issue. Now, the export should work in wrapped mode too (master\nbranch).\n\nRegards\n\nPavel\n\n\n> Pavel\n>\n>\n>\n>\n>\n>\n>\n>> Best regards,\n>> Platon Pronko\n>>\n>\n\nčt 5. 8. 2021 v 17:13 odesílatel Pavel Stehule <pavel.stehule@gmail.com> napsal:čt 5. 8. 2021 v 16:50 odesílatel Platon Pronko <platon7pronko@gmail.com> napsal:Hi!\n\n> pspg supports copy cell to clipboard - you can copy complete cell\n> \n> but I am not sure if it is working well in extended mode. This mode is not\n> extra tested in pspg\n\nThanks for the tip!\n\nI tried it out, in non-extended mode copy indeed works well, in extended mode vertical cursor\nselects both columns (and copies both), and in extended+wrapped mode copy includes wrapping\nsymbol.Yes, this is probably not finished yet. It was a surprise for me, so I am able to use the clipboard from the terminal application, so support for copy is relatively new feature. I'll check it when I have time.I fixed this issue. Now, the export should work in wrapped mode too (master branch).RegardsPavelPavel\n\nBest regards,\nPlaton Pronko", "msg_date": "Sun, 8 Aug 2021 15:33:14 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "Hi!\n\nPlease find attached the patch implementing the proposed changes.\nI hope I didn't forget anything (docs, tab completion, comments, etc),\nif I did forget something please tell me and I'll fix it.\n\nBest regards,\nPlaton Pronko\n\nOn 2021-08-08 01:18, Andrew Dunstan wrote:\n> \n> On 8/7/21 10:56 AM, Platon Pronko wrote:\n>> Hi!\n>>\n>>>>>>> I also find this annoying and would be happy to be rid of it.\n>>>>>>\n>>>>>> Have you tried \"\\pset format wrapped\"? Pavel suggested it, and it\n>>>>>> solved most of the problem for me, for example.\n>>>>>\n>>>>> Yes, but it changes the data line output. Ideally, you should be able\n>>>>> to  modify these independently.\n>>>>\n>>>> I agree, and I think this can be implemented, but I'm a bit afraid of\n>>>> introducing an additional psql option (there's already quite a lot of\n>>>> them).\n>>>> I suspect primary PostgreSQL maintainers won't be happy with such an\n>>>> approach.\n>>>>\n>>>>\n>>>\n>>> I think I qualify as one of those ... :-)\n>>\n>> Sorry, I'm new here, don't know who's who :)\n> \n> \n> No problem. Welcome! We're always very glad to see new contributors.\n> \n> \n>>\n>> I'll start working on a new patch then. A couple questions about\n>> specifics:\n>>\n>> 1. Can we add \"expanded\" in the option name, like\n>> \"xheader_expanded_width\"?\n>> I think adjusting the header row width doesn't make sense on any other\n>> modes,\n>> and placing that in the option name makes intent a bit clearer.\n> \n> \n> \n> \"xheader\" was meant to be shorthand for \"expanded output header\"\n> \n> \n>>\n>> 2. What was \"column\" option in your original suggestion supposed to do?\n>> (\"\\pset xheader_width column|page|nnn\")\n> \n> \n> It's meant to say don't print anything past the column spec, e.g.:\n> \n> \n> -[ RECORD 1 ]----+\n> n | 42\n> long_column_name | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n> -[ RECORD 2 ]----+\n> n | 210\n> long_column_name | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n> \n> \n>>\n>> 3. Should we bother with using this option when in \"\\pset border 2\" mode?\n>> I can do it for consistency, but it will still look bad.\n>>\n>>\n> \n> Probably not, but since I never use it I'll let others who do weigh in\n> on the subject.\n> \n> \n> cheers\n> \n> \n> andrew\n> \n> \n> --\n> Andrew Dunstan\n> EDB: https://www.enterprisedb.com\n> \n\n\n", "msg_date": "Mon, 23 Aug 2021 20:51:24 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "Hi!\n\nApparently I did forget something, and that's the patch itself :)\nThanks for Justin Pryzby for pointing this out.\n\nAttaching the patch now.\n\nBest regards,\nPlaton Pronko\n\nOn 2021-08-23 20:51, Platon Pronko wrote:\n> Hi!\n> \n> Please find attached the patch implementing the proposed changes.\n> I hope I didn't forget anything (docs, tab completion, comments, etc),\n> if I did forget something please tell me and I'll fix it.\n> \n> Best regards,\n> Platon Pronko\n> \n> On 2021-08-08 01:18, Andrew Dunstan wrote:\n>>\n>> On 8/7/21 10:56 AM, Platon Pronko wrote:\n>>> Hi!\n>>>\n>>>>>>>> I also find this annoying and would be happy to be rid of it.\n>>>>>>>\n>>>>>>> Have you tried \"\\pset format wrapped\"? Pavel suggested it, and it\n>>>>>>> solved most of the problem for me, for example.\n>>>>>>\n>>>>>> Yes, but it changes the data line output. Ideally, you should be able\n>>>>>> to  modify these independently.\n>>>>>\n>>>>> I agree, and I think this can be implemented, but I'm a bit afraid of\n>>>>> introducing an additional psql option (there's already quite a lot of\n>>>>> them).\n>>>>> I suspect primary PostgreSQL maintainers won't be happy with such an\n>>>>> approach.\n>>>>>\n>>>>>\n>>>>\n>>>> I think I qualify as one of those ... :-)\n>>>\n>>> Sorry, I'm new here, don't know who's who :)\n>>\n>>\n>> No problem. Welcome! We're always very glad to see new contributors.\n>>\n>>\n>>>\n>>> I'll start working on a new patch then. A couple questions about\n>>> specifics:\n>>>\n>>> 1. Can we add \"expanded\" in the option name, like\n>>> \"xheader_expanded_width\"?\n>>> I think adjusting the header row width doesn't make sense on any other\n>>> modes,\n>>> and placing that in the option name makes intent a bit clearer.\n>>\n>>\n>>\n>> \"xheader\" was meant to be shorthand for \"expanded output header\"\n>>\n>>\n>>>\n>>> 2. What was \"column\" option in your original suggestion supposed to do?\n>>> (\"\\pset xheader_width column|page|nnn\")\n>>\n>>\n>> It's meant to say don't print anything past the column spec, e.g.:\n>>\n>>\n>> -[ RECORD 1 ]----+\n>> n                | 42\n>> long_column_name | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n>> -[ RECORD 2 ]----+\n>> n                | 210\n>> long_column_name | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n>>\n>>\n>>>\n>>> 3. Should we bother with using this option when in \"\\pset border 2\" mode?\n>>> I can do it for consistency, but it will still look bad.\n>>>\n>>>\n>>\n>> Probably not, but since I never use it I'll let others who do weigh in\n>> on the subject.\n>>\n>>\n>> cheers\n>>\n>>\n>> andrew\n>>\n>>\n>> -- \n>> Andrew Dunstan\n>> EDB: https://www.enterprisedb.com\n>>", "msg_date": "Mon, 23 Aug 2021 21:00:22 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "\nOn 8/23/21 2:00 PM, Platon Pronko wrote:\n> Hi!\n>\n> Apparently I did forget something, and that's the patch itself :)\n> Thanks for Justin Pryzby for pointing this out.\n>\n> Attaching the patch now.\n>\n>\n\nPlease add it to the commitfest, the next one starts in about a week.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Mon, 23 Aug 2021 14:14:27 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "Hi!\n\nDone, here's the link: https://commitfest.postgresql.org/34/3295/\n\nBest regards,\nPlaton Pronko\n\nOn 2021-08-23 21:14, Andrew Dunstan wrote:\n> \n> On 8/23/21 2:00 PM, Platon Pronko wrote:\n>> Hi!\n>>\n>> Apparently I did forget something, and that's the patch itself :)\n>> Thanks for Justin Pryzby for pointing this out.\n>>\n>> Attaching the patch now.\n>>\n>>\n> \n> Please add it to the commitfest, the next one starts in about a week.\n> \n> \n> cheers\n> \n> \n> andrew\n> \n> --\n> Andrew Dunstan\n> EDB: https://www.enterprisedb.com\n> \n\n\n", "msg_date": "Mon, 23 Aug 2021 21:46:57 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "\nOn 8/23/21 2:00 PM, Platon Pronko wrote:\n> Hi!\n>\n> Apparently I did forget something, and that's the patch itself :)\n> Thanks for Justin Pryzby for pointing this out.\n>\n> Attaching the patch now.\n>\n>\n\n(Please avoid top-posting on PostgreSQL lists)\n\n\nThis patch seems basically sound. A couple of things:\n\n\n1. It's not following project indentation style (BSD brace placement)\n\n2. It would possibly be better to pass the relevant parts of the options\nto print_aligned_vertical_line() rather than the whole options\nstructure. It feels odd to pass both that and opt_border.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Thu, 23 Sep 2021 15:28:04 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "On 2021-09-23 22:28, Andrew Dunstan wrote:\n>\n> 2. It would possibly be better to pass the relevant parts of the options\n> to print_aligned_vertical_line() rather than the whole options\n> structure. It feels odd to pass both that and opt_border.\n\nWhat do you think about doing it the other way around - passing only whole\noptions structure? That way we will roll 4 parameters (opt_border, printTextFormat,\nand two xheader ones) into only one argument.\nThis increases code coupling a bit, but I'm not sure if that's relevant here.\n\nBest regards,\nPlaton Pronko\n\n\n", "msg_date": "Fri, 24 Sep 2021 07:49:32 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "\nOn 9/24/21 12:49 AM, Platon Pronko wrote:\n> On 2021-09-23 22:28, Andrew Dunstan wrote:\n>>\n>> 2. It would possibly be better to pass the relevant parts of the options\n>> to print_aligned_vertical_line() rather than the whole options\n>> structure. It feels odd to pass both that and opt_border.\n>\n> What do you think about doing it the other way around - passing only\n> whole\n> options structure? That way we will roll 4 parameters (opt_border,\n> printTextFormat,\n> and two xheader ones) into only one argument.\n> This increases code coupling a bit, but I'm not sure if that's\n> relevant here.\n>\n\nSure, as long as it doesn't result in duplicated computation.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Fri, 24 Sep 2021 07:42:53 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "On 2021-09-24 14:42, Andrew Dunstan wrote:\n> \n> On 9/24/21 12:49 AM, Platon Pronko wrote:\n>> On 2021-09-23 22:28, Andrew Dunstan wrote:\n>>>\n>>> 2. It would possibly be better to pass the relevant parts of the options\n>>> to print_aligned_vertical_line() rather than the whole options\n>>> structure. It feels odd to pass both that and opt_border.\n>>\n>> What do you think about doing it the other way around - passing only\n>> whole\n>> options structure? That way we will roll 4 parameters (opt_border,\n>> printTextFormat,\n>> and two xheader ones) into only one argument.\n>> This increases code coupling a bit, but I'm not sure if that's\n>> relevant here.\n>>\n> \n> Sure, as long as it doesn't result in duplicated computation.\n\nHi!\n\nPlease find attached the updated patch - with fixed braces and\nadjusted parameters to print_aligned_vertical_line().\n\nBest regards,\nPlaton Pronko", "msg_date": "Sun, 3 Oct 2021 15:57:33 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "On Sun, Oct 3, 2021 at 5:57 AM Platon Pronko <platon7pronko@gmail.com>\nwrote:\n\n> On 2021-09-24 14:42, Andrew Dunstan wrote:\n> >\n> > On 9/24/21 12:49 AM, Platon Pronko wrote:\n> >> On 2021-09-23 22:28, Andrew Dunstan wrote:\n> >>>\n> >>> 2. It would possibly be better to pass the relevant parts of the\n> options\n> >>> to print_aligned_vertical_line() rather than the whole options\n> >>> structure. It feels odd to pass both that and opt_border.\n> >>\n> >> What do you think about doing it the other way around - passing only\n> >> whole\n> >> options structure? That way we will roll 4 parameters (opt_border,\n> >> printTextFormat,\n> >> and two xheader ones) into only one argument.\n> >> This increases code coupling a bit, but I'm not sure if that's\n> >> relevant here.\n> >>\n> >\n> > Sure, as long as it doesn't result in duplicated computation.\n>\n> Hi!\n>\n> Please find attached the updated patch - with fixed braces and\n> adjusted parameters to print_aligned_vertical_line().\n>\n> Best regards,\n> Platon Pronko\n\n\nHi,\n\n+ pg_log_error(\"\\\\pset: allowed xheader_width values are full\n(default), column, page, or an number specifying exact width.\");\n\n an number specifying -> a number specifying\n\nCheers\n\nOn Sun, Oct 3, 2021 at 5:57 AM Platon Pronko <platon7pronko@gmail.com> wrote:On 2021-09-24 14:42, Andrew Dunstan wrote:\n> \n> On 9/24/21 12:49 AM, Platon Pronko wrote:\n>> On 2021-09-23 22:28, Andrew Dunstan wrote:\n>>>\n>>> 2. It would possibly be better to pass the relevant parts of the options\n>>> to print_aligned_vertical_line() rather than the whole options\n>>> structure. It feels odd to pass both that and opt_border.\n>>\n>> What do you think about doing it the other way around - passing only\n>> whole\n>> options structure? That way we will roll 4 parameters (opt_border,\n>> printTextFormat,\n>> and two xheader ones) into only one argument.\n>> This increases code coupling a bit, but I'm not sure if that's\n>> relevant here.\n>>\n> \n> Sure, as long as it doesn't result in duplicated computation.\n\nHi!\n\nPlease find attached the updated patch - with fixed braces and\nadjusted parameters to print_aligned_vertical_line().\n\nBest regards,\nPlaton PronkoHi,+               pg_log_error(\"\\\\pset: allowed xheader_width values are full (default), column, page, or an number specifying exact width.\"); an number specifying -> a number specifyingCheers", "msg_date": "Sun, 3 Oct 2021 08:51:21 -0700", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "> Hi,\n> \n> + pg_log_error(\"\\\\pset: allowed xheader_width values are full\n> (default), column, page, or an number specifying exact width.\");\n> \n> an number specifying -> a number specifying\n> \n> Cheers\n> \n\nFixed, attaching the updated patch. Thank you!\n\nBest regards,\nPlaton Pronko", "msg_date": "Sun, 3 Oct 2021 23:03:25 +0300", "msg_from": "Platon Pronko <platon7pronko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "\nOn 2021-10-03 Su 16:03, Platon Pronko wrote:\n>> Hi,\n>>\n>> +               pg_log_error(\"\\\\pset: allowed xheader_width values\n>> are full\n>> (default), column, page, or an number specifying exact width.\");\n>>\n>>   an number specifying -> a number specifying\n>>\n>> Cheers\n>>\n>\n> Fixed, attaching the updated patch. Thank you!\n>\n>\n\nCommitted. There were a couple of bits missing, which I filled in, and I\nchanged the behaviour when the option is given without an argument, so\nthat instead of resetting it the current value is shown, similarly to\nhow most pset options work.\n\n\ncheers\n\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Mon, 25 Jul 2022 14:27:22 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" }, { "msg_contents": "Re: Andrew Dunstan\n> >> +�������������� pg_log_error(\"\\\\pset: allowed xheader_width values are full\n> >> (default), column, page, or an number specifying exact width.\");\n\n> Committed. There were a couple of bits missing, which I filled in, and I\n> changed the behaviour when the option is given without an argument, so\n> that instead of resetting it the current value is shown, similarly to\n> how most pset options work.\n\nThanks for implementing this! This has been #1 on my PG annoyances\nlist since forever. I had even tried to patch it 10� years ago, but\never managed to get that patch to submittable quality.\n\nNow, is there a chance that we could make this the default? Having\npsql print a whole screen of ------------ minus characters doesn't\nseem very useful as default behavior.\n\nI see upthread that Pavel was objecting to that because pspg doesn't\nunderstand it. But since the expanded format is a one-column output,\nand the only thing pspg needs to know is the maxium line length, I'd\nthink pspg could just look at each line, and update the maximum as it\nreads the input anyway.\n\nCan we set 'page' as default?\n\nChristoph\n\n\n", "msg_date": "Tue, 30 Aug 2022 15:49:44 +0200", "msg_from": "Christoph Berg <myon@debian.org>", "msg_from_op": false, "msg_subject": "\\pset xheader_width page as default? (Re: very long record lines in\n expanded psql output)" }, { "msg_contents": "út 30. 8. 2022 v 15:49 odesílatel Christoph Berg <myon@debian.org> napsal:\n\n> Re: Andrew Dunstan\n> > >> + pg_log_error(\"\\\\pset: allowed xheader_width values\n> are full\n> > >> (default), column, page, or an number specifying exact width.\");\n>\n> > Committed. There were a couple of bits missing, which I filled in, and I\n> > changed the behaviour when the option is given without an argument, so\n> > that instead of resetting it the current value is shown, similarly to\n> > how most pset options work.\n>\n> Thanks for implementing this! This has been #1 on my PG annoyances\n> list since forever. I had even tried to patch it 10½ years ago, but\n> ever managed to get that patch to submittable quality.\n>\n> Now, is there a chance that we could make this the default? Having\n> psql print a whole screen of ------------ minus characters doesn't\n> seem very useful as default behavior.\n>\n> I see upthread that Pavel was objecting to that because pspg doesn't\n> understand it. But since the expanded format is a one-column output,\n> and the only thing pspg needs to know is the maxium line length, I'd\n> think pspg could just look at each line, and update the maximum as it\n> reads the input anyway.\n>\n\npspg requires all lines to have the same width. It can do some corrections\n- but it is hard to detect wanted differences or just plain text format.\n\ncan be nice to have the first invisible row with some information about\nused formatting. pspg does some heuristic but this code is not nice and it\nis fragile.\n\nRegards\n\nPavel\n\n\n> Can we set 'page' as default?\n>\n> Christoph\n>\n>\n>\n\nút 30. 8. 2022 v 15:49 odesílatel Christoph Berg <myon@debian.org> napsal:Re: Andrew Dunstan\n> >> +               pg_log_error(\"\\\\pset: allowed xheader_width values are full\n> >> (default), column, page, or an number specifying exact width.\");\n\n> Committed. There were a couple of bits missing, which I filled in, and I\n> changed the behaviour when the option is given without an argument, so\n> that instead of resetting it the current value is shown, similarly to\n> how most pset options work.\n\nThanks for implementing this! This has been #1 on my PG annoyances\nlist since forever. I had even tried to patch it 10½ years ago, but\never managed to get that patch to submittable quality.\n\nNow, is there a chance that we could make this the default? Having\npsql print a whole screen of ------------ minus characters doesn't\nseem very useful as default behavior.\n\nI see upthread that Pavel was objecting to that because pspg doesn't\nunderstand it. But since the expanded format is a one-column output,\nand the only thing pspg needs to know is the maxium line length, I'd\nthink pspg could just look at each line, and update the maximum as it\nreads the input anyway.pspg requires all lines to have the same width. It can do some corrections - but it is hard to detect wanted differences or just plain text format.can be nice to have the first invisible row with some information about used formatting. pspg does some heuristic but this code is not nice and it is fragile.RegardsPavel\n\nCan we set 'page' as default?\n\nChristoph", "msg_date": "Tue, 30 Aug 2022 16:28:05 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: \\pset xheader_width page as default? (Re: very long record lines\n in expanded psql output)" }, { "msg_contents": "Re: Pavel Stehule\n> pspg requires all lines to have the same width. It can do some corrections\n> - but it is hard to detect wanted differences or just plain text format.\n> \n> can be nice to have the first invisible row with some information about\n> used formatting. pspg does some heuristic but this code is not nice and it\n> is fragile.\n\nI like pspg and use it myself, but I don't think a tool that does the\nright thing by hiding a full screen of ---- from the user should\nhinder making the same progress in psql with a simple pager.\n\nChristoph\n\n\n", "msg_date": "Tue, 30 Aug 2022 16:36:49 +0200", "msg_from": "Christoph Berg <myon@debian.org>", "msg_from_op": false, "msg_subject": "Re: \\pset xheader_width page as default? (Re: very long record lines\n in expanded psql output)" }, { "msg_contents": "út 30. 8. 2022 v 16:36 odesílatel Christoph Berg <myon@debian.org> napsal:\n\n> Re: Pavel Stehule\n> > pspg requires all lines to have the same width. It can do some\n> corrections\n> > - but it is hard to detect wanted differences or just plain text format.\n> >\n> > can be nice to have the first invisible row with some information about\n> > used formatting. pspg does some heuristic but this code is not nice and\n> it\n> > is fragile.\n>\n> I like pspg and use it myself, but I don't think a tool that does the\n> right thing by hiding a full screen of ---- from the user should\n> hinder making the same progress in psql with a simple pager.\n>\n\nASCII allows to set some metadata, that should be invisible in all\ncorrectly implemented pagers.\n\n\n\n>\n> Christoph\n>\n\nút 30. 8. 2022 v 16:36 odesílatel Christoph Berg <myon@debian.org> napsal:Re: Pavel Stehule\n> pspg requires all lines to have the same width. It can do some corrections\n> - but it is hard to detect wanted differences or just plain text format.\n> \n> can be nice to have the first invisible row with some information about\n> used formatting. pspg does some heuristic but this code is not nice and it\n> is fragile.\n\nI like pspg and use it myself, but I don't think a tool that does the\nright thing by hiding a full screen of ---- from the user should\nhinder making the same progress in psql with a simple pager.ASCII allows to set some metadata, that should be invisible in all correctly implemented pagers. \n\nChristoph", "msg_date": "Tue, 30 Aug 2022 16:49:57 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: \\pset xheader_width page as default? (Re: very long record lines\n in expanded psql output)" }, { "msg_contents": "út 30. 8. 2022 v 16:49 odesílatel Pavel Stehule <pavel.stehule@gmail.com>\nnapsal:\n\n>\n>\n> út 30. 8. 2022 v 16:36 odesílatel Christoph Berg <myon@debian.org> napsal:\n>\n>> Re: Pavel Stehule\n>> > pspg requires all lines to have the same width. It can do some\n>> corrections\n>> > - but it is hard to detect wanted differences or just plain text format.\n>> >\n>> > can be nice to have the first invisible row with some information about\n>> > used formatting. pspg does some heuristic but this code is not nice and\n>> it\n>> > is fragile.\n>>\n>> I like pspg and use it myself, but I don't think a tool that does the\n>> right thing by hiding a full screen of ---- from the user should\n>> hinder making the same progress in psql with a simple pager.\n>>\n>\n> ASCII allows to set some metadata, that should be invisible in all\n> correctly implemented pagers.\n>\n\nor these parameters can be sent by pager's command line or via some\nenvironment variable. Currently there are only two pagers on the world that\nsupport tabular format, and both are created against psql (pspg and ov), so\nwe can define our own protocol. Surely - pspg will have heuristic forever,\nbecause I want to support psql, mysql and many others. But it can be fine\nto switch to some more robust mode. It can be interesting for continuous\nload via pipe.\n\nRegards\n\nPavel\n\n\n\n>\n>\n>>\n>> Christoph\n>>\n>\n\nút 30. 8. 2022 v 16:49 odesílatel Pavel Stehule <pavel.stehule@gmail.com> napsal:út 30. 8. 2022 v 16:36 odesílatel Christoph Berg <myon@debian.org> napsal:Re: Pavel Stehule\n> pspg requires all lines to have the same width. It can do some corrections\n> - but it is hard to detect wanted differences or just plain text format.\n> \n> can be nice to have the first invisible row with some information about\n> used formatting. pspg does some heuristic but this code is not nice and it\n> is fragile.\n\nI like pspg and use it myself, but I don't think a tool that does the\nright thing by hiding a full screen of ---- from the user should\nhinder making the same progress in psql with a simple pager.ASCII allows to set some metadata, that should be invisible in all correctly implemented pagers.or these parameters can be sent by pager's command line or via some environment variable. Currently there are only two pagers on the world that support tabular format, and both are created against psql (pspg and ov), so we can define our own protocol. Surely - pspg will have heuristic forever, because I want to support psql, mysql and many others. But it can be fine to switch to some more robust mode. It can be interesting for continuous load via pipe.  RegardsPavel \n\nChristoph", "msg_date": "Tue, 30 Aug 2022 16:55:36 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: \\pset xheader_width page as default? (Re: very long record lines\n in expanded psql output)" }, { "msg_contents": "\nOn 2022-08-30 Tu 10:55, Pavel Stehule wrote:\n>\n>\n> út 30. 8. 2022 v 16:49 odesílatel Pavel Stehule\n> <pavel.stehule@gmail.com> napsal:\n>\n>\n>\n> út 30. 8. 2022 v 16:36 odesílatel Christoph Berg <myon@debian.org>\n> napsal:\n>\n> Re: Pavel Stehule\n> > pspg requires all lines to have the same width. It can do\n> some corrections\n> > - but it is hard to detect wanted differences or just plain\n> text format.\n> >\n> > can be nice to have the first invisible row with some\n> information about\n> > used formatting. pspg does some heuristic but this code is\n> not nice and it\n> > is fragile.\n>\n> I like pspg and use it myself, but I don't think a tool that\n> does the\n> right thing by hiding a full screen of ---- from the user should\n> hinder making the same progress in psql with a simple pager.\n>\n>\n> ASCII allows to set some metadata, that should be invisible in all\n> correctly implemented pagers.\n>\n>\n> or these parameters can be sent by pager's command line or via some\n> environment variable. Currently there are only two pagers on the world\n> that support tabular format, and both are created against psql (pspg\n> and ov), so we can define our own protocol. Surely - pspg will have\n> heuristic forever, because I want to support psql, mysql and many\n> others. But it can be fine to switch to some more robust mode. It can\n> be interesting for continuous load via pipe.  \n>\n\nI'm somewhat sympathetic to Christoph's position.\n\nSurely pspg could itself issue\n\n   \\pset xheader_width full\n\nat the start of a session.\n\n\ncheers\n\n\nandrew\n\n-- \n\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Tue, 30 Aug 2022 14:57:48 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: \\pset xheader_width page as default? (Re: very long record lines\n in expanded psql output)" }, { "msg_contents": "On 2022-Jul-25, Andrew Dunstan wrote:\n\n> Committed. There were a couple of bits missing, which I filled in, and I\n> changed the behaviour when the option is given without an argument, so\n> that instead of resetting it the current value is shown, similarly to\n> how most pset options work.\n\nI was translating the new messages introduced by this commit, and\ndecided to unify them. While doing so, I notice that the feature\nmisbehaves when you give it a string value that doesn't match any valid\nvalue: it just resets the value to 0, which is entirely the wrong thing.\nFor other settings, we first verify that the given value is valid, and\nonly then we change the setting.\n\nSo I came up with the attached. While at it, I noticed that we have\nother uses of atoi() there, most notably pager_min_lines. My first\nimpulse was to just to do the same as for xheader_width, namely to test\nwhether the atoid result is zero, and not change in that case. But then\nI noticed we're already using variables.c facilities, so I decided to do\nlikewise; this results in simpler code. So we're now stricter, because\nvariables.c rejects trailing junk after the number. (123asd was\npreviously parsed as 123, now it's an error.)\n\n\nThere remain atoi uses in this code, and aside from the atoi()-induced\nbehavior of making any non-number input set it to 0, it does stuff like\n\n=# \\pset border 65538asd\nBorder style is 2.\n\nbecause border style is short int, so this value overflows it. Same\nhappens with 'columns'. However, this is all very old code and nobody\nseems to have complained.\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n\"¿Cómo puedes confiar en algo que pagas y que no ves,\ny no confiar en algo que te dan y te lo muestran?\" (Germán Poo)", "msg_date": "Fri, 19 May 2023 13:02:05 +0200", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: very long record lines in expanded psql output" } ]
[ { "msg_contents": "Tom,\n\nwhile testing your patch in [1], I stumbled upon the following assert in master, without your patch applied:\n\n+select 'vyrlvyrlwvqko' ~ '(?:(?:((.))))((\\2)\\1.){0,0}?';\n+server closed the connection unexpectedly\n+ This probably means the server terminated abnormally\n+ before or while processing the request.\n+connection to server was lost\n\n\nThe assert itself dates back to a commit of yours from 2003. I don't think you did anything wrong here, but I wonder if you might understand the code better than anyone else?\n\nThe relevant bit of the stack trace is:\n\n frame #3: 0x00000001020eff7d postgres`ExceptionalCondition(conditionName=<unavailable>, errorType=<unavailable>, fileName=<unavailable>, lineNumber=<unavailable>) at assert.c:69:2 [opt]\n frame #4: 0x0000000101e2c682 postgres`delsub(nfa=0x00007fc7e8407360, lp=0x00007fc7e8831010, rp=0x00007fc7e8827328) at regc_nfa.c:1265:2 [opt]\n frame #5: 0x0000000101e28dd8 postgres`parsebranch [inlined] parseqatom(v=<unavailable>, stopper=101, type=112, lp=<unavailable>, rp=0x00007fc7e8827328, top=<unavailable>) at regcomp.c:1084:3 [opt]\n frame #6: 0x0000000101e27de9 postgres`parsebranch(v=0x00007ffeee0a80b8, stopper=101, type=<unavailable>, left=<unavailable>, right=<unavailable>, partial=<unavailable>) at regcomp.c:759 [opt]\n frame #7: 0x0000000101e29719 postgres`parsebranch [inlined] parseqatom(v=<unavailable>, stopper=101, type=112, lp=<unavailable>, rp=0x00007fc7e8827328, top=<unavailable>) at regcomp.c:1282:23 [opt]\n frame #8: 0x0000000101e29639 postgres`parsebranch(v=0x00007ffeee0a80b8, stopper=101, type=<unavailable>, left=<unavailable>, right=<unavailable>, partial=<unavailable>) at regcomp.c:759 [opt]\n frame #9: 0x0000000101e2457b postgres`parse(v=0x00007ffeee0a80b8, stopper=101, type=112, init=0x00007fc7e8827280, final=0x00007fc7e88272b8) at regcomp.c:691:12 [opt]\n frame #10: 0x0000000101e234d2 postgres`pg_regcomp(re=0x00007ffeee0a8208, string=<unavailable>, len=<unavailable>, flags=<unavailable>, collation=<unavailable>) at regcomp.c:418:12 [opt]\n frame #11: 0x0000000101f75790 postgres`RE_compile_and_cache(text_re=<unavailable>, cflags=<unavailable>, collation=100) at regexp.c:186:19 [opt]\n frame #12: 0x0000000101f75b90 postgres`textregexeq [inlined] RE_compile_and_execute(text_re=<unavailable>, dat=<unavailable>, dat_len=13, cflags=3, collation=<unavailable>, nmatch=0, pmatch=<unavailable>) at regexp.c:351:7 [opt]\n\n[1] https://www.postgresql.org/message-id/2219936.1628115334%40sss.pgh.pa.us\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Thu, 5 Aug 2021 13:38:58 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Assert triggered during RE_compile_and_cache" }, { "msg_contents": "\n\n> On Aug 5, 2021, at 1:38 PM, Mark Dilger <mark.dilger@enterprisedb.com> wrote:\n> \n> +select 'vyrlvyrlwvqko' ~ '(?:(?:((.))))((\\2)\\1.){0,0}?';\n\nI've boiled it down a bit more:\n\n+select '' ~ '()\\1{0}';\n+ ?column? \n+----------\n+ t\n+(1 row)\n+\n+select '' ~ '()(\\1){0}';\n+ ?column? \n+----------\n+ t\n+(1 row)\n+\n+select '' ~ '(())\\2{0}';\n+ ?column? \n+----------\n+ t\n+(1 row)\n+\n+select '' ~ '(())(\\2){0}';\n+server closed the connection unexpectedly\n+ This probably means the server terminated abnormally\n+ before or while processing the request.\n+connection to server was lost\n\nAny ideas?\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Thu, 5 Aug 2021 13:49:00 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> +select '' ~ '(())(\\2){0}';\n> +server closed the connection unexpectedly\n\n> Any ideas?\n\nHuh. This seems like some deficiency in the part of parseqatom\nstarting with\n\n\t/* annoying special case: {0} or {0,0} cancels everything */\n\tif (m == 0 && n == 0)\n\nbut I don't immediately see what's different about your failing case\nversus the not-failing ones.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 05 Aug 2021 18:15:27 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" }, { "msg_contents": "> On Aug 5, 2021, at 3:15 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> I don't immediately see what's different about your failing case\n> versus the not-failing ones.\n\nI have now found lots of cases of this failure. I *believe* the backreference is always greater than 1, and it is always in a capture group which then has the {0} or {0,0} applied to it.\n\nYou can find lots of cases using the attached regex generating script I whipped up for testing your work. (Note this is just a quick and dirty tool for hacking, not anything refined.)\n\n\n\n\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Thu, 5 Aug 2021 15:22:57 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> I have now found lots of cases of this failure. I *believe* the backreference is always greater than 1, and it is always in a capture group which then has the {0} or {0,0} applied to it.\n\nHm. I thought that this might be an old issue, but I'm not seeing the\ncrash in pre-v14 branches. That means it's some bug introduced in\nthe performance improvements I did a few months ago. Open item added.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 05 Aug 2021 19:16:22 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" }, { "msg_contents": "I wrote:\n> Hm. I thought that this might be an old issue, but I'm not seeing the\n> crash in pre-v14 branches. That means it's some bug introduced in\n> the performance improvements I did a few months ago. Open item added.\n\ngit bisect says the trouble started with\n\nea1268f6301cc7adce571cc9c5ebe8d9342a2ef4 is the first bad commit\ncommit ea1268f6301cc7adce571cc9c5ebe8d9342a2ef4\nAuthor: Tom Lane <tgl@sss.pgh.pa.us>\nDate: Sat Feb 20 19:26:41 2021 -0500\n\n Avoid generating extra subre tree nodes for capturing parentheses.\n\nI probably won't be able to dig deeper for a little while.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 05 Aug 2021 20:13:03 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" }, { "msg_contents": "I wrote:\n>> Hm. I thought that this might be an old issue, but I'm not seeing the\n>> crash in pre-v14 branches. That means it's some bug introduced in\n>> the performance improvements I did a few months ago. Open item added.\n\n> git bisect says the trouble started with\n> ea1268f6301cc7adce571cc9c5ebe8d9342a2ef4 is the first bad commit\n\nHere's a draft fix for this. The issue seems to be that parseqatom\nrecords where a previous capture group is by saving a pointer to\nthe \"subre\" that parse() returned for it. That was okay before\nsaid commit because we didn't do anything further to that subre:\nwe immediately wrapped it into a parent subre, and then any further\nhacking that parseqatom did was done on the parent subre. But after\nea1268f63, in most cases we'd hack right on that same subre, thus\npotentially modifying the portion of the NFA that would be copied\nby a subsequent back-reference.\n\nThe particular thing that's asserting when you wrap {0} around such\na back-ref is just accidental road kill: it happens to notice that\nthe NFA is no longer consistent, because there's no path leading\nfrom the start to the end of the copied sub-NFA, thanks to the copying\nhaving been done between a pair of states that weren't actually\nappropriate to reference. What surprises me about this is not that\ncrash, but that we didn't see fundamental breakage of backref-using\npatterns all over the place. It evidently breaks only in corner\ncases, but I'm not quite sure why the effects are so limited.\n\nAnyway, the fix seems pretty straightforward. We don't really need\nanything about the subre as such except for its starting and ending\nNFA states, so the attached modifies things to record only those\nstate pointers. I'm not done testing this by any means, but it\ndoes fix the two cases you showed, and I've been running that perl\nscript for some time with no further crashes.\n\nI suspect the assertion you hit with the REG_NOSUB patch was just\nfurther fallout from this same basic bug, but I've not yet rebased\nthat patch over this to check.\n\n\t\t\tregards, tom lane", "msg_date": "Sat, 07 Aug 2021 17:44:39 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" }, { "msg_contents": "I wrote:\n> ... What surprises me about this is not that\n> crash, but that we didn't see fundamental breakage of backref-using\n> patterns all over the place. It evidently breaks only in corner\n> cases, but I'm not quite sure why the effects are so limited.\n\nAh-hah, I've sussed it. I'd supposed that the issue was that parseqatom\ncould replace the subre atom's endpoints in the bit where it starts\nto \"prepare a general-purpose state skeleton\". However, it seems that\nthat's not what makes it go off the rails. Rather, in the specific\ncombination we've got in the test case, the next outer recursion level\nof parseqatom() decides that it can free the subre that was returned\nby the inner level, *which is the same subre that v->subs[n] is pointing\nto*. So this is really a use-after-free problem. freesrnode() won't\nactually free() the node, just stick it back onto the chain for possible\nrecycling --- and it doesn't clear the state pointer fields when it\ndoes that. So there's no use-after-free that ordinary tools could detect.\nWe only see a problem manifest if the subre node is reused later, which\nexplains why '(())(\\2){0}' fails while '(())\\2{0}' does not.\n\nSo the problem boils down to parseqatom deciding it can free child\nsubre nodes that it knows little about the provenance of. It would\nbe safer to make that optimization by instead freeing the \"top\"\nnode passed in from parsebranch, which we know has got no other\ninteresting linkages. That requires tweaking the API of parseqatom,\nwhich why I'd not done it like that to begin with --- but that's not\na hard or complicated change, just a mite tedious.\n\nHence, the attached patch.\n\nWhile this is sufficient to make the problem go away, I'm\ninclined to apply both changesets. Even if it accidentally\nworks right now to have later backrefs consult the outer s/s2\nstate pair rather than the original pair, that seems far too\nconvoluted and bug-prone. The outer states should be strictly\nthe concern of the iteration setup logic in the outer invocation\nof parseqatom.\n\n(I'm sort of wondering now whether the outer s/s2 states are\neven really necessary anymore ... maybe Spencer put those in\nas a way of preventing some prehistoric version of this bug.\nBut I'm not excited about messing with that right now.)\n\n\t\t\tregards, tom lane", "msg_date": "Sat, 07 Aug 2021 21:03:26 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" }, { "msg_contents": "I wrote:\n> While this is sufficient to make the problem go away, I'm\n> inclined to apply both changesets. Even if it accidentally\n> works right now to have later backrefs consult the outer s/s2\n> state pair rather than the original pair, that seems far too\n> convoluted and bug-prone. The outer states should be strictly\n> the concern of the iteration setup logic in the outer invocation\n> of parseqatom.\n\n> (I'm sort of wondering now whether the outer s/s2 states are\n> even really necessary anymore ... maybe Spencer put those in\n> as a way of preventing some prehistoric version of this bug.\n> But I'm not excited about messing with that right now.)\n\nI realized that the earlier patch is actually a bad idea, because\nit breaks the possibility of updating the subre to mark it as\nbeing referenced by a later backref, as the REG_NOSUB patch needs\nto do. However, on closer study, the outer s/s2 states being\nadded by the \"prepare a general-purpose state skeleton\" stanza\nreally are duplicative of the ones we already made for a\nparenthesized atom, so we can just get rid of them. Done that\nway.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 08 Aug 2021 12:31:53 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" }, { "msg_contents": "\n\n> On Aug 8, 2021, at 9:31 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> I realized that the earlier patch is actually a bad idea\n\nApplying only your <fix-backref-corner-case-1.patch> to master, the following which did not crash begins to crash:\n\n select regexp_split_to_array('rjgykkkk', '(?:(.))((\\1\\1.))');\n\nIt also changes the results for another one:\n\n select regexp_split_to_array('jdpveoarcnsarcnsarcnszieqbqbqbqbiufdlywphbnrxtdoboouuzcqiqmenj', '()((.)){1}?\\3?', 'itx');\n- regexp_split_to_array \n-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n- {\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"}\n+ regexp_split_to_array \n+------------------------------------------------------------------\n+ {jdpveoarcnsarcnsarcnszieqbqbqbqbiufdlywphbnrxtdoboouuzcqiqmenj}\n\nI'm not sure what *should* be returned here, only that it is a behavioral change.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Sun, 8 Aug 2021 10:00:10 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" }, { "msg_contents": "\n\n> On Aug 7, 2021, at 6:03 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> That requires tweaking the API of parseqatom,\n> which why I'd not done it like that to begin with --- but that's not\n> a hard or complicated change, just a mite tedious.\n> \n> Hence, the attached patch.\n\nApplying your <alternate-backref-corner-case-fix-1.patch> to master changes the outcome of some regular expression queries, but I *think* it changes them for the better.\n\nThese three look to me exactly correct after the patch, and wrong before:\n\n select regexp_matches('vnrungnajjjgkaaeaper', '((.))(((\\1)))((?:\\5..))', 'mx');\n- regexp_matches \n-----------------\n-(0 rows)\n+ regexp_matches \n+-----------------\n+ {j,j,j,j,j,jgk}\n+(1 row)\n\n select regexp_match('kgkgeganlifykxhfspjtgluwluwluwdfdfbbdjvrxjvrxedndrkaxxvbtqdj', '((.))\\2');\n regexp_match\n --------------\n- \n+ {b,b}\n (1 row)\n\n select regexp_split_to_array('uuuzkodphfbfbfb', '((.))(\\1\\2)', 'ntw');\n regexp_split_to_array\n -----------------------\n- {uuuzkodphfbfbfb}\n+ {\"\",zkodphfbfbfb}\n (1 row)\n\nBut these next two look to me correct before the patch and wrong after:\n\n select regexp_matches('ircecpbgyiggvtruqgxzigxzigxzisdbkuhbkuhrvl', '(((.)))(?:(\\3))[^\\f]');\n regexp_matches\n ----------------\n-(0 rows)\n+ {g,g,g,g}\n+(1 row)\n\n select regexp_matches('fhgxnvbvjaej', '(((.)).)((\\3)((.)))', 'csx');\n- regexp_matches \n-----------------\n-(0 rows)\n+ regexp_matches \n+-------------------\n+ {vb,v,v,vj,v,j,j}\n+(1 row)\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Sun, 8 Aug 2021 10:15:28 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" }, { "msg_contents": "\n\n> On Aug 8, 2021, at 10:15 AM, Mark Dilger <mark.dilger@enterprisedb.com> wrote:\n> \n> But these next two look to me correct before the patch and wrong after:\n> \n> select regexp_matches('ircecpbgyiggvtruqgxzigxzigxzisdbkuhbkuhrvl', '(((.)))(?:(\\3))[^\\f]');\n> regexp_matches\n> ----------------\n> -(0 rows)\n> + {g,g,g,g}\n> +(1 row)\n> \n> select regexp_matches('fhgxnvbvjaej', '(((.)).)((\\3)((.)))', 'csx');\n> - regexp_matches \n> -----------------\n> -(0 rows)\n> + regexp_matches \n> +-------------------\n> + {vb,v,v,vj,v,j,j}\n> +(1 row)\n\nScratch that. On further thought, these also look correct. I wasn't doing the capturing in my head correctly. So I think the patch is working! I'll test a bit longer.\n\nIs this patch (alternate-backref-corner-case-fix-1.patch) the current state of your patch set? I'd like to be sure I'm testing your latest work. Thanks.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Sun, 8 Aug 2021 10:28:55 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> Applying your <alternate-backref-corner-case-fix-1.patch> to master changes the outcome of some regular expression queries, but I *think* it changes them for the better.\n\n[ squint... ] You sure you applied the patch properly? All these examples\ngive me the same results in HEAD (with said patches as-committed) and v13.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 08 Aug 2021 13:29:36 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" }, { "msg_contents": "\n\n> On Aug 8, 2021, at 10:29 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Mark Dilger <mark.dilger@enterprisedb.com> writes:\n>> Applying your <alternate-backref-corner-case-fix-1.patch> to master changes the outcome of some regular expression queries, but I *think* it changes them for the better.\n> \n> [ squint... ] You sure you applied the patch properly? All these examples\n> give me the same results in HEAD (with said patches as-committed) and v13.\n> \n> \t\t\tregards, tom lane\n\nI'm not sure what you mean by \"as-committed\". Did you commit one of these recently?\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Sun, 8 Aug 2021 10:32:56 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" }, { "msg_contents": "\n\n> On Aug 8, 2021, at 10:32 AM, Mark Dilger <mark.dilger@enterprisedb.com> wrote:\n> \n> I'm not sure what you mean by \"as-committed\". Did you commit one of these recently?\n\nNevermind, I see the commit now.\n\nI'll rerun my tests with the new master. I was still using the code that I pulled yesterday.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Sun, 8 Aug 2021 10:34:16 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" }, { "msg_contents": "\n\n> On Aug 8, 2021, at 10:34 AM, Mark Dilger <mark.dilger@enterprisedb.com> wrote:\n> \n> I'll rerun my tests with the new master. I was still using the code that I pulled yesterday.\n\nI am now testing REL_13_STABLE (ba9f665a4413f855bbf4b544481db326f7b9bd73) vs master (c1132aae336c41cf9d316222e525d8d593c2b5d2). The regular expressions we discussed upthread show no differences.\n\nThere are a few changes which appear correct to me, but I don't know if you expected them:\n\n select regexp_match('hko', '((((?<!.))))(.(\\3)(\\1.))');\n- regexp_match \n---------------\n- \n+ regexp_match \n+--------------------\n+ {\"\",\"\",\"\",hk,\"\",k}\n (1 row)\n\n select 'nigqvigqvee' !~ '(())((\\2)\\2)(?:([^\\W]))';\n-ERROR: invalid regular expression: invalid escape \\ sequence\n+ ?column? \n+----------\n+ f\n+(1 row)\n+\n\n select regexp_replace('tl', '.{0}?(((?<![^][^]{1}?)))(.)\\2{6}?', 'jx', 'mt');\n regexp_replace\n ----------------\n- tl\n+ jxl\n (1 row)\n\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Sun, 8 Aug 2021 11:02:03 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> There are a few changes which appear correct to me, but I don't know if you expected them:\n\n> select regexp_match('hko', '((((?<!.))))(.(\\3)(\\1.))');\n> - regexp_match \n> ---------------\n> - \n> + regexp_match \n> +--------------------\n> + {\"\",\"\",\"\",hk,\"\",k}\n> (1 row)\n\nYes, this one is a consequence of 4aea704a5 (Fix semantics of regular\nexpression back-references). The lookbehind constraint should not be\napplied within the back-ref.\n\n> select 'nigqvigqvee' !~ '(())((\\2)\\2)(?:([^\\W]))';\n> -ERROR: invalid regular expression: invalid escape \\ sequence\n> + ?column? \n> +----------\n> + f\n> +(1 row)\n> +\n\nand this one of 2a0af7fe4 (Allow complemented character class escapes\nwithin regex brackets).\n\n> select regexp_replace('tl', '.{0}?(((?<![^][^]{1}?)))(.)\\2{6}?', 'jx', 'mt');\n> regexp_replace\n> ----------------\n> - tl\n> + jxl\n> (1 row)\n\nThis looks like also a consequence of 4aea704a5.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 08 Aug 2021 14:44:02 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Assert triggered during RE_compile_and_cache" } ]
[ { "msg_contents": "Hi,\n\nWhen testing EXEC_BACKEND on linux I see occasional test failures as long as I\ndon't disable ASLR. There's a code comment to that effect:\n\n\t * If testing EXEC_BACKEND on Linux, you should run this as root before\n\t * starting the postmaster:\n\t *\n\t * echo 0 >/proc/sys/kernel/randomize_va_space\n\nbut I don't like doing that on a system wide basis.\n\nLinux allows disabling ASLR on a per-process basis using\npersonality(ADDR_NO_RANDOMIZE). There's a wrapper binary to do that as well,\nsetarch --addr-no-randomize.\n\nI was wondering if we should have postmaster do personality(ADDR_NO_RANDOMIZE)\nfor EXEC_BACKEND builds? It seems nicer to make it automatically work than\nhave people remember that they need to call \"setarch --addr-no-randomize make check\".\n\nNot that it actually matters for EXEC_BACKEND, but theoretically doing\npersonality(ADDR_NO_RANDOMIZE) in postmaster is a tad more secure than doing\nit via setarch, as in the personality() case postmaster's layout itself is\nstill randomized...\n\n\nOr perhaps we should just add a comment mentioning setarch.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 5 Aug 2021 20:29:44 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on linux?" }, { "msg_contents": "\nOn 8/5/21 11:29 PM, Andres Freund wrote:\n> Hi,\n>\n> When testing EXEC_BACKEND on linux I see occasional test failures as long as I\n> don't disable ASLR. There's a code comment to that effect:\n>\n> \t * If testing EXEC_BACKEND on Linux, you should run this as root before\n> \t * starting the postmaster:\n> \t *\n> \t * echo 0 >/proc/sys/kernel/randomize_va_space\n>\n> but I don't like doing that on a system wide basis.\n>\n> Linux allows disabling ASLR on a per-process basis using\n> personality(ADDR_NO_RANDOMIZE). There's a wrapper binary to do that as well,\n> setarch --addr-no-randomize.\n>\n> I was wondering if we should have postmaster do personality(ADDR_NO_RANDOMIZE)\n> for EXEC_BACKEND builds? It seems nicer to make it automatically work than\n> have people remember that they need to call \"setarch --addr-no-randomize make check\".\n>\n> Not that it actually matters for EXEC_BACKEND, but theoretically doing\n> personality(ADDR_NO_RANDOMIZE) in postmaster is a tad more secure than doing\n> it via setarch, as in the personality() case postmaster's layout itself is\n> still randomized...\n>\n>\n> Or perhaps we should just add a comment mentioning setarch.\n>\n\nIf we can set it conveniently then that seems worth doing.\n\n\n(Thinks: do we have non-Windows buildfarm members doing EXEC_BACKEND?)\n\n\ncheers\n\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Fri, 6 Aug 2021 08:48:25 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On 2021-Aug-06, Andrew Dunstan wrote:\n\n> On 8/5/21 11:29 PM, Andres Freund wrote:\n\n> > I was wondering if we should have postmaster do personality(ADDR_NO_RANDOMIZE)\n> > for EXEC_BACKEND builds? It seems nicer to make it automatically work than\n> > have people remember that they need to call \"setarch --addr-no-randomize make check\".\n\nHow common is to get a failure? I know I've run tests under\nEXEC_BACKEND and not seen any failures. Not many runs though.\n\n> > Not that it actually matters for EXEC_BACKEND, but theoretically doing\n> > personality(ADDR_NO_RANDOMIZE) in postmaster is a tad more secure than doing\n> > it via setarch, as in the personality() case postmaster's layout itself is\n> > still randomized...\n\nTrue. I think the security aspect is not critically important, since\nhopefully nobody should be using such builds for production.\n\n\n> (Thinks: do we have non-Windows buildfarm members doing EXEC_BACKEND?)\n\nculicidae does that.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"Pido que me den el Nobel por razones humanitarias\" (Nicanor Parra)\n\n\n", "msg_date": "Mon, 9 Aug 2021 13:30:00 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Mon, Aug 9, 2021 at 1:30 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> How common is to get a failure? I know I've run tests under\n> EXEC_BACKEND and not seen any failures. Not many runs though.\n\nOn macOS, failures are extremely common. Sometimes I have to run\nsimple tests many times to get even one success. The proposal on the\ntable won't help with that problem since it's Linux-specific, but if\nthere's any way to do something similar on macOS it would be a _huge_\nhelp.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 9 Aug 2021 13:43:03 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "Hi,\n\nOn 2021-08-09 13:43:03 -0400, Robert Haas wrote:\n> On Mon, Aug 9, 2021 at 1:30 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> > How common is to get a failure? I know I've run tests under\n> > EXEC_BACKEND and not seen any failures. Not many runs though.\n\nI get check-world failures in about 1/2-1/3 of the runs, and a plain check\nfails in maybe 1/4 of the cases. It's pretty annoying because it often isn't\ntrivial to distinguish whether I've broken something or whether it's\nrandomization related...\n\nThe frequency of failures isn't stable over time, making it a bit harder to\nknow what's going on.\n\n\n> On macOS, failures are extremely common. Sometimes I have to run\n> simple tests many times to get even one success. The proposal on the\n> table won't help with that problem since it's Linux-specific, but if\n> there's any way to do something similar on macOS it would be a _huge_\n> help.\n\nThere does seem to be a way of doing so, because I found blog posts talking\nabout how to get e.g. lldb to *enable* ASLR, which it disables by default...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 9 Aug 2021 10:50:28 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2021-08-09 13:43:03 -0400, Robert Haas wrote:\n>> On Mon, Aug 9, 2021 at 1:30 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> How common is to get a failure? I know I've run tests under\n> EXEC_BACKEND and not seen any failures. Not many runs though.\n\n> I get check-world failures in about 1/2-1/3 of the runs, and a plain check\n> fails in maybe 1/4 of the cases. It's pretty annoying because it often isn't\n> trivial to distinguish whether I've broken something or whether it's\n> randomization related...\n\nI don't have numbers, but I do know that on Linux EXEC_BACKEND builds fail\noften enough to be annoying if you don't disable ASLR. If we can do\nsomething not-too-invasive about that, it'd be great.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 09 Aug 2021 13:54:25 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "Hi,\n\nOn 2021-08-09 13:54:25 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > On 2021-08-09 13:43:03 -0400, Robert Haas wrote:\n> >> On Mon, Aug 9, 2021 at 1:30 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> > How common is to get a failure? I know I've run tests under\n> > EXEC_BACKEND and not seen any failures. Not many runs though.\n> \n> > I get check-world failures in about 1/2-1/3 of the runs, and a plain check\n> > fails in maybe 1/4 of the cases. It's pretty annoying because it often isn't\n> > trivial to distinguish whether I've broken something or whether it's\n> > randomization related...\n> \n> I don't have numbers, but I do know that on Linux EXEC_BACKEND builds fail\n> often enough to be annoying if you don't disable ASLR. If we can do\n> something not-too-invasive about that, it'd be great.\n\nI now not sure if personality(NO_RANDOMIZE) in postmaster is actually\nsufficient. It does seem to drastically reduce the frequency of issues, but\nthere's still conceivable failures where postmaster's layout would class with\nthe non-randomized children - obviously personality(NO_RANDOMIZE) cannot\nretroactively change the layout of the already running binary.\n\nSo maybe we should put it into pg_ctl?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 9 Aug 2021 11:04:07 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Tue, Aug 10, 2021 at 5:43 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> On Mon, Aug 9, 2021 at 1:30 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> > How common is to get a failure? I know I've run tests under\n> > EXEC_BACKEND and not seen any failures. Not many runs though.\n>\n> On macOS, failures are extremely common. Sometimes I have to run\n> simple tests many times to get even one success. The proposal on the\n> table won't help with that problem since it's Linux-specific, but if\n> there's any way to do something similar on macOS it would be a _huge_\n> help.\n\nYeah, make check always fails for me on macOS 11. With the attached\nexperimental hack, it fails only occasionally (1 in 8 runs or so). I\ndon't know why.", "msg_date": "Wed, 11 Aug 2021 01:19:00 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "Hi,\n\nOn Tue, Aug 10, 2021, at 15:19, Thomas Munro wrote:\n> On Tue, Aug 10, 2021 at 5:43 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > On Mon, Aug 9, 2021 at 1:30 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> > > How common is to get a failure? I know I've run tests under\n> > > EXEC_BACKEND and not seen any failures. Not many runs though.\n> >\n> > On macOS, failures are extremely common. Sometimes I have to run\n> > simple tests many times to get even one success. The proposal on the\n> > table won't help with that problem since it's Linux-specific, but if\n> > there's any way to do something similar on macOS it would be a _huge_\n> > help.\n> \n> Yeah, make check always fails for me on macOS 11. With the attached\n> experimental hack, it fails only occasionally (1 in 8 runs or so). I\n> don't know why.\n\nI suspect you'd need to use the hack in pg_ctl to make it reliable. The layout of normally stayed position independent postmaster can be incompatible with the non ASLR spawned child.\n\nAndres\n\n\n\n", "msg_date": "Tue, 10 Aug 2021 16:11:59 +0200", "msg_from": "\"Andres Freund\" <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "\n =?UTF-8?Q?Re:_Worth_using_personality(ADDR=5FNO=5FRANDOMIZE)_for_EXEC=5F?=\n =?UTF-8?Q?BACKEND_on_linux=3F?=" }, { "msg_contents": "On Wed, Aug 11, 2021 at 2:12 AM Andres Freund <andres@anarazel.de> wrote:\n> On Tue, Aug 10, 2021, at 15:19, Thomas Munro wrote:\n> > Yeah, make check always fails for me on macOS 11. With the attached\n> > experimental hack, it fails only occasionally (1 in 8 runs or so). I\n> > don't know why.\n>\n> I suspect you'd need to use the hack in pg_ctl to make it reliable. The layout of normally stayed position independent postmaster can be incompatible with the non ASLR spawned child.\n\nYeah, but the patch already changes both pg_ctl.c and postmaster.c.\n\n\n", "msg_date": "Wed, 11 Aug 2021 07:07:49 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Wed, Aug 11, 2021 at 7:07 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> On Wed, Aug 11, 2021 at 2:12 AM Andres Freund <andres@anarazel.de> wrote:\n> > On Tue, Aug 10, 2021, at 15:19, Thomas Munro wrote:\n> > > Yeah, make check always fails for me on macOS 11. With the attached\n> > > experimental hack, it fails only occasionally (1 in 8 runs or so). I\n> > > don't know why.\n> >\n> > I suspect you'd need to use the hack in pg_ctl to make it reliable. The layout of normally stayed position independent postmaster can be incompatible with the non ASLR spawned child.\n>\n> Yeah, but the patch already changes both pg_ctl.c and postmaster.c.\n\n/me stares at vmmap output for a while\n\nOooh. It's working perfectly (for example if you export\nPATH=binarys:$PATH, pg_ctl -D pgdata start, make installcheck), but\npg_regress.c has its own separate fork/exec to launch the temporary\ncluster that needs to be similarly hacked. Unfortunately I have to\ngive this Macintosh back and go and do some real work on a different\ncomputer now. That does seem to be a working solution to the problem,\nthough, and could be polished into proposable form.\n\nI saw claims that you can also link with -Wl,-no_pie or toggle the PIE\nbit on your executable and libraries, but that didn't work for me on\n11, Intel (no effect) or ARM (linker option gone).\n\n\n", "msg_date": "Wed, 11 Aug 2021 11:59:02 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "\nOn 8/10/21 7:59 PM, Thomas Munro wrote:\n> On Wed, Aug 11, 2021 at 7:07 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n>> On Wed, Aug 11, 2021 at 2:12 AM Andres Freund <andres@anarazel.de> wrote:\n>>> On Tue, Aug 10, 2021, at 15:19, Thomas Munro wrote:\n>>>> Yeah, make check always fails for me on macOS 11. With the attached\n>>>> experimental hack, it fails only occasionally (1 in 8 runs or so). I\n>>>> don't know why.\n>>> I suspect you'd need to use the hack in pg_ctl to make it reliable. The layout of normally stayed position independent postmaster can be incompatible with the non ASLR spawned child.\n>> Yeah, but the patch already changes both pg_ctl.c and postmaster.c.\n> /me stares at vmmap output for a while\n>\n> Oooh. It's working perfectly (for example if you export\n> PATH=binarys:$PATH, pg_ctl -D pgdata start, make installcheck), but\n> pg_regress.c has its own separate fork/exec to launch the temporary\n> cluster that needs to be similarly hacked. \n\n\ninitdb also runs postgres a bunch of times via system(), similarly to\npg_regress but without the \"exec\". Does it also need adjusting?\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Wed, 11 Aug 2021 08:38:43 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Tue, Aug 10, 2021 at 7:59 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> I saw claims that you can also link with -Wl,-no_pie or toggle the PIE\n> bit on your executable and libraries, but that didn't work for me on\n> 11, Intel (no effect) or ARM (linker option gone).\n\nI think that worked for me on older macOS releases, and then it\nstopped working at some point after some update or reinstall or\nsomething. Unfortunately I don't know any more precisely than that,\nbut it does seem like we have to find some other approach to work on\nmodern systems.\n\nHopefully they don't keep whacking this around...\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 11 Aug 2021 09:45:45 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "Andrew Dunstan <andrew@dunslane.net> writes:\n> initdb also runs postgres a bunch of times via system(), similarly to\n> pg_regress but without the \"exec\". Does it also need adjusting?\n\nThat shouldn't be an issue, because we're only running the single\n\"standalone backend\" process, not a cluster.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 11 Aug 2021 09:55:49 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Thu, Aug 12, 2021 at 1:45 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> I think that worked for me on older macOS releases, and then it\n> stopped working at some point after some update or reinstall or\n> something. Unfortunately I don't know any more precisely than that,\n> but it does seem like we have to find some other approach to work on\n> modern systems.\n\nI gave up on trying to make that work once I realised that\n/usr/lib/dyld doesn't seem to obey the flag, so although other\nsegments become deterministic and the success rate is fairly high,\nthere's still a 600kb wrecking ball swinging around. I wondered what\nthe \"slide\" range could be... it appears to be fairly small\n(vm_map_get_max_aslr_slide_pages() seems to be the place that's\ndetermined and it's a 16MB or 256MB window, depending on architecture,\nif I read that right). Given that, the death of 32 bit processes\nsince Catalina, and the typical layout we see, I think just doing\nsomething like (/me rolls dice) export PG_SHMEM_ADDR=0x80000000000 is\na good candidate for something that works on both architectures, being\nmany TB away from everything else (above everything on ARM, between\nheap etc and libs on Intel but with 8TB of space below it and 120TB\nabove). That gets the tests passing consistently with unpatched\nmaster, -DEXEC_BACKEND, on both flavours of silicon.\n\n\n", "msg_date": "Thu, 12 Aug 2021 10:24:09 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Wed, Aug 11, 2021 at 6:24 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> On Thu, Aug 12, 2021 at 1:45 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > I think that worked for me on older macOS releases, and then it\n> > stopped working at some point after some update or reinstall or\n> > something. Unfortunately I don't know any more precisely than that,\n> > but it does seem like we have to find some other approach to work on\n> > modern systems.\n>\n> I gave up on trying to make that work once I realised that\n> /usr/lib/dyld doesn't seem to obey the flag, so although other\n> segments become deterministic and the success rate is fairly high,\n> there's still a 600kb wrecking ball swinging around. I wondered what\n> the \"slide\" range could be... it appears to be fairly small\n> (vm_map_get_max_aslr_slide_pages() seems to be the place that's\n> determined and it's a 16MB or 256MB window, depending on architecture,\n> if I read that right). Given that, the death of 32 bit processes\n> since Catalina, and the typical layout we see, I think just doing\n> something like (/me rolls dice) export PG_SHMEM_ADDR=0x80000000000 is\n> a good candidate for something that works on both architectures, being\n> many TB away from everything else (above everything on ARM, between\n> heap etc and libs on Intel but with 8TB of space below it and 120TB\n> above). That gets the tests passing consistently with unpatched\n> master, -DEXEC_BACKEND, on both flavours of silicon.\n\nUgh, OK. So, is there a way that we can get an \"easy button\" committed\nto the tree?\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 12 Aug 2021 10:58:02 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> On Wed, Aug 11, 2021 at 6:24 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n>> ... I think just doing\n>> something like (/me rolls dice) export PG_SHMEM_ADDR=0x80000000000 is\n>> a good candidate for something that works on both architectures, being\n>> many TB away from everything else (above everything on ARM, between\n>> heap etc and libs on Intel but with 8TB of space below it and 120TB\n>> above). That gets the tests passing consistently with unpatched\n>> master, -DEXEC_BACKEND, on both flavours of silicon.\n\n> Ugh, OK. So, is there a way that we can get an \"easy button\" committed\n> to the tree?\n\nI don't see why that approach couldn't be incorporated into pg_ctl,\nor the postmaster itself. Given Andres' point that Linux ASLR\ndisable probably has to happen in pg_ctl, it seems like doing it\nin pg_ctl in all cases is the way to move forward.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 12 Aug 2021 11:13:17 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Fri, Aug 13, 2021 at 3:13 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Robert Haas <robertmhaas@gmail.com> writes:\n> > Ugh, OK. So, is there a way that we can get an \"easy button\" committed\n> > to the tree?\n>\n> I don't see why that approach couldn't be incorporated into pg_ctl,\n> or the postmaster itself. Given Andres' point that Linux ASLR\n> disable probably has to happen in pg_ctl, it seems like doing it\n> in pg_ctl in all cases is the way to move forward.\n\nI think doing it in the postmaster is best, since otherwise you have\nto put code into pg_regress.c and pg_ctl.c. Here's a patch like that.", "msg_date": "Fri, 13 Aug 2021 09:39:36 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n> On Fri, Aug 13, 2021 at 3:13 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> I don't see why that approach couldn't be incorporated into pg_ctl,\n>> or the postmaster itself. Given Andres' point that Linux ASLR\n>> disable probably has to happen in pg_ctl, it seems like doing it\n>> in pg_ctl in all cases is the way to move forward.\n\n> I think doing it in the postmaster is best, since otherwise you have\n> to put code into pg_regress.c and pg_ctl.c. Here's a patch like that.\n\nHmm, ok. Small thought: it might be better to put the #if inside\nthe \"else { .... }\". That way it scales easily to allow other\nplatform-specific defaults if we find anything useful. As-is,\nthe obvious extension would end up with multiple else-blocks,\nwhich seems likely to confuse pgindent if nothing else.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 12 Aug 2021 17:59:38 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Fri, Aug 13, 2021 at 9:59 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Hmm, ok. Small thought: it might be better to put the #if inside\n> the \"else { .... }\". That way it scales easily to allow other\n> platform-specific defaults if we find anything useful. As-is,\n> the obvious extension would end up with multiple else-blocks,\n> which seems likely to confuse pgindent if nothing else.\n\nTrue. Thanks. Pushed to all live branches.\n\nObviously the address may have to be adjusted if Apple moves stuff\naround, or if the initial layout and ASLR slide range turn out to be\nless constrained than I inferred by nosing around the source code and\ntesting on a couple of systems.\n\n\n", "msg_date": "Fri, 13 Aug 2021 12:06:19 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n> Obviously the address may have to be adjusted if Apple moves stuff\n> around, or if the initial layout and ASLR slide range turn out to be\n> less constrained than I inferred by nosing around the source code and\n> testing on a couple of systems.\n\nSure. But we're no worse off than before; the workaround of \"set\nPG_SHMEM_ADDR by hand\" is just as applicable as ever.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 12 Aug 2021 20:29:09 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "Here's a patch for Linux and also FreeBSD. The latter OS decided to\nturn on ASLR by default recently, causing my workstation to fail like\nthis quite reliably, which reminded me to follow up with this. It\ndisables ASLR in pg_ctl and pg_regress, which is enough for check and\ncheck-world, but doesn't help you if you run the server directly\n(unlike the different hack done for macOS).\n\nFor whatever random reason the failures are rarer on Linux (could be\nmy imagination, but I think they might be clustered, I didn't look\ninto the recipe for the randomness), but even without reproducing a\nfailure it's clear to see using pmap that this has the right effect.\nI didn't bother with a check for the existence of ADDR_NO_RANDOMIZE\nbecause it's since 2.6.12 which is definitely ancient enough.", "msg_date": "Wed, 24 Nov 2021 08:27:43 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On 11/23/21, 11:29 AM, \"Thomas Munro\" <thomas.munro@gmail.com> wrote:\r\n> Here's a patch for Linux and also FreeBSD. The latter OS decided to\r\n> turn on ASLR by default recently, causing my workstation to fail like\r\n> this quite reliably, which reminded me to follow up with this. It\r\n> disables ASLR in pg_ctl and pg_regress, which is enough for check and\r\n> check-world, but doesn't help you if you run the server directly\r\n> (unlike the different hack done for macOS).\r\n>\r\n> For whatever random reason the failures are rarer on Linux (could be\r\n> my imagination, but I think they might be clustered, I didn't look\r\n> into the recipe for the randomness), but even without reproducing a\r\n> failure it's clear to see using pmap that this has the right effect.\r\n> I didn't bother with a check for the existence of ADDR_NO_RANDOMIZE\r\n> because it's since 2.6.12 which is definitely ancient enough.\r\n\r\nFWIW I just found this patch very useful for testing some EXEC_BACKEND\r\nstuff on Linux.\r\n\r\nNathan\r\n\r\n", "msg_date": "Fri, 7 Jan 2022 20:20:31 +0000", "msg_from": "\"Bossart, Nathan\" <bossartn@amazon.com>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Sat, Jan 8, 2022 at 9:20 AM Bossart, Nathan <bossartn@amazon.com> wrote:\n> FWIW I just found this patch very useful for testing some EXEC_BACKEND\n> stuff on Linux.\n\nThanks for testing. Tidied and pushed, to master only for now.\n\n\n", "msg_date": "Tue, 11 Jan 2022 00:29:44 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Tue, Jan 11, 2022 at 12:29:44AM +1300, Thomas Munro wrote:\n> Thanks for testing. Tidied and pushed, to master only for now.\n\nI have noticed the following failure for v11~14 on one of my hosts\nthat compiles with -DEXEC_BACKEND, and Nathan has redirected me here:\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=gokiburi&dt=2023-01-31%2012%3A07%3A32\nFATAL: could not reattach to shared memory (key=1050468, addr=0xffff97eb2000): Invalid argument\n\nCould it be worth back-patching f3e7806? I don't mind changing this\nanimal setup by switching the kernel configuration or reducing the\nbranch scope, but this solution is less invasive because it would not\ninfluence parallel runs.\n\nThoughts?\n--\nMichael", "msg_date": "Wed, 1 Feb 2023 10:32:40 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "Michael Paquier <michael@paquier.xyz> writes:\n> Could it be worth back-patching f3e7806?\n\nThat's aged long enough now that it seems like a pretty safe\nthing to do.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 31 Jan 2023 20:37:29 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Tue, Jan 31, 2023 at 08:37:29PM -0500, Tom Lane wrote:\n> That's aged long enough now that it seems like a pretty safe\n> thing to do.\n\nThanks. I'll wait for a few days before doing something for my\nbuildfarm stuff, in case somebody thinks this is a bad idea..\n--\nMichael", "msg_date": "Wed, 1 Feb 2023 10:58:46 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Wed, Feb 1, 2023 at 2:58 PM Michael Paquier <michael@paquier.xyz> wrote:\n> On Tue, Jan 31, 2023 at 08:37:29PM -0500, Tom Lane wrote:\n> > That's aged long enough now that it seems like a pretty safe\n> > thing to do.\n>\n> Thanks. I'll wait for a few days before doing something for my\n> buildfarm stuff, in case somebody thinks this is a bad idea..\n\n+1, go for it. It shouldn't affect Unix build releases, and on\nWindows the function does nothing.\n\n\n", "msg_date": "Wed, 1 Feb 2023 15:06:16 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Wed, Feb 01, 2023 at 03:06:16PM +1300, Thomas Munro wrote:\n> +1, go for it. It shouldn't affect Unix build releases, and on\n> Windows the function does nothing.\n\nThanks for confirming. I am wondering what these animals may complain\nabout next, but based on some tests on this buildfarm host with the\nsame configuration, things are looking OK once this stuff is applied\non 11~14.\n--\nMichael", "msg_date": "Thu, 2 Feb 2023 10:06:15 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Thu, Feb 02, 2023 at 10:06:15AM +0900, Michael Paquier wrote:\n> Thanks for confirming. I am wondering what these animals may complain\n> about next, but based on some tests on this buildfarm host with the\n> same configuration, things are looking OK once this stuff is applied\n> on 11~14.\n\nActually, I completely forgot to take into account that there is a\nminor release planned for next week:\nhttps://www.postgresql.org/developer/roadmap/\n\nSo I'll hold on a bit longer here, until the next versions get their\ntags.\n--\nMichael", "msg_date": "Thu, 2 Feb 2023 11:14:39 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Thu, Feb 02, 2023 at 11:14:39AM +0900, Michael Paquier wrote:\n> Actually, I completely forgot to take into account that there is a\n> minor release planned for next week:\n> https://www.postgresql.org/developer/roadmap/\n> \n> So I'll hold on a bit longer here, until the next versions get their\n> tags.\n\nSo, the backpatch down to 12 is straight-forward, with some conflicts\nin ./configure. ~12 handles also differently its CFLAGS with\npg_config.h.win32. 11 is more annoying because it lacks\nHAVE_SYS_PROCCTL_H and it would need a partial backport of f98b847. I\nam not completely sure if this could have more side effects, though,\neven if the part of pmsignal.c is left out. It should not..\n\nAt the end, I have just done this stuff down to ~12, 11 does not seem\nworth the trouble as the next stable version to go out of support.\nI'll reduce gokiburi's script a bit, as a result, until the oldest\nversion support is v12.\n--\nMichael", "msg_date": "Wed, 8 Feb 2023 13:12:15 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On 2023-02-08 13:12:15 +0900, Michael Paquier wrote:\n> On Thu, Feb 02, 2023 at 11:14:39AM +0900, Michael Paquier wrote:\n> > Actually, I completely forgot to take into account that there is a\n> > minor release planned for next week:\n> > https://www.postgresql.org/developer/roadmap/\n> > \n> > So I'll hold on a bit longer here, until the next versions get their\n> > tags.\n> \n> So, the backpatch down to 12 is straight-forward, with some conflicts\n> in ./configure. ~12 handles also differently its CFLAGS with\n> pg_config.h.win32. 11 is more annoying because it lacks\n> HAVE_SYS_PROCCTL_H and it would need a partial backport of f98b847. I\n> am not completely sure if this could have more side effects, though,\n> even if the part of pmsignal.c is left out. It should not..\n> \n> At the end, I have just done this stuff down to ~12, 11 does not seem\n> worth the trouble as the next stable version to go out of support.\n> I'll reduce gokiburi's script a bit, as a result, until the oldest\n> version support is v12.\n\nThat seems reasonable to me.\n\n\n", "msg_date": "Tue, 7 Feb 2023 21:44:47 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Wed, Feb 8, 2023 at 5:12 PM Michael Paquier <michael@paquier.xyz> wrote:\n> At the end, I have just done this stuff down to ~12, 11 does not seem\n> worth the trouble as the next stable version to go out of support.\n> I'll reduce gokiburi's script a bit, as a result, until the oldest\n> version support is v12.\n\nFor the record, according to [1] it's not necessary to use\n--reset-author when back-patching. (Maybe a little confusingly,\nbecause it's not quite clear whether our policies consider the author\nfield to be meaningful or not.)\n\n[1] https://www.postgresql.org/message-id/flat/1347459696.16215.11.camel%40vanquo.pezone.net\n\n\n", "msg_date": "Fri, 10 Feb 2023 08:15:21 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" }, { "msg_contents": "On Fri, Feb 10, 2023 at 08:15:21AM +1300, Thomas Munro wrote:\n> For the record, according to [1] it's not necessary to use\n> --reset-author when back-patching. (Maybe a little confusingly,\n> because it's not quite clear whether our policies consider the author\n> field to be meaningful or not.)\n> \n> [1] https://www.postgresql.org/message-id/flat/1347459696.16215.11.camel%40vanquo.pezone.net\n\nOops, sorry about that. Using --reset-author is a habit when it comes\nto backpatch. It looks like my mistake when back-patching something\nonly to stable branches.\n--\nMichael", "msg_date": "Fri, 10 Feb 2023 07:56:33 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Worth using personality(ADDR_NO_RANDOMIZE) for EXEC_BACKEND on\n linux?" } ]
[ { "msg_contents": "Hi,\n\nThe call to “pg_stat_reset“ does reset all the statistics data for\ntables belonging to the current database but does not take care of\nshared tables e.g pg_attribute. Similarly to reset the statistics at\ntable level, the call to “pg_stat_reset_single_table_counters“ does\nnot take care of shared tables.\n\nWhen we reset all the statistics using the call “pg_stat_reset”, the\npostgres process internally makes calls to “\npgstat_recv_resetcounter“, which resets the statistics of all the\ntables of the current database. But not resetting the statistics of\nshared objects using database ID as 'InvalidOid'.\n\nThe same fix is made in the internal function\n“pgstat_recv_resetsinglecounter“ to reset the statistics for the\nshared table for the call \"pg_stat_reset_single_table_counters\".\n\n--\nthank u\nSADHU PRASAD\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Fri, 6 Aug 2021 13:56:21 +0530", "msg_from": "Sadhuprasad Patro <b.sadhu@gmail.com>", "msg_from_op": true, "msg_subject": "Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Fri, 6 Aug 2021 at 13:56, Sadhuprasad Patro <b.sadhu@gmail.com> wrote:\n>\n> Hi,\n>\n> The call to “pg_stat_reset“ does reset all the statistics data for\n> tables belonging to the current database but does not take care of\n> shared tables e.g pg_attribute. Similarly to reset the statistics at\n> table level, the call to “pg_stat_reset_single_table_counters“ does\n> not take care of shared tables.\n>\n> When we reset all the statistics using the call “pg_stat_reset”, the\n> postgres process internally makes calls to “\n> pgstat_recv_resetcounter“, which resets the statistics of all the\n> tables of the current database. But not resetting the statistics of\n> shared objects using database ID as 'InvalidOid'.\n>\n> The same fix is made in the internal function\n> “pgstat_recv_resetsinglecounter“ to reset the statistics for the\n> shared table for the call \"pg_stat_reset_single_table_counters\".\n>\n\nHi Sadhu,\nI was looking into the patch. I will look more in the coming days. I\nhave below comments.\n\n1. Please can you share the test case to reproduce the issue and\nplease add the test case in patch.\n\n2. diff --git a/src/backend/postmaster/pgstat.c\nb/src/backend/postmaster/pgstat.c\nindex 56755cb92b..f272931276 100644\n--- a/src/backend/postmaster/pgstat.c\n+++ b/src/backend/postmaster/pgstat.c\n@@ -5092,7 +5092,6 @@ pgstat_recv_resetcounter(PgStat_MsgResetcounter\n*msg, int len)\n * Lookup the database in the hashtable. Nothing to do if not there.\n */\n dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n-\n if (!dbentry)\n return;\n\nI think, by mistake, you removed one line in the patch.\n\n-- \nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 6 Aug 2021 16:40:51 +0530", "msg_from": "Mahendra Singh Thalor <mahi6run@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "Hi Sadhu,\n\n\n> The call to “pg_stat_reset“ does reset all the statistics data for\n> tables belonging to the current database but does not take care of\n> shared tables e.g pg_attribute.\n\npg_attribute is not a shared catalog, is the mentioned scenario is also\napplicable for few others tables?\n\nI have just tried it with-out your patch:\n\npostgres=# SELECT * FROM pg_statio_all_tables where relid=1249;\n relid | schemaname | relname | heap_blks_read | heap_blks_hit |\nidx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\ntidx_blks_read | tidx_blks_hit\n-------+------------+--------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n 1249 | pg_catalog | pg_attribute | 29 | 522 |\n 8 | 673 | | |\n |\n(1 row)\n\npostgres=# select pg_stat_reset();\n pg_stat_reset\n---------------\n\n(1 row)\n\npostgres=# SELECT * FROM pg_statio_all_tables where relid=1249;\n relid | schemaname | relname | heap_blks_read | heap_blks_hit |\nidx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\ntidx_blks_read | tidx_blks_hit\n-------+------------+--------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n 1249 | pg_catalog | pg_attribute | 0 | 0 |\n 0 | 0 | | |\n |\n\n\nWe are able to reset the stats of pg_attibute without your patch.\n\nThanks,\nHimanshu\n\nOn Fri, Aug 6, 2021 at 1:56 PM Sadhuprasad Patro <b.sadhu@gmail.com> wrote:\n\n> Hi,\n>\n> The call to “pg_stat_reset“ does reset all the statistics data for\n> tables belonging to the current database but does not take care of\n> shared tables e.g pg_attribute. Similarly to reset the statistics at\n> table level, the call to “pg_stat_reset_single_table_counters“ does\n> not take care of shared tables.\n>\n> When we reset all the statistics using the call “pg_stat_reset”, the\n> postgres process internally makes calls to “\n> pgstat_recv_resetcounter“, which resets the statistics of all the\n> tables of the current database. But not resetting the statistics of\n> shared objects using database ID as 'InvalidOid'.\n>\n> The same fix is made in the internal function\n> “pgstat_recv_resetsinglecounter“ to reset the statistics for the\n> shared table for the call \"pg_stat_reset_single_table_counters\".\n>\n> --\n> thank u\n> SADHU PRASAD\n> EnterpriseDB: http://www.enterprisedb.com\n>\n\nHi Sadhu,> The call to “pg_stat_reset“ does reset all the statistics data for\n> tables belonging to the current database but does not take care of\n> shared tables e.g pg_attribute. pg_attribute is not a shared catalog, is the mentioned scenario is also applicable for few others tables?I have just tried it with-out your patch:postgres=# SELECT * FROM pg_statio_all_tables  where relid=1249; relid | schemaname |   relname    | heap_blks_read | heap_blks_hit | idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit | tidx_blks_read | tidx_blks_hit -------+------------+--------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------  1249 | pg_catalog | pg_attribute |             29 |           522 |             8 |          673 |                 |                |                |              (1 row)postgres=# select pg_stat_reset(); pg_stat_reset --------------- (1 row)postgres=# SELECT * FROM pg_statio_all_tables  where relid=1249; relid | schemaname |   relname    | heap_blks_read | heap_blks_hit | idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit | tidx_blks_read | tidx_blks_hit -------+------------+--------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------  1249 | pg_catalog | pg_attribute |              0 |             0 |             0 |            0 |                 |                |                |              We are able to reset the stats of pg_attibute without your patch. Thanks,HimanshuOn Fri, Aug 6, 2021 at 1:56 PM Sadhuprasad Patro <b.sadhu@gmail.com> wrote:Hi,\n\nThe call to “pg_stat_reset“ does reset all the statistics data for\ntables belonging to the current database but does not take care of\nshared tables e.g pg_attribute. Similarly to reset the statistics at\ntable level, the call to “pg_stat_reset_single_table_counters“ does\nnot take care of shared tables.\n\nWhen we reset all the statistics using the call “pg_stat_reset”, the\npostgres process internally makes calls to “\npgstat_recv_resetcounter“, which resets the statistics of all the\ntables of the current database. But not resetting the statistics of\nshared objects using database ID as 'InvalidOid'.\n\nThe same fix is made in the internal function\n“pgstat_recv_resetsinglecounter“ to reset the statistics for the\nshared table for the call \"pg_stat_reset_single_table_counters\".\n\n--\nthank u\nSADHU PRASAD\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Fri, 6 Aug 2021 17:40:24 +0530", "msg_from": "Himanshu Upadhyaya <upadhyaya.himanshu@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Fri, 6 Aug 2021 at 17:40, Himanshu Upadhyaya\n<upadhyaya.himanshu@gmail.com> wrote:\n>\n> Hi Sadhu,\n>\n>\n> > The call to “pg_stat_reset“ does reset all the statistics data for\n> > tables belonging to the current database but does not take care of\n> > shared tables e.g pg_attribute.\n>\n> pg_attribute is not a shared catalog, is the mentioned scenario is also applicable for few others tables?\n\nYes, I think, by mistake, Sadhu has mentioned pg_attribute.\n\nWith patch, I checked for pg_database and verified that we are resetting stats.\n\npsql (15devel)\nType \"help\" for help.\n\npostgres=# SELECT * FROM pg_statio_all_tables where relid=1262;\n relid | schemaname | relname | heap_blks_read | heap_blks_hit |\nidx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\ntidx_blks_read | tidx_blks_hit\n-------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n 1262 | pg_catalog | pg_database | 1 | 2 |\n 2 | 0 | 0 | 0 |\n 0 | 0\n(1 row)\n\npostgres=#\npostgres=# select pg_stat_reset();\n pg_stat_reset\n---------------\n\n(1 row)\n\npostgres=# SELECT * FROM pg_statio_all_tables where relid=1262;\n relid | schemaname | relname | heap_blks_read | heap_blks_hit |\nidx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\ntidx_blks_read | tidx_blks_hit\n-------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n 1262 | pg_catalog | pg_database | 0 | 0 |\n 0 | 0 | 0 | 0 |\n 0 | 0\n(1 row)\n\npostgres=#\n\n\nShared tables are:\n1. pg_database -- DatabaseRelationId 1262\n2. pg_tablespcae -- TableSpaceRelationId 1213\n3. pg_authid -- AuthIdRelationId 1260\n4. pg_auth_members -- AuthMemRelationId 1261\n5. pg_shdescription -- SharedDescriptionRelationId 2396\n6. pg_shdepend -- SharedDependRelationId 1214\n7. pg_shseclabel -- SharedSecLabelRelationId 3592\n8. pg_db_role_setting -- DbRoleSettingRelationId 2694\n9. pg_replication_origin -- ReplicationOriginRelationId 6000\n10. pg_subscription -- SubscriptionRelationId 6100\n\n--\nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n>\n> I have just tried it with-out your patch:\n>\n> postgres=# SELECT * FROM pg_statio_all_tables where relid=1249;\n> relid | schemaname | relname | heap_blks_read | heap_blks_hit | idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit | tidx_blks_read | tidx_blks_hit\n> -------+------------+--------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> 1249 | pg_catalog | pg_attribute | 29 | 522 | 8 | 673 | | | |\n> (1 row)\n>\n> postgres=# select pg_stat_reset();\n> pg_stat_reset\n> ---------------\n>\n> (1 row)\n>\n> postgres=# SELECT * FROM pg_statio_all_tables where relid=1249;\n> relid | schemaname | relname | heap_blks_read | heap_blks_hit | idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit | tidx_blks_read | tidx_blks_hit\n> -------+------------+--------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> 1249 | pg_catalog | pg_attribute | 0 | 0 | 0 | 0 | | | |\n>\n>\n> We are able to reset the stats of pg_attibute without your patch.\n>\n> Thanks,\n> Himanshu\n>\n> On Fri, Aug 6, 2021 at 1:56 PM Sadhuprasad Patro <b.sadhu@gmail.com> wrote:\n>>\n>> Hi,\n>>\n>> The call to “pg_stat_reset“ does reset all the statistics data for\n>> tables belonging to the current database but does not take care of\n>> shared tables e.g pg_attribute. Similarly to reset the statistics at\n>> table level, the call to “pg_stat_reset_single_table_counters“ does\n>> not take care of shared tables.\n>>\n>> When we reset all the statistics using the call “pg_stat_reset”, the\n>> postgres process internally makes calls to “\n>> pgstat_recv_resetcounter“, which resets the statistics of all the\n>> tables of the current database. But not resetting the statistics of\n>> shared objects using database ID as 'InvalidOid'.\n>>\n>> The same fix is made in the internal function\n>> “pgstat_recv_resetsinglecounter“ to reset the statistics for the\n>> shared table for the call \"pg_stat_reset_single_table_counters\".\n>>\n>> --\n>> thank u\n>> SADHU PRASAD\n>> EnterpriseDB: http://www.enterprisedb.com\n\n\n\n--\nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 6 Aug 2021 18:00:23 +0530", "msg_from": "Mahendra Singh Thalor <mahi6run@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "Hi Sadhu,\n\nPatch working as expected with shared tables, just one Minor comment on the\npatch.\n+ if (!dbentry)\n+ return;\n+\n+ /*\n+ * We simply throw away all the shared table entries by recreating\nnew\n+ * hash table for them.\n+ */\n+ if (dbentry->tables != NULL)\n+ hash_destroy(dbentry->tables);\n+ if (dbentry->functions != NULL)\n+ hash_destroy(dbentry->functions);\n+\n+ dbentry->tables = NULL;\n+ dbentry->functions = NULL;\n+\n+ /*\n+ * This creates empty hash tables for tables and functions.\n+ */\n+ reset_dbentry_counters(dbentry);\n\nWe already have the above code for non-shared tables, can we restrict\nduplicate code?\none solution I can think of, if we can have a list with two elements and\niterate each element with\nthese common steps?\n\nThanks,\nHimanshu\n\nOn Fri, Aug 6, 2021 at 5:40 PM Himanshu Upadhyaya <\nupadhyaya.himanshu@gmail.com> wrote:\n\n> Hi Sadhu,\n>\n>\n> > The call to “pg_stat_reset“ does reset all the statistics data for\n> > tables belonging to the current database but does not take care of\n> > shared tables e.g pg_attribute.\n>\n> pg_attribute is not a shared catalog, is the mentioned scenario is also\n> applicable for few others tables?\n>\n> I have just tried it with-out your patch:\n>\n> postgres=# SELECT * FROM pg_statio_all_tables where relid=1249;\n> relid | schemaname | relname | heap_blks_read | heap_blks_hit |\n> idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\n> tidx_blks_read | tidx_blks_hit\n>\n> -------+------------+--------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> 1249 | pg_catalog | pg_attribute | 29 | 522 |\n> 8 | 673 | | |\n> |\n> (1 row)\n>\n> postgres=# select pg_stat_reset();\n> pg_stat_reset\n> ---------------\n>\n> (1 row)\n>\n> postgres=# SELECT * FROM pg_statio_all_tables where relid=1249;\n> relid | schemaname | relname | heap_blks_read | heap_blks_hit |\n> idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\n> tidx_blks_read | tidx_blks_hit\n>\n> -------+------------+--------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> 1249 | pg_catalog | pg_attribute | 0 | 0 |\n> 0 | 0 | | |\n> |\n>\n>\n> We are able to reset the stats of pg_attibute without your patch.\n>\n> Thanks,\n> Himanshu\n>\n> On Fri, Aug 6, 2021 at 1:56 PM Sadhuprasad Patro <b.sadhu@gmail.com>\n> wrote:\n>\n>> Hi,\n>>\n>> The call to “pg_stat_reset“ does reset all the statistics data for\n>> tables belonging to the current database but does not take care of\n>> shared tables e.g pg_attribute. Similarly to reset the statistics at\n>> table level, the call to “pg_stat_reset_single_table_counters“ does\n>> not take care of shared tables.\n>>\n>> When we reset all the statistics using the call “pg_stat_reset”, the\n>> postgres process internally makes calls to “\n>> pgstat_recv_resetcounter“, which resets the statistics of all the\n>> tables of the current database. But not resetting the statistics of\n>> shared objects using database ID as 'InvalidOid'.\n>>\n>> The same fix is made in the internal function\n>> “pgstat_recv_resetsinglecounter“ to reset the statistics for the\n>> shared table for the call \"pg_stat_reset_single_table_counters\".\n>>\n>> --\n>> thank u\n>> SADHU PRASAD\n>> EnterpriseDB: http://www.enterprisedb.com\n>>\n>\n\nHi Sadhu,Patch working as expected with shared tables, just one Minor comment on the patch.+       if (!dbentry)+               return;++       /*+        * We simply throw away all the shared table entries by recreating new+        * hash table for them.+        */+       if (dbentry->tables != NULL)+               hash_destroy(dbentry->tables);+       if (dbentry->functions != NULL)+               hash_destroy(dbentry->functions);++       dbentry->tables = NULL;+       dbentry->functions = NULL;++       /*+        * This creates empty hash tables for tables and functions.+        */+       reset_dbentry_counters(dbentry);We already have the above code for non-shared tables, can we restrict duplicate code?one solution I can think of, if we can have a list with two elements and iterate each element with these common steps?Thanks,HimanshuOn Fri, Aug 6, 2021 at 5:40 PM Himanshu Upadhyaya <upadhyaya.himanshu@gmail.com> wrote:Hi Sadhu,> The call to “pg_stat_reset“ does reset all the statistics data for\n> tables belonging to the current database but does not take care of\n> shared tables e.g pg_attribute. pg_attribute is not a shared catalog, is the mentioned scenario is also applicable for few others tables?I have just tried it with-out your patch:postgres=# SELECT * FROM pg_statio_all_tables  where relid=1249; relid | schemaname |   relname    | heap_blks_read | heap_blks_hit | idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit | tidx_blks_read | tidx_blks_hit -------+------------+--------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------  1249 | pg_catalog | pg_attribute |             29 |           522 |             8 |          673 |                 |                |                |              (1 row)postgres=# select pg_stat_reset(); pg_stat_reset --------------- (1 row)postgres=# SELECT * FROM pg_statio_all_tables  where relid=1249; relid | schemaname |   relname    | heap_blks_read | heap_blks_hit | idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit | tidx_blks_read | tidx_blks_hit -------+------------+--------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------  1249 | pg_catalog | pg_attribute |              0 |             0 |             0 |            0 |                 |                |                |              We are able to reset the stats of pg_attibute without your patch. Thanks,HimanshuOn Fri, Aug 6, 2021 at 1:56 PM Sadhuprasad Patro <b.sadhu@gmail.com> wrote:Hi,\n\nThe call to “pg_stat_reset“ does reset all the statistics data for\ntables belonging to the current database but does not take care of\nshared tables e.g pg_attribute. Similarly to reset the statistics at\ntable level, the call to “pg_stat_reset_single_table_counters“ does\nnot take care of shared tables.\n\nWhen we reset all the statistics using the call “pg_stat_reset”, the\npostgres process internally makes calls to “\npgstat_recv_resetcounter“, which resets the statistics of all the\ntables of the current database. But not resetting the statistics of\nshared objects using database ID as 'InvalidOid'.\n\nThe same fix is made in the internal function\n“pgstat_recv_resetsinglecounter“ to reset the statistics for the\nshared table for the call \"pg_stat_reset_single_table_counters\".\n\n--\nthank u\nSADHU PRASAD\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Fri, 6 Aug 2021 20:53:17 +0530", "msg_from": "Himanshu Upadhyaya <upadhyaya.himanshu@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Fri, Aug 6, 2021 at 8:53 PM Himanshu Upadhyaya\n<upadhyaya.himanshu@gmail.com> wrote:\n>\n> Hi Sadhu,\n>\n> Patch working as expected with shared tables, just one Minor comment on the patch.\n> + if (!dbentry)\n> + return;\n> +\n> + /*\n> + * We simply throw away all the shared table entries by recreating new\n> + * hash table for them.\n> + */\n> + if (dbentry->tables != NULL)\n> + hash_destroy(dbentry->tables);\n> + if (dbentry->functions != NULL)\n> + hash_destroy(dbentry->functions);\n> +\n> + dbentry->tables = NULL;\n> + dbentry->functions = NULL;\n> +\n> + /*\n> + * This creates empty hash tables for tables and functions.\n> + */\n> + reset_dbentry_counters(dbentry);\n>\n> We already have the above code for non-shared tables, can we restrict duplicate code?\n> one solution I can think of, if we can have a list with two elements and iterate each element with\n> these common steps?\n\nAnother idea could be that instead of putting this logic in\npgstat_recv_resetcounter(), we can have this logic in pg_stat_reset()\nor maybe in pgstat_reset_counters(). So now\npgstat_recv_resetcounter() logic remain the same and I think that\nlogic is much cleaner i.e. whatever dobid it got in the message it\nwill reset stat for that dboid.\n\nSo now, if it depends upon the logic of the callers that what they\nwant to do so in this case pgstat_recv_resetcounter(), can send two\nmessages one for MyDatabaseOid which it is already doing, and another\nmessage for the InvalidOid.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 6 Aug 2021 21:16:43 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Fri, 6 Aug 2021 at 21:17, Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Fri, Aug 6, 2021 at 8:53 PM Himanshu Upadhyaya\n> <upadhyaya.himanshu@gmail.com> wrote:\n> >\n> > Hi Sadhu,\n> >\n> > Patch working as expected with shared tables, just one Minor comment on the patch.\n> > + if (!dbentry)\n> > + return;\n> > +\n> > + /*\n> > + * We simply throw away all the shared table entries by recreating new\n> > + * hash table for them.\n> > + */\n> > + if (dbentry->tables != NULL)\n> > + hash_destroy(dbentry->tables);\n> > + if (dbentry->functions != NULL)\n> > + hash_destroy(dbentry->functions);\n> > +\n> > + dbentry->tables = NULL;\n> > + dbentry->functions = NULL;\n> > +\n> > + /*\n> > + * This creates empty hash tables for tables and functions.\n> > + */\n> > + reset_dbentry_counters(dbentry);\n> >\n> > We already have the above code for non-shared tables, can we restrict duplicate code?\n> > one solution I can think of, if we can have a list with two elements and iterate each element with\n> > these common steps?\n>\n> Another idea could be that instead of putting this logic in\n> pgstat_recv_resetcounter(), we can have this logic in pg_stat_reset()\n> or maybe in pgstat_reset_counters(). So now\n> pgstat_recv_resetcounter() logic remain the same and I think that\n> logic is much cleaner i.e. whatever dobid it got in the message it\n> will reset stat for that dboid.\n>\n> So now, if it depends upon the logic of the callers that what they\n> want to do so in this case pgstat_recv_resetcounter(), can send two\n> messages one for MyDatabaseOid which it is already doing, and another\n> message for the InvalidOid.\n>\nHi,\nI reviewed patch and please find my review comments below:\n\n1)\nIn pgstat_recv_resetcounter, first we are checking for m_databaseid.\n\n+++ b/src/backend/postmaster/pgstat.c\n@@ -5092,7 +5092,6 @@ pgstat_recv_resetcounter(PgStat_MsgResetcounter\n*msg, int len)\n * Lookup the database in the hashtable. Nothing to do if not there.\n */\n dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n\n if (!dbentry)\n return;\n If we don't find any dbentry, then we are returning but I think we\nshould try to reset stats for shared tables. I may be wrong because I\nhaven't tested this.\n\n2)\n+\n+ /*\n+ * Lookup for the shared tables also to reset the stats\n+ */\n+ dbentry = pgstat_get_db_entry(InvalidOid, false);\n+ if (!dbentry)\n+ return;\n\nI think, always we should get dbentry for shared tables so we can add\nassert here.\n\n+ Assert (dbentry);\n\n3)\n pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len)\n {\n PgStat_StatDBEntry *dbentry;\n+ bool found;\n\n dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n\n@@ -5168,13 +5192,41 @@\npgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int\nlen)\n /* Set the reset timestamp for the whole database */\n dbentry->stat_reset_timestamp = GetCurrentTimestamp();\n\n- /* Remove object if it exists, ignore it if not */\n+ /* Remove object if it exists, if not then may be it's a shared table */\n if (msg->m_resettype == RESET_TABLE)\n+ {\n (void) hash_search(dbentry->tables, (void *) &(msg->m_objectid),\n- HASH_REMOVE, NULL);\n+ HASH_REMOVE, &found);\n+ if (!found)\n+ {\n+ /* If we didn't find it, maybe it's a shared table */\n+ dbentry = pgstat_get_db_entry(InvalidOid, false);\n+ if (dbentry)\n+ {\n+ /* Set the reset timestamp for the whole database */\n+ dbentry->stat_reset_timestamp = GetCurrentTimestamp();\n+ (void) hash_search(dbentry->tables, (void *)\n&(msg->m_objectid),\n+ HASH_REMOVE, NULL);\n+ }\n+ }\n+ }\n else if (msg->m_resettype == RESET_FUNCTION)\n+ {\n (void) hash_search(dbentry->functions, (void *) &(msg->m_objectid),\n- HASH_REMOVE, NULL);\n+ HASH_REMOVE, &found);\n+ if (!found)\n+ {\n+ /* If we didn't find it, maybe it's a shared table */\n+ dbentry = pgstat_get_db_entry(InvalidOid, false);\n+ if (dbentry)\n+ {\n+ /* Set the reset timestamp for the whole database */\n+ dbentry->stat_reset_timestamp = GetCurrentTimestamp();\n+ (void) hash_search(dbentry->functions, (void *)\n&(msg->m_objectid),\n+ HASH_REMOVE, NULL);\n+ }\n+ }\n+ }\n }\n\nAbove code can be replaced with:\n@@ -5160,7 +5162,10 @@\npgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int\nlen)\n {\n PgStat_StatDBEntry *dbentry;\n\n- dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n+ if (IsSharedRelation(msg->m_objectid))\n+ dbentry = pgstat_get_db_entry(InvalidOid, false);\n+ else\n+ dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n\n if (!dbentry)\n return;\n\n4) In the attached patch, I made one common function to reset dbentry\nand this common function fixes my 1st comment also.\n\n5) pg_stat_reset_single_table_counters is not resetting all the\ncolumns for pg_database.\nEx:\npostgres=# SELECT * FROM pg_statio_all_tables where relid =\n'pg_database'::regclass::oid;\n relid | schemaname | relname | heap_blks_read | heap_blks_hit |\nidx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\ntidx_blks_read | tidx_blks_hit\n-------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n 1262 | pg_catalog | pg_database | 1 | 2 |\n 2 | 0 | 0 | 0 |\n 0 | 0\n(1 row)\n\npostgres=# select\npg_stat_reset_single_table_counters('pg_database'::regclass::oid);\n pg_stat_reset_single_table_counters\n-------------------------------------\n\n(1 row)\n\npostgres=# SELECT * FROM pg_statio_all_tables where relid =\n'pg_database'::regclass::oid;\n relid | schemaname | relname | heap_blks_read | heap_blks_hit |\nidx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\ntidx_blks_read | tidx_blks_hit\n-------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n 1262 | pg_catalog | pg_database | 0 | 0 |\n 2 | 0 | 0 | 0 |\n 0 | 0\n(1 row)\n\npostgres=#\n\n\n-- \nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Sat, 7 Aug 2021 00:13:30 +0530", "msg_from": "Mahendra Singh Thalor <mahi6run@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Sat, 7 Aug 2021 at 00:13, Mahendra Singh Thalor <mahi6run@gmail.com>\nwrote:\n>\n> On Fri, 6 Aug 2021 at 21:17, Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n> > On Fri, Aug 6, 2021 at 8:53 PM Himanshu Upadhyaya\n> > <upadhyaya.himanshu@gmail.com> wrote:\n> > >\n> > > Hi Sadhu,\n> > >\n> > > Patch working as expected with shared tables, just one Minor comment\non the patch.\n> > > + if (!dbentry)\n> > > + return;\n> > > +\n> > > + /*\n> > > + * We simply throw away all the shared table entries by\nrecreating new\n> > > + * hash table for them.\n> > > + */\n> > > + if (dbentry->tables != NULL)\n> > > + hash_destroy(dbentry->tables);\n> > > + if (dbentry->functions != NULL)\n> > > + hash_destroy(dbentry->functions);\n> > > +\n> > > + dbentry->tables = NULL;\n> > > + dbentry->functions = NULL;\n> > > +\n> > > + /*\n> > > + * This creates empty hash tables for tables and functions.\n> > > + */\n> > > + reset_dbentry_counters(dbentry);\n> > >\n> > > We already have the above code for non-shared tables, can we restrict\nduplicate code?\n> > > one solution I can think of, if we can have a list with two elements\nand iterate each element with\n> > > these common steps?\n> >\n> > Another idea could be that instead of putting this logic in\n> > pgstat_recv_resetcounter(), we can have this logic in pg_stat_reset()\n> > or maybe in pgstat_reset_counters(). So now\n> > pgstat_recv_resetcounter() logic remain the same and I think that\n> > logic is much cleaner i.e. whatever dobid it got in the message it\n> > will reset stat for that dboid.\n> >\n> > So now, if it depends upon the logic of the callers that what they\n> > want to do so in this case pgstat_recv_resetcounter(), can send two\n> > messages one for MyDatabaseOid which it is already doing, and another\n> > message for the InvalidOid.\n> >\n> Hi,\n> I reviewed patch and please find my review comments below:\n>\n> 1)\n> In pgstat_recv_resetcounter, first we are checking for m_databaseid.\n>\n> +++ b/src/backend/postmaster/pgstat.c\n> @@ -5092,7 +5092,6 @@ pgstat_recv_resetcounter(PgStat_MsgResetcounter\n> *msg, int len)\n> * Lookup the database in the hashtable. Nothing to do if not there.\n> */\n> dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n>\n> if (!dbentry)\n> return;\n> If we don't find any dbentry, then we are returning but I think we\n> should try to reset stats for shared tables. I may be wrong because I\n> haven't tested this.\n>\n> 2)\n> +\n> + /*\n> + * Lookup for the shared tables also to reset the stats\n> + */\n> + dbentry = pgstat_get_db_entry(InvalidOid, false);\n> + if (!dbentry)\n> + return;\n>\n> I think, always we should get dbentry for shared tables so we can add\n> assert here.\n>\n> + Assert (dbentry);\n>\n> 3)\n> pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int\nlen)\n> {\n> PgStat_StatDBEntry *dbentry;\n> + bool found;\n>\n> dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n>\n> @@ -5168,13 +5192,41 @@\n> pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int\n> len)\n> /* Set the reset timestamp for the whole database */\n> dbentry->stat_reset_timestamp = GetCurrentTimestamp();\n>\n> - /* Remove object if it exists, ignore it if not */\n> + /* Remove object if it exists, if not then may be it's a shared\ntable */\n> if (msg->m_resettype == RESET_TABLE)\n> + {\n> (void) hash_search(dbentry->tables, (void *) &(msg->m_objectid),\n> - HASH_REMOVE, NULL);\n> + HASH_REMOVE, &found);\n> + if (!found)\n> + {\n> + /* If we didn't find it, maybe it's a shared table */\n> + dbentry = pgstat_get_db_entry(InvalidOid, false);\n> + if (dbentry)\n> + {\n> + /* Set the reset timestamp for the whole database */\n> + dbentry->stat_reset_timestamp = GetCurrentTimestamp();\n> + (void) hash_search(dbentry->tables, (void *)\n> &(msg->m_objectid),\n> + HASH_REMOVE, NULL);\n> + }\n> + }\n> + }\n> else if (msg->m_resettype == RESET_FUNCTION)\n> + {\n> (void) hash_search(dbentry->functions, (void *)\n&(msg->m_objectid),\n> - HASH_REMOVE, NULL);\n> + HASH_REMOVE, &found);\n> + if (!found)\n> + {\n> + /* If we didn't find it, maybe it's a shared table */\n> + dbentry = pgstat_get_db_entry(InvalidOid, false);\n> + if (dbentry)\n> + {\n> + /* Set the reset timestamp for the whole database */\n> + dbentry->stat_reset_timestamp = GetCurrentTimestamp();\n> + (void) hash_search(dbentry->functions, (void *)\n> &(msg->m_objectid),\n> + HASH_REMOVE, NULL);\n> + }\n> + }\n> + }\n> }\n>\n> Above code can be replaced with:\n> @@ -5160,7 +5162,10 @@\n> pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int\n> len)\n> {\n> PgStat_StatDBEntry *dbentry;\n>\n> - dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n> + if (IsSharedRelation(msg->m_objectid))\n> + dbentry = pgstat_get_db_entry(InvalidOid, false);\n> + else\n> + dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n>\n> if (!dbentry)\n> return;\n>\n> 4) In the attached patch, I made one common function to reset dbentry\n> and this common function fixes my 1st comment also.\n>\n> 5) pg_stat_reset_single_table_counters is not resetting all the\n> columns for pg_database.\n> Ex:\n> postgres=# SELECT * FROM pg_statio_all_tables where relid =\n> 'pg_database'::regclass::oid;\n> relid | schemaname | relname | heap_blks_read | heap_blks_hit |\n> idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\n> tidx_blks_read | tidx_blks_hit\n>\n-------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> 1262 | pg_catalog | pg_database | 1 | 2 |\n> 2 | 0 | 0 | 0 |\n> 0 | 0\n> (1 row)\n>\n> postgres=# select\n> pg_stat_reset_single_table_counters('pg_database'::regclass::oid);\n> pg_stat_reset_single_table_counters\n> -------------------------------------\n>\n> (1 row)\n>\n> postgres=# SELECT * FROM pg_statio_all_tables where relid =\n> 'pg_database'::regclass::oid;\n> relid | schemaname | relname | heap_blks_read | heap_blks_hit |\n> idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\n> tidx_blks_read | tidx_blks_hit\n>\n-------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> 1262 | pg_catalog | pg_database | 0 | 0 |\n> 2 | 0 | 0 | 0 |\n> 0 | 0\n> (1 row)\n>\n> postgres=#\n\nI have some more review comments.\n\n*1)* We should update the document for both the functions. May be, we can\nupdate like:\n\ndiff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml\nindex 74a58a916c..232764a5dd 100644\n--- a/doc/src/sgml/monitoring.sgml\n+++ b/doc/src/sgml/monitoring.sgml\n@@ -5056,7 +5056,8 @@ SELECT pid, wait_event_type, wait_event FROM\npg_stat_activity WHERE wait_event i\n <returnvalue>void</returnvalue>\n </para>\n <para>\n- Resets all statistics counters for the current database to zero.\n+ Resets all statistics counters for the current database to zero and\n+ reset for shared tables also.\n </para>\n <para>\n This function is restricted to superusers by default, but other\nusers\n@@ -5098,6 +5099,8 @@ SELECT pid, wait_event_type, wait_event FROM\npg_stat_activity WHERE wait_event i\n <para>\n Resets statistics for a single table or index in the current\ndatabase\n to zero.\n+ NOTE: if we pass shared table oid, then restes statistics for\nshared\n+ table also.\n </para>\n <para>\n This function is restricted to superusers by default, but other\nusers\n*2) *I think, pg_stat_reset_single_table_counters is not working properly\nfor shared tables so we should find out the reason for this.\n\n*Ex: (I tested for pg_database)*\npostgres=# SELECT * FROM pg_statio_all_tables where relid =\n'pg_database'::regclass::oid;\n relid | schemaname | relname | heap_blks_read | heap_blks_hit |\nidx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\ntidx_blks_read | tidx_blks_hit\n-------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n 1262 | pg_catalog | pg_database | 1 | 2 |\n 2 | 0 | 0 | 0 | 0\n| 0\n(1 row)\npostgres=#\npostgres=# select\npg_stat_reset_single_table_counters('pg_database'::regclass::oid);\n pg_stat_reset_single_table_counters\n-------------------------------------\n\n(1 row)\npostgres=# SELECT * FROM pg_statio_all_tables where relid =\n'pg_database'::regclass::oid;\n relid | schemaname | relname | heap_blks_read | heap_blks_hit |\nidx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\ntidx_blks_read | tidx_blks_hit\n-------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n 1262 | pg_catalog | pg_database | 0 | 0 |\n 2 | 0 | 0 | 0 | 0\n| 0\n(1 row)\n\n3) I am attaching a .sql file. We can add similar types of test cases for\nshared tables.\nEx: first reset stats for all shared tables using pg_stat_reset and then\ncheck stats for all shared tables(all should be zero)\n\n-- \nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Sat, 7 Aug 2021 11:49:24 +0530", "msg_from": "Mahendra Singh Thalor <mahi6run@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Sat, 7 Aug 2021 at 11:49, Mahendra Singh Thalor <mahi6run@gmail.com> wrote:\n>\n> On Sat, 7 Aug 2021 at 00:13, Mahendra Singh Thalor <mahi6run@gmail.com> wrote:\n> >\n> > On Fri, 6 Aug 2021 at 21:17, Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> > >\n> > > On Fri, Aug 6, 2021 at 8:53 PM Himanshu Upadhyaya\n> > > <upadhyaya.himanshu@gmail.com> wrote:\n> > > >\n> > > > Hi Sadhu,\n> > > >\n> > > > Patch working as expected with shared tables, just one Minor comment on the patch.\n> > > > + if (!dbentry)\n> > > > + return;\n> > > > +\n> > > > + /*\n> > > > + * We simply throw away all the shared table entries by recreating new\n> > > > + * hash table for them.\n> > > > + */\n> > > > + if (dbentry->tables != NULL)\n> > > > + hash_destroy(dbentry->tables);\n> > > > + if (dbentry->functions != NULL)\n> > > > + hash_destroy(dbentry->functions);\n> > > > +\n> > > > + dbentry->tables = NULL;\n> > > > + dbentry->functions = NULL;\n> > > > +\n> > > > + /*\n> > > > + * This creates empty hash tables for tables and functions.\n> > > > + */\n> > > > + reset_dbentry_counters(dbentry);\n> > > >\n> > > > We already have the above code for non-shared tables, can we restrict duplicate code?\n> > > > one solution I can think of, if we can have a list with two elements and iterate each element with\n> > > > these common steps?\n> > >\n> > > Another idea could be that instead of putting this logic in\n> > > pgstat_recv_resetcounter(), we can have this logic in pg_stat_reset()\n> > > or maybe in pgstat_reset_counters(). So now\n> > > pgstat_recv_resetcounter() logic remain the same and I think that\n> > > logic is much cleaner i.e. whatever dobid it got in the message it\n> > > will reset stat for that dboid.\n> > >\n> > > So now, if it depends upon the logic of the callers that what they\n> > > want to do so in this case pgstat_recv_resetcounter(), can send two\n> > > messages one for MyDatabaseOid which it is already doing, and another\n> > > message for the InvalidOid.\n> > >\n> > Hi,\n> > I reviewed patch and please find my review comments below:\n> >\n> > 1)\n> > In pgstat_recv_resetcounter, first we are checking for m_databaseid.\n> >\n> > +++ b/src/backend/postmaster/pgstat.c\n> > @@ -5092,7 +5092,6 @@ pgstat_recv_resetcounter(PgStat_MsgResetcounter\n> > *msg, int len)\n> > * Lookup the database in the hashtable. Nothing to do if not there.\n> > */\n> > dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n> >\n> > if (!dbentry)\n> > return;\n> > If we don't find any dbentry, then we are returning but I think we\n> > should try to reset stats for shared tables. I may be wrong because I\n> > haven't tested this.\n> >\n> > 2)\n> > +\n> > + /*\n> > + * Lookup for the shared tables also to reset the stats\n> > + */\n> > + dbentry = pgstat_get_db_entry(InvalidOid, false);\n> > + if (!dbentry)\n> > + return;\n> >\n> > I think, always we should get dbentry for shared tables so we can add\n> > assert here.\n> >\n> > + Assert (dbentry);\n> >\n> > 3)\n> > pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len)\n> > {\n> > PgStat_StatDBEntry *dbentry;\n> > + bool found;\n> >\n> > dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n> >\n> > @@ -5168,13 +5192,41 @@\n> > pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int\n> > len)\n> > /* Set the reset timestamp for the whole database */\n> > dbentry->stat_reset_timestamp = GetCurrentTimestamp();\n> >\n> > - /* Remove object if it exists, ignore it if not */\n> > + /* Remove object if it exists, if not then may be it's a shared table */\n> > if (msg->m_resettype == RESET_TABLE)\n> > + {\n> > (void) hash_search(dbentry->tables, (void *) &(msg->m_objectid),\n> > - HASH_REMOVE, NULL);\n> > + HASH_REMOVE, &found);\n> > + if (!found)\n> > + {\n> > + /* If we didn't find it, maybe it's a shared table */\n> > + dbentry = pgstat_get_db_entry(InvalidOid, false);\n> > + if (dbentry)\n> > + {\n> > + /* Set the reset timestamp for the whole database */\n> > + dbentry->stat_reset_timestamp = GetCurrentTimestamp();\n> > + (void) hash_search(dbentry->tables, (void *)\n> > &(msg->m_objectid),\n> > + HASH_REMOVE, NULL);\n> > + }\n> > + }\n> > + }\n> > else if (msg->m_resettype == RESET_FUNCTION)\n> > + {\n> > (void) hash_search(dbentry->functions, (void *) &(msg->m_objectid),\n> > - HASH_REMOVE, NULL);\n> > + HASH_REMOVE, &found);\n> > + if (!found)\n> > + {\n> > + /* If we didn't find it, maybe it's a shared table */\n> > + dbentry = pgstat_get_db_entry(InvalidOid, false);\n> > + if (dbentry)\n> > + {\n> > + /* Set the reset timestamp for the whole database */\n> > + dbentry->stat_reset_timestamp = GetCurrentTimestamp();\n> > + (void) hash_search(dbentry->functions, (void *)\n> > &(msg->m_objectid),\n> > + HASH_REMOVE, NULL);\n> > + }\n> > + }\n> > + }\n> > }\n> >\n> > Above code can be replaced with:\n> > @@ -5160,7 +5162,10 @@\n> > pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int\n> > len)\n> > {\n> > PgStat_StatDBEntry *dbentry;\n> >\n> > - dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n> > + if (IsSharedRelation(msg->m_objectid))\n> > + dbentry = pgstat_get_db_entry(InvalidOid, false);\n> > + else\n> > + dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n> >\n> > if (!dbentry)\n> > return;\n> >\n> > 4) In the attached patch, I made one common function to reset dbentry\n> > and this common function fixes my 1st comment also.\n> >\n> > 5) pg_stat_reset_single_table_counters is not resetting all the\n> > columns for pg_database.\n> > Ex:\n> > postgres=# SELECT * FROM pg_statio_all_tables where relid =\n> > 'pg_database'::regclass::oid;\n> > relid | schemaname | relname | heap_blks_read | heap_blks_hit |\n> > idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\n> > tidx_blks_read | tidx_blks_hit\n> > -------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> > 1262 | pg_catalog | pg_database | 1 | 2 |\n> > 2 | 0 | 0 | 0 |\n> > 0 | 0\n> > (1 row)\n> >\n> > postgres=# select\n> > pg_stat_reset_single_table_counters('pg_database'::regclass::oid);\n> > pg_stat_reset_single_table_counters\n> > -------------------------------------\n> >\n> > (1 row)\n> >\n> > postgres=# SELECT * FROM pg_statio_all_tables where relid =\n> > 'pg_database'::regclass::oid;\n> > relid | schemaname | relname | heap_blks_read | heap_blks_hit |\n> > idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\n> > tidx_blks_read | tidx_blks_hit\n> > -------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> > 1262 | pg_catalog | pg_database | 0 | 0 |\n> > 2 | 0 | 0 | 0 |\n> > 0 | 0\n> > (1 row)\n> >\n> > postgres=#\n>\n> I have some more review comments.\n>\n> 1) We should update the document for both the functions. May be, we can update like:\n>\n> diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml\n> index 74a58a916c..232764a5dd 100644\n> --- a/doc/src/sgml/monitoring.sgml\n> +++ b/doc/src/sgml/monitoring.sgml\n> @@ -5056,7 +5056,8 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i\n> <returnvalue>void</returnvalue>\n> </para>\n> <para>\n> - Resets all statistics counters for the current database to zero.\n> + Resets all statistics counters for the current database to zero and\n> + reset for shared tables also.\n> </para>\n> <para>\n> This function is restricted to superusers by default, but other users\n> @@ -5098,6 +5099,8 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i\n> <para>\n> Resets statistics for a single table or index in the current database\n> to zero.\n> + NOTE: if we pass shared table oid, then restes statistics for shared\n> + table also.\n> </para>\n> <para>\n> This function is restricted to superusers by default, but other users\n\nAs of now, we are adding handling inside pg_stat_reset for shared\ntables but I think we can add a new function with the name of\npg_stat_reset_shared_tables to reset stats for all the shared tables.\nNew function will give more clarity to the users also. We already have\na pg_stat_reset_shared(text) function for \"archiver\", \"bgwriter\", or\n\"wal\".\n\nThoughts?\n\nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n\n> 2) I think, pg_stat_reset_single_table_counters is not working properly for shared tables so we should find out the reason for this.\n>\n> Ex: (I tested for pg_database)\n> postgres=# SELECT * FROM pg_statio_all_tables where relid = 'pg_database'::regclass::oid;\n> relid | schemaname | relname | heap_blks_read | heap_blks_hit | idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit | tidx_blks_read | tidx_blks_hit\n> -------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> 1262 | pg_catalog | pg_database | 1 | 2 | 2 | 0 | 0 | 0 | 0 | 0\n> (1 row)\n> postgres=#\n> postgres=# select pg_stat_reset_single_table_counters('pg_database'::regclass::oid);\n> pg_stat_reset_single_table_counters\n> -------------------------------------\n>\n> (1 row)\n> postgres=# SELECT * FROM pg_statio_all_tables where relid = 'pg_database'::regclass::oid;\n> relid | schemaname | relname | heap_blks_read | heap_blks_hit | idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit | tidx_blks_read | tidx_blks_hit\n> -------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> 1262 | pg_catalog | pg_database | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0\n> (1 row)\n>\n> 3) I am attaching a .sql file. We can add similar types of test cases for shared tables.\n> Ex: first reset stats for all shared tables using pg_stat_reset and then check stats for all shared tables(all should be zero)\n>\n> --\n> Thanks and Regards\n> Mahendra Singh Thalor\n> EnterpriseDB: http://www.enterprisedb.com\n\n\n\n-- \nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Sat, 7 Aug 2021 12:13:38 +0530", "msg_from": "Mahendra Singh Thalor <mahi6run@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "Hi,\n\n> > 3)\n> > pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len)\n> > {\n> > PgStat_StatDBEntry *dbentry;\n> > + bool found;\n> >\n> > dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n> >\n> > @@ -5168,13 +5192,41 @@\n> > pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int\n> > len)\n> > /* Set the reset timestamp for the whole database */\n> > dbentry->stat_reset_timestamp = GetCurrentTimestamp();\n> >\n> > - /* Remove object if it exists, ignore it if not */\n> > + /* Remove object if it exists, if not then may be it's a shared table */\n> > if (msg->m_resettype == RESET_TABLE)\n> > + {\n> > (void) hash_search(dbentry->tables, (void *) &(msg->m_objectid),\n> > - HASH_REMOVE, NULL);\n> > + HASH_REMOVE, &found);\n> > + if (!found)\n> > + {\n> > + /* If we didn't find it, maybe it's a shared table */\n> > + dbentry = pgstat_get_db_entry(InvalidOid, false);\n> > + if (dbentry)\n> > + {\n> > + /* Set the reset timestamp for the whole database */\n> > + dbentry->stat_reset_timestamp = GetCurrentTimestamp();\n> > + (void) hash_search(dbentry->tables, (void *)\n> > &(msg->m_objectid),\n> > + HASH_REMOVE, NULL);\n> > + }\n> > + }\n> > + }\n> > else if (msg->m_resettype == RESET_FUNCTION)\n> > + {\n> > (void) hash_search(dbentry->functions, (void *) &(msg->m_objectid),\n> > - HASH_REMOVE, NULL);\n> > + HASH_REMOVE, &found);\n> > + if (!found)\n> > + {\n> > + /* If we didn't find it, maybe it's a shared table */\n> > + dbentry = pgstat_get_db_entry(InvalidOid, false);\n> > + if (dbentry)\n> > + {\n> > + /* Set the reset timestamp for the whole database */\n> > + dbentry->stat_reset_timestamp = GetCurrentTimestamp();\n> > + (void) hash_search(dbentry->functions, (void *)\n> > &(msg->m_objectid),\n> > + HASH_REMOVE, NULL);\n> > + }\n> > + }\n> > + }\n> > }\n> >\n> > Above code can be replaced with:\n> > @@ -5160,7 +5162,10 @@\n> > pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int\n> > len)\n> > {\n> > PgStat_StatDBEntry *dbentry;\n> >\n> > - dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n> > + if (IsSharedRelation(msg->m_objectid))\n> > + dbentry = pgstat_get_db_entry(InvalidOid, false);\n> > + else\n> > + dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n> >\n> > if (!dbentry)\n> > return;\n> >\n\nWill Check the function \"IsSharedRelation '' usage further and will\nuse it to fix the patch.\nBut I have not seen this function used every time as needed. No where\nin the stat collector code.\n\n\n> > 5) pg_stat_reset_single_table_counters is not resetting all the\n> > columns for pg_database.\n> > Ex:\n> > postgres=# SELECT * FROM pg_statio_all_tables where relid =\n> > 'pg_database'::regclass::oid;\n> > relid | schemaname | relname | heap_blks_read | heap_blks_hit |\n> > idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\n> > tidx_blks_read | tidx_blks_hit\n> > -------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> > 1262 | pg_catalog | pg_database | 1 | 2 |\n> > 2 | 0 | 0 | 0 |\n> > 0 | 0\n> > (1 row)\n> >\n> > postgres=# select\n> > pg_stat_reset_single_table_counters('pg_database'::regclass::oid);\n> > pg_stat_reset_single_table_counters\n> > -------------------------------------\n> >\n> > (1 row)\n> >\n> > postgres=# SELECT * FROM pg_statio_all_tables where relid =\n> > 'pg_database'::regclass::oid;\n> > relid | schemaname | relname | heap_blks_read | heap_blks_hit |\n> > idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\n> > tidx_blks_read | tidx_blks_hit\n> > -------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> > 1262 | pg_catalog | pg_database | 0 | 0 |\n> > 2 | 0 | 0 | 0 |\n> > 0 | 0\n> > (1 row)\n> >\n\nAs we have given input as ObjectID of pg_database, it resets only the\ncounters of heap_blk_read & heap_blk_hit.\nTo reset other counters like index & toast table related, we need to\nprovide respective objectIDs and call the function again. Then it\nresets everything.\nThis behavior is kept same as user tables local to the database.\n\n\n\n> 2) I think, pg_stat_reset_single_table_counters is not working properly for shared tables so we should find out the reason for this.\n>\n> Ex: (I tested for pg_database)\n> postgres=# SELECT * FROM pg_statio_all_tables where relid = 'pg_database'::regclass::oid;\n> relid | schemaname | relname | heap_blks_read | heap_blks_hit | idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit | tidx_blks_read | tidx_blks_hit\n> -------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> 1262 | pg_catalog | pg_database | 1 | 2 | 2 | 0 | 0 | 0 | 0 | 0\n> (1 row)\n> postgres=#\n> postgres=# select pg_stat_reset_single_table_counters('pg_database'::regclass::oid);\n> pg_stat_reset_single_table_counters\n> -------------------------------------\n>\n> (1 row)\n> postgres=# SELECT * FROM pg_statio_all_tables where relid = 'pg_database'::regclass::oid;\n> relid | schemaname | relname | heap_blks_read | heap_blks_hit | idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit | tidx_blks_read | tidx_blks_hit\n> -------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> 1262 | pg_catalog | pg_database | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0\n> (1 row)\n\nThis function \"pg_stat_reset_single_table_counters\" works as per the\ngiven table ID. To reset the index & toast table related counters, we\nneed to provide the respective ObjectIDs. (Refer example given for\npg_attribute).\nSo this works the same as a shared table and user tables local to the\ncurrent database.\n\n> 3) I am attaching a .sql file. We can add similar types of test cases for shared tables.\n> Ex: first reset stats for all shared tables using pg_stat_reset and then check stats for all shared tables(all should be zero)\n\nI did not find any existing test case for \"pg_stat_reset\", so I did\nnot add a new testcase for this issue..\nI can add if needed.\n\n-- \nThanks & Regards\nSadhuPrasad\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 9 Aug 2021 06:56:37 +0530", "msg_from": "Sadhuprasad Patro <b.sadhu@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Mon, 9 Aug 2021 at 06:56, Sadhuprasad Patro <b.sadhu@gmail.com> wrote:\n>\n> Hi,\n>\n> > > 3)\n> > > pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len)\n> > > {\n> > > PgStat_StatDBEntry *dbentry;\n> > > + bool found;\n> > >\n> > > dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n> > >\n> > > @@ -5168,13 +5192,41 @@\n> > > pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int\n> > > len)\n> > > /* Set the reset timestamp for the whole database */\n> > > dbentry->stat_reset_timestamp = GetCurrentTimestamp();\n> > >\n> > > - /* Remove object if it exists, ignore it if not */\n> > > + /* Remove object if it exists, if not then may be it's a shared table */\n> > > if (msg->m_resettype == RESET_TABLE)\n> > > + {\n> > > (void) hash_search(dbentry->tables, (void *) &(msg->m_objectid),\n> > > - HASH_REMOVE, NULL);\n> > > + HASH_REMOVE, &found);\n> > > + if (!found)\n> > > + {\n> > > + /* If we didn't find it, maybe it's a shared table */\n> > > + dbentry = pgstat_get_db_entry(InvalidOid, false);\n> > > + if (dbentry)\n> > > + {\n> > > + /* Set the reset timestamp for the whole database */\n> > > + dbentry->stat_reset_timestamp = GetCurrentTimestamp();\n> > > + (void) hash_search(dbentry->tables, (void *)\n> > > &(msg->m_objectid),\n> > > + HASH_REMOVE, NULL);\n> > > + }\n> > > + }\n> > > + }\n> > > else if (msg->m_resettype == RESET_FUNCTION)\n> > > + {\n> > > (void) hash_search(dbentry->functions, (void *) &(msg->m_objectid),\n> > > - HASH_REMOVE, NULL);\n> > > + HASH_REMOVE, &found);\n> > > + if (!found)\n> > > + {\n> > > + /* If we didn't find it, maybe it's a shared table */\n> > > + dbentry = pgstat_get_db_entry(InvalidOid, false);\n> > > + if (dbentry)\n> > > + {\n> > > + /* Set the reset timestamp for the whole database */\n> > > + dbentry->stat_reset_timestamp = GetCurrentTimestamp();\n> > > + (void) hash_search(dbentry->functions, (void *)\n> > > &(msg->m_objectid),\n> > > + HASH_REMOVE, NULL);\n> > > + }\n> > > + }\n> > > + }\n> > > }\n> > >\n> > > Above code can be replaced with:\n> > > @@ -5160,7 +5162,10 @@\n> > > pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int\n> > > len)\n> > > {\n> > > PgStat_StatDBEntry *dbentry;\n> > >\n> > > - dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n> > > + if (IsSharedRelation(msg->m_objectid))\n> > > + dbentry = pgstat_get_db_entry(InvalidOid, false);\n> > > + else\n> > > + dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n> > >\n> > > if (!dbentry)\n> > > return;\n> > >\n>\n> Will Check the function \"IsSharedRelation '' usage further and will\n> use it to fix the patch.\n> But I have not seen this function used every time as needed. No where\n> in the stat collector code.\n>\n>\n> > > 5) pg_stat_reset_single_table_counters is not resetting all the\n> > > columns for pg_database.\n> > > Ex:\n> > > postgres=# SELECT * FROM pg_statio_all_tables where relid =\n> > > 'pg_database'::regclass::oid;\n> > > relid | schemaname | relname | heap_blks_read | heap_blks_hit |\n> > > idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\n> > > tidx_blks_read | tidx_blks_hit\n> > > -------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> > > 1262 | pg_catalog | pg_database | 1 | 2 |\n> > > 2 | 0 | 0 | 0 |\n> > > 0 | 0\n> > > (1 row)\n> > >\n> > > postgres=# select\n> > > pg_stat_reset_single_table_counters('pg_database'::regclass::oid);\n> > > pg_stat_reset_single_table_counters\n> > > -------------------------------------\n> > >\n> > > (1 row)\n> > >\n> > > postgres=# SELECT * FROM pg_statio_all_tables where relid =\n> > > 'pg_database'::regclass::oid;\n> > > relid | schemaname | relname | heap_blks_read | heap_blks_hit |\n> > > idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit |\n> > > tidx_blks_read | tidx_blks_hit\n> > > -------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> > > 1262 | pg_catalog | pg_database | 0 | 0 |\n> > > 2 | 0 | 0 | 0 |\n> > > 0 | 0\n> > > (1 row)\n> > >\n>\n> As we have given input as ObjectID of pg_database, it resets only the\n> counters of heap_blk_read & heap_blk_hit.\n> To reset other counters like index & toast table related, we need to\n> provide respective objectIDs and call the function again. Then it\n> resets everything.\n> This behavior is kept same as user tables local to the database.\n\nThanks Sadhu for your explanation.\n\nI also debugged this and understood the design.\n\n-- \nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n\n>\n>\n>\n> > 2) I think, pg_stat_reset_single_table_counters is not working properly for shared tables so we should find out the reason for this.\n> >\n> > Ex: (I tested for pg_database)\n> > postgres=# SELECT * FROM pg_statio_all_tables where relid = 'pg_database'::regclass::oid;\n> > relid | schemaname | relname | heap_blks_read | heap_blks_hit | idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit | tidx_blks_read | tidx_blks_hit\n> > -------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> > 1262 | pg_catalog | pg_database | 1 | 2 | 2 | 0 | 0 | 0 | 0 | 0\n> > (1 row)\n> > postgres=#\n> > postgres=# select pg_stat_reset_single_table_counters('pg_database'::regclass::oid);\n> > pg_stat_reset_single_table_counters\n> > -------------------------------------\n> >\n> > (1 row)\n> > postgres=# SELECT * FROM pg_statio_all_tables where relid = 'pg_database'::regclass::oid;\n> > relid | schemaname | relname | heap_blks_read | heap_blks_hit | idx_blks_read | idx_blks_hit | toast_blks_read | toast_blks_hit | tidx_blks_read | tidx_blks_hit\n> > -------+------------+-------------+----------------+---------------+---------------+--------------+-----------------+----------------+----------------+---------------\n> > 1262 | pg_catalog | pg_database | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0\n> > (1 row)\n>\n> This function \"pg_stat_reset_single_table_counters\" works as per the\n> given table ID. To reset the index & toast table related counters, we\n> need to provide the respective ObjectIDs. (Refer example given for\n> pg_attribute).\n> So this works the same as a shared table and user tables local to the\n> current database.\n>\n> > 3) I am attaching a .sql file. We can add similar types of test cases for shared tables.\n> > Ex: first reset stats for all shared tables using pg_stat_reset and then check stats for all shared tables(all should be zero)\n>\n> I did not find any existing test case for \"pg_stat_reset\", so I did\n> not add a new testcase for this issue..\n> I can add if needed.\n>\n> --\n> Thanks & Regards\n> SadhuPrasad\n> EnterpriseDB: http://www.enterprisedb.com\n\n\n\n-- \nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 9 Aug 2021 07:42:31 +0530", "msg_from": "Mahendra Singh Thalor <mahi6run@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "> 3) I am attaching a .sql file. We can add similar types of test cases for shared tables.\n> Ex: first reset stats for all shared tables using pg_stat_reset and then check stats for all shared tables(all should be zero)\n\nAdding a new test case for this looks difficult as results are not\nconsistent when the testcase added to automation. There may be some\npossible delay as collector process has to reset the statistics in\nbackground...\nSo Not adding any testcase and I think for the same reason there are\nno existing test case for this stat reset.\n\nThanks & Regards\nSadhuPrasad\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 10 Aug 2021 21:33:33 +0530", "msg_from": "Sadhuprasad Patro <b.sadhu@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "> As of now, we are adding handling inside pg_stat_reset for shared\n> tables but I think we can add a new function with the name of\n> pg_stat_reset_shared_tables to reset stats for all the shared tables.\n> New function will give more clarity to the users also. We already have\n> a pg_stat_reset_shared(text) function for \"archiver\", \"bgwriter\", or\n> \"wal\".\n>\n> Thoughts?\n\nIn my opinion, it is better to extend the functionality of\n\"pg_stat_reset\" call because a new function just to reset shared table\ndata may not be needed. Where we already have a reset shared function\n\"pg_stat_reset_shared\" in place.\n\nAll of applicable comments are implemented in the patch below:\n\n\nThanks & Regards\nSadhuPrasad\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Tue, 10 Aug 2021 21:53:22 +0530", "msg_from": "Sadhuprasad Patro <b.sadhu@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Tue, 10 Aug 2021 at 21:53, Sadhuprasad Patro <b.sadhu@gmail.com> wrote:\n>\n> > As of now, we are adding handling inside pg_stat_reset for shared\n> > tables but I think we can add a new function with the name of\n> > pg_stat_reset_shared_tables to reset stats for all the shared tables.\n> > New function will give more clarity to the users also. We already have\n> > a pg_stat_reset_shared(text) function for \"archiver\", \"bgwriter\", or\n> > \"wal\".\n> >\n> > Thoughts?\n>\n> In my opinion, it is better to extend the functionality of\n> \"pg_stat_reset\" call because a new function just to reset shared table\n> data may not be needed. Where we already have a reset shared function\n> \"pg_stat_reset_shared\" in place.\n>\n> All of applicable comments are implemented in the patch below:\n>\n\nHi Sadhu,\nI can see that you forgot to include \"catalog.h\" so I am getting below\nwarning:\n\n> pgstat.c: In function ‘pgstat_recv_resetsinglecounter’:\n> pgstat.c:5216:7: warning: implicit declaration of function\n> ‘IsSharedRelation’; did you mean ‘InvalidRelation’?\n> [-Wimplicit-function-declaration]\n> if (!IsSharedRelation(msg->m_objectid))\n> ^~~~~~~~~~~~~~~~\n> InvalidRelation\n>\n\n1) Please add the .h file.\n--- a/src/backend/postmaster/pgstat.c\n+++ b/src/backend/postmaster/pgstat.c\n@@ -38,6 +38,7 @@\n #include \"access/transam.h\"\n #include \"access/twophase_rmgr.h\"\n #include \"access/xact.h\"\n+#include \"catalog/catalog.h\"\n #include \"catalog/partition.h\"\n\n2)\n@@ -1442,6 +1443,10 @@ pgstat_reset_counters(void)\n pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);\n msg.m_databaseid = MyDatabaseId;\n pgstat_send(&msg, sizeof(msg));\n+\n+ /* Reset the stat counters for Shared tables also. */\n+ msg.m_databaseid = InvalidOid;\n+ pgstat_send(&msg, sizeof(msg));\n\nI will look into this part again. If pgstat_send forks a new process, then\nI think, it will be better if we can reset stats in\npgstat_recv_resetcounter for shared tables also because shared tables are\nnot much in counting so it will be good if we reset in one function only. I\nwill debug this part more and will see.\n\n-- \nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Tue, 10 Aug 2021 at 21:53, Sadhuprasad Patro <b.sadhu@gmail.com> wrote:>> > As of now, we are adding handling inside pg_stat_reset for shared> > tables but I think we can add a new function with the name of> > pg_stat_reset_shared_tables to reset stats for all the shared tables.> > New function will give more clarity to the users also. We already have> > a pg_stat_reset_shared(text) function for \"archiver\", \"bgwriter\", or> > \"wal\".> >> > Thoughts?>> In my opinion, it is better to extend the functionality of> \"pg_stat_reset\" call because a new function just to reset shared table> data may not be needed. Where we already have a reset shared function> \"pg_stat_reset_shared\" in place.>> All of applicable comments are implemented in the patch below:>Hi Sadhu,I can see that you forgot to include \"catalog.h\" so I am getting below warning:pgstat.c: In function ‘pgstat_recv_resetsinglecounter’:pgstat.c:5216:7: warning: implicit declaration of function ‘IsSharedRelation’; did you mean ‘InvalidRelation’? [-Wimplicit-function-declaration]  if (!IsSharedRelation(msg->m_objectid))       ^~~~~~~~~~~~~~~~       InvalidRelation1) Please add the .h file.--- a/src/backend/postmaster/pgstat.c+++ b/src/backend/postmaster/pgstat.c@@ -38,6 +38,7 @@ #include \"access/transam.h\" #include \"access/twophase_rmgr.h\" #include \"access/xact.h\"+#include \"catalog/catalog.h\" #include \"catalog/partition.h\"2)@@ -1442,6 +1443,10 @@ pgstat_reset_counters(void)        pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);        msg.m_databaseid = MyDatabaseId;        pgstat_send(&msg, sizeof(msg));++       /* Reset the stat counters for Shared tables also. */+       msg.m_databaseid = InvalidOid;+       pgstat_send(&msg, sizeof(msg));I will look into this part again. If pgstat_send forks a new process, then I think, it will be better if we can reset stats in pgstat_recv_resetcounter for shared tables also because shared tables are not much in counting so it will be good if we reset in one function only. I will debug this part more and will see.-- Thanks and RegardsMahendra Singh ThalorEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Tue, 10 Aug 2021 22:32:14 +0530", "msg_from": "Mahendra Singh Thalor <mahi6run@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Tue, 10 Aug 2021 at 22:32, Mahendra Singh Thalor <mahi6run@gmail.com> wrote:\n>\n> On Tue, 10 Aug 2021 at 21:53, Sadhuprasad Patro <b.sadhu@gmail.com> wrote:\n> >\n> > > As of now, we are adding handling inside pg_stat_reset for shared\n> > > tables but I think we can add a new function with the name of\n> > > pg_stat_reset_shared_tables to reset stats for all the shared tables.\n> > > New function will give more clarity to the users also. We already have\n> > > a pg_stat_reset_shared(text) function for \"archiver\", \"bgwriter\", or\n> > > \"wal\".\n> > >\n> > > Thoughts?\n> >\n> > In my opinion, it is better to extend the functionality of\n> > \"pg_stat_reset\" call because a new function just to reset shared table\n> > data may not be needed. Where we already have a reset shared function\n> > \"pg_stat_reset_shared\" in place.\n> >\n> > All of applicable comments are implemented in the patch below:\n> >\n>\n> Hi Sadhu,\n> I can see that you forgot to include \"catalog.h\" so I am getting below warning:\n>>\n>> pgstat.c: In function ‘pgstat_recv_resetsinglecounter’:\n>> pgstat.c:5216:7: warning: implicit declaration of function ‘IsSharedRelation’; did you mean ‘InvalidRelation’? [-Wimplicit-function-declaration]\n>> if (!IsSharedRelation(msg->m_objectid))\n>> ^~~~~~~~~~~~~~~~\n>> InvalidRelation\n>\n>\n> 1) Please add the .h file.\n> --- a/src/backend/postmaster/pgstat.c\n> +++ b/src/backend/postmaster/pgstat.c\n> @@ -38,6 +38,7 @@\n> #include \"access/transam.h\"\n> #include \"access/twophase_rmgr.h\"\n> #include \"access/xact.h\"\n> +#include \"catalog/catalog.h\"\n> #include \"catalog/partition.h\"\n>\n> 2)\n> @@ -1442,6 +1443,10 @@ pgstat_reset_counters(void)\n> pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);\n> msg.m_databaseid = MyDatabaseId;\n> pgstat_send(&msg, sizeof(msg));\n> +\n> + /* Reset the stat counters for Shared tables also. */\n> + msg.m_databaseid = InvalidOid;\n> + pgstat_send(&msg, sizeof(msg));\n>\n> I will look into this part again. If pgstat_send forks a new process, then I think, it will be better if we can reset stats in pgstat_recv_resetcounter for shared tables also because shared tables are not much in counting so it will be good if we reset in one function only. I will debug this part more and will see.\n>\n\nI checked this and found that we already have one process \"stats\ncollector\" and in v02 patch, we are sending requests to collect stats\ntwo times. I don't know how costly one call is but I feel that we can\navoid the 2nd call by keeping handling of the shared tables into\npgstat_recv_resetcounter.\n\nThoughts?\n\n-- \nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 10 Aug 2021 22:49:27 +0530", "msg_from": "Mahendra Singh Thalor <mahi6run@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Tue, Aug 10, 2021 at 10:49 PM Mahendra Singh Thalor\n<mahi6run@gmail.com> wrote:\n\n> I checked this and found that we already have one process \"stats\n> collector\" and in v02 patch, we are sending requests to collect stats\n> two times. I don't know how costly one call is but I feel that we can\n> avoid the 2nd call by keeping handling of the shared tables into\n> pgstat_recv_resetcounter.\n>\n\nI think let's not make the stat collector aware of what we want to\nachieve, so the stat collector will only reset for what we have asked\nfor and let the caller or the signal sender decide what they want to\ndo.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 11 Aug 2021 09:17:16 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Wed, 11 Aug 2021 at 09:17, Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Tue, Aug 10, 2021 at 10:49 PM Mahendra Singh Thalor\n> <mahi6run@gmail.com> wrote:\n>\n> > I checked this and found that we already have one process \"stats\n> > collector\" and in v02 patch, we are sending requests to collect stats\n> > two times. I don't know how costly one call is but I feel that we can\n> > avoid the 2nd call by keeping handling of the shared tables into\n> > pgstat_recv_resetcounter.\n> >\n>\n> I think let's not make the stat collector aware of what we want to\n> achieve, so the stat collector will only reset for what we have asked\n> for and let the caller or the signal sender decide what they want to\n> do.\n>\nThanks Dilip for your opinion.\n\nIf we want to use pgstat_recv_resetcounter with invalid database oid,\nthen we should update all the comments of pgstat_recv_resetcounter\nfunction because we are calling this function with both valid and\ninvalid database oid.\nIf we are passing invalid database oid, it means we want to reset\nstats for shared tables.\n\n1)\n /*\n * Lookup the database in the hashtable. Nothing to do if not\nthere.\n */\n dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\nWe should update the above comment and if m_databaseid is invalid,\nthen we should always get dbentry.\n\nAssert (msg->m_databaseid == 0 && dbentry ) and some more sanity checks.\n\n2)\n /*\n * We simply throw away all the database's table entries by recreating a\n * new hash table for them.\n */\nI think we should update this also.\n\n3)\n* Reset the statistics for the specified database.\nThis should be updated.\n\n-- \nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 11 Aug 2021 10:30:25 +0530", "msg_from": "Mahendra Singh Thalor <mahi6run@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Wed, Aug 11, 2021 at 10:30 AM Mahendra Singh Thalor\n<mahi6run@gmail.com> wrote:\n>\n> On Wed, 11 Aug 2021 at 09:17, Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n> > On Tue, Aug 10, 2021 at 10:49 PM Mahendra Singh Thalor\n> > <mahi6run@gmail.com> wrote:\n> >\n> > > I checked this and found that we already have one process \"stats\n> > > collector\" and in v02 patch, we are sending requests to collect stats\n> > > two times. I don't know how costly one call is but I feel that we can\n> > > avoid the 2nd call by keeping handling of the shared tables into\n> > > pgstat_recv_resetcounter.\n> > >\n> >\n> > I think let's not make the stat collector aware of what we want to\n> > achieve, so the stat collector will only reset for what we have asked\n> > for and let the caller or the signal sender decide what they want to\n> > do.\n\nIf we do support resetting the stats for shared tables in\n'pg_stat_reset', which is for DB level,\nthen the stats of shared tables will be reseted in other instances as\nwell, which seems to be not correct.\nSo we need to provide some way to reset the stats for shared tables to\ncustomers.\n\nIn the latest patch, we have supported only through the\npgstat_recv_resetsinglecounter function to reset stats for shared\ntables.\n\nThanks & Regards\nSadhuPrasad\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Thu, 19 Aug 2021 22:24:06 +0530", "msg_from": "Sadhuprasad Patro <b.sadhu@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "> If we do support resetting the stats for shared tables in\n> 'pg_stat_reset', which is for DB level,\n> then the stats of shared tables will be reseted in other instances as\n> well, which seems to be not correct.\n> So we need to provide some way to reset the stats for shared tables to\n> customers.\n>\n> In the latest patch, we have supported only through the\n> pgstat_recv_resetsinglecounter function to reset stats for shared\n> tables.\n\nFinal patch attached after some corrections..\n\nThanks & Regards\nSadhuPrasad\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Fri, 20 Aug 2021 06:32:14 +0530", "msg_from": "Sadhuprasad Patro <b.sadhu@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Fri, 20 Aug 2021 at 06:32, Sadhuprasad Patro <b.sadhu@gmail.com> wrote:\n>\n> > If we do support resetting the stats for shared tables in\n> > 'pg_stat_reset', which is for DB level,\n> > then the stats of shared tables will be reseted in other instances as\n> > well, which seems to be not correct.\n> > So we need to provide some way to reset the stats for shared tables to\n> > customers.\n\nJFI, I am briefly explaining here.\n\nIn an offline discussion with Robert Haas, we discussed all the review\ncomments with him and then he suggested that we can consider this as a\nsmall bug in pgstat_recv_resetsinglecounter because when we are giving\nshared table oid to pgstat_recv_resetsinglecounter, then it is not doing\nanything so we can add handling for this so that users can reset stats for\nshared table also and there is no need to reset stats from pg_reset_stats\nfor all the shard tables.\nSo based on that, we decided that we should add handling only in\npgstat_recv_resetsinglecounter\nThanks Robert Hass for your opinion.\n\n> >\n> > In the latest patch, we have supported only through the\n> > pgstat_recv_resetsinglecounter function to reset stats for shared\n> > tables.\n>\n> Final patch attached after some corrections..\n\nThanks Sadhu for the updated patch.\n\nI reviewed v4* patch. Below are some of my some review comments.\n\n1)\n Resets statistics for a single table or index in the current\ndatabase\n- to zero.\n+ to zero. The input can be a shared table also\n\nI think, above comment should be modified. Maybe, we can modify it as \"If\ninput is a shared oid(table or index or toast), then resets statistics for\na single shared entry to zero.\n\n2)\n #include \"catalog/pg_proc.h\"\n+#include \"catalog/catalog.h\"\n #include \"common/ip.h\"\nHeader file should be in alphabetical order.\n\n3)\n- dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n+ if (!IsSharedRelation(msg->m_objectid))\n+ dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n+ else\n+ dbentry = pgstat_get_db_entry(InvalidOid, false);\n\nWe should add some comments before this change.\n\n4)\n /* ----------\n * pgstat_recv_resetsinglecounter() -\n *\n- * Reset a statistics for a single object\n+ * Reset a statistics for a single object, which may also be a shared\n*+ * table.*\n\ntable should be replaced with 'object' as we have table, index, toast for\nshared tables and if we can modify the above comment with some additional\ninfo, then it will be good.\n\n-- \nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Fri, 20 Aug 2021 at 06:32, Sadhuprasad Patro <b.sadhu@gmail.com> wrote:>> > If we do support resetting the stats for shared tables in> > 'pg_stat_reset', which is for DB level,> > then the stats of shared tables will be reseted in other instances as> > well, which seems to be not correct.> > So we need to provide some way to reset the stats for shared tables to> > customers.JFI, I am briefly explaining here.In an offline discussion with Robert Haas, we discussed all the review comments with him and then he suggested that we can consider this as a small bug in pgstat_recv_resetsinglecounter because when we are giving shared table oid to pgstat_recv_resetsinglecounter, then it is not doing anything so we can add handling for this so that users can reset stats for shared table also and there is no need to reset stats from pg_reset_stats for all the shard tables.So based on that, we decided that we should add handling only in pgstat_recv_resetsinglecounterThanks Robert Hass for your opinion.> >> > In the latest patch, we have supported only through the> > pgstat_recv_resetsinglecounter function to reset stats for shared> > tables.>> Final patch attached after some corrections..Thanks Sadhu for the updated patch.I reviewed v4* patch. Below are some of my some review comments.1)         Resets statistics for a single table or index in the current database-        to zero.+        to zero. The input can be a shared table alsoI think, above comment should be modified. Maybe, we can modify it as \"If input is a shared oid(table or index or toast), then resets statistics for a single shared entry to zero.2) #include \"catalog/pg_proc.h\"+#include \"catalog/catalog.h\" #include \"common/ip.h\"Header file should be in alphabetical order.3)-       dbentry = pgstat_get_db_entry(msg->m_databaseid, false);+       if (!IsSharedRelation(msg->m_objectid))+               dbentry = pgstat_get_db_entry(msg->m_databaseid, false);+       else+               dbentry = pgstat_get_db_entry(InvalidOid, false); We should add some comments before this change.4) /* ----------  * pgstat_recv_resetsinglecounter() -  *- *     Reset a statistics for a single object+ *     Reset a statistics for a single object, which may also be a shared+ *     table.table should be replaced with 'object' as we have table, index, toast for shared tables and if we can modify the above comment with some additional info, then it will be good.-- Thanks and RegardsMahendra Singh ThalorEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Fri, 20 Aug 2021 07:37:52 +0530", "msg_from": "Mahendra Singh Thalor <mahi6run@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Fri, 20 Aug 2021 at 07:37, Mahendra Singh Thalor <mahi6run@gmail.com> wrote:\n>\n> On Fri, 20 Aug 2021 at 06:32, Sadhuprasad Patro <b.sadhu@gmail.com> wrote:\n> >\n> > > If we do support resetting the stats for shared tables in\n> > > 'pg_stat_reset', which is for DB level,\n> > > then the stats of shared tables will be reseted in other instances as\n> > > well, which seems to be not correct.\n> > > So we need to provide some way to reset the stats for shared tables to\n> > > customers.\n>\n> JFI, I am briefly explaining here.\n>\n> In an offline discussion with Robert Haas, we discussed all the review comments with him and then he suggested that we can consider this as a small bug in pgstat_recv_resetsinglecounter because when we are giving shared table oid to pgstat_recv_resetsinglecounter, then it is not doing anything so we can add handling for this so that users can reset stats for shared table also and there is no need to reset stats from pg_reset_stats for all the shard tables.\n> So based on that, we decided that we should add handling only in pgstat_recv_resetsinglecounter\n> Thanks Robert Hass for your opinion.\n>\n> > >\n> > > In the latest patch, we have supported only through the\n> > > pgstat_recv_resetsinglecounter function to reset stats for shared\n> > > tables.\n> >\n> > Final patch attached after some corrections..\n>\n> Thanks Sadhu for the updated patch.\n>\n> I reviewed v4* patch. Below are some of my some review comments.\n>\n> 1)\n> Resets statistics for a single table or index in the current database\n> - to zero.\n> + to zero. The input can be a shared table also\n>\n> I think, above comment should be modified. Maybe, we can modify it as \"If input is a shared oid(table or index or toast), then resets statistics for a single shared entry to zero.\n>\n> 2)\n> #include \"catalog/pg_proc.h\"\n> +#include \"catalog/catalog.h\"\n> #include \"common/ip.h\"\n> Header file should be in alphabetical order.\n>\n> 3)\n> - dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n> + if (!IsSharedRelation(msg->m_objectid))\n> + dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n> + else\n> + dbentry = pgstat_get_db_entry(InvalidOid, false);\n>\n> We should add some comments before this change.\n\nAbove changes can be replaced with below code(Either 1 or 2):\n\n1)\n@@ -5143,6 +5143,13 @@\npgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int\nlen)\n {\n PgStat_StatDBEntry *dbentry;\n\n+ /*\n+ * If oid refers to shared object, then set m_databaseid as invalid so\n+ * that we can reset stats for shared object also.\n+ */\n+ if (IsSharedRelation(msg->m_objectid))\n+ msg->m_databaseid = InvalidOid;\n+\n dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n\n2)\n@@ -5143,7 +5143,11 @@\npgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int\nlen)\n {\n PgStat_StatDBEntry *dbentry;\n\n- dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n+ /* some comment */\n+ if (IsSharedRelation(msg->m_objectid))\n+ dbentry = pgstat_get_db_entry(InvalidOid, false);\n+ else\n+ dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n\nIn 'if' condition, we can check shared and then if object is shared,\nthen pass 'invalidOid' in 'if' case only so that it will give more\nreadability and code will be cleaner.\n\nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n>\n> 4)\n> /* ----------\n> * pgstat_recv_resetsinglecounter() -\n> *\n> - * Reset a statistics for a single object\n> + * Reset a statistics for a single object, which may also be a shared\n> + * table.\n>\n> table should be replaced with 'object' as we have table, index, toast for shared tables and if we can modify the above comment with some additional info, then it will be good.\n>\n> --\n> Thanks and Regards\n> Mahendra Singh Thalor\n> EnterpriseDB: http://www.enterprisedb.com\n\n\n\n-- \nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 20 Aug 2021 07:58:22 +0530", "msg_from": "Mahendra Singh Thalor <mahi6run@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "\n\nOn 2021/08/20 11:07, Mahendra Singh Thalor wrote:\n> 1)\n>          Resets statistics for a single table or index in the current database\n> -        to zero.\n> +        to zero. The input can be a shared table also\n> \n> I think, above comment should be modified. Maybe, we can modify it as \"If input is a shared oid(table or index or toast), then resets statistics for a single shared entry to zero.\n\nI'm not sure if ordinary users can understand what \"shared oid\" means. Instead,\nwhat about \"Resets statistics for a single relation in the current database or\nshared across all databases in the cluster to zero.\"?\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Fri, 20 Aug 2021 11:42:30 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "> 3)\n> - dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n> + if (!IsSharedRelation(msg->m_objectid))\n> + dbentry = pgstat_get_db_entry(msg->m_databaseid, false);\n> + else\n> + dbentry = pgstat_get_db_entry(InvalidOid, false);\n>\n> We should add some comments before this change.\n\nIn my opinion, the comments added above the function\n\"pgstat_recv_resetsinglecounter\" and the function call\n\"IsSharedRelation\" added are self explanatory. If we add anything\nmore, it will be a duplication.\nSo No need to add any more comments here.\n\n\nThanks & Regards\nSadhuPrasad\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Sun, 22 Aug 2021 22:51:48 +0530", "msg_from": "Sadhuprasad Patro <b.sadhu@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "> On 2021/08/20 11:07, Mahendra Singh Thalor wrote:\n> > 1)\n> > Resets statistics for a single table or index in the current database\n> > - to zero.\n> > + to zero. The input can be a shared table also\n> >\n> > I think, above comment should be modified. Maybe, we can modify it as \"If input is a shared oid(table or index or toast), then resets statistics for a single shared entry to zero.\n>\n> I'm not sure if ordinary users can understand what \"shared oid\" means. Instead,\n> what about \"Resets statistics for a single relation in the current database or\n> shared across all databases in the cluster to zero.\"?\n>\n\nThank you for the review here. As per the comments, attached the\nlatest patch here...\n\n\nThanks & Regards\nSadhuPrasad\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Sun, 22 Aug 2021 22:53:47 +0530", "msg_from": "Sadhuprasad Patro <b.sadhu@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Sun, 22 Aug 2021 at 22:53, Sadhuprasad Patro <b.sadhu@gmail.com> wrote:\n>\n> > On 2021/08/20 11:07, Mahendra Singh Thalor wrote:\n> > > 1)\n> > > Resets statistics for a single table or index in the\ncurrent database\n> > > - to zero.\n> > > + to zero. The input can be a shared table also\n> > >\n> > > I think, above comment should be modified. Maybe, we can modify it as\n\"If input is a shared oid(table or index or toast), then resets statistics\nfor a single shared entry to zero.\n> >\n> > I'm not sure if ordinary users can understand what \"shared oid\" means.\nInstead,\n> > what about \"Resets statistics for a single relation in the current\ndatabase or\n> > shared across all databases in the cluster to zero.\"?\n> >\n>\n> Thank you for the review here. As per the comments, attached the\n> latest patch here...\n>\n\nThanks Sadhu for the updated patch.\n\nPatch looks good to me and I don't have any more comments.\n\nI marked this patch as 'ready for committer'.\nhttps://commitfest.postgresql.org/34/3282/\n\n-- \nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Sun, 22 Aug 2021 at 22:53, Sadhuprasad Patro <b.sadhu@gmail.com> wrote:>> > On 2021/08/20 11:07, Mahendra Singh Thalor wrote:> > > 1)> > >           Resets statistics for a single table or index in the current database> > > -        to zero.> > > +        to zero. The input can be a shared table also> > >> > > I think, above comment should be modified. Maybe, we can modify it as \"If input is a shared oid(table or index or toast), then resets statistics for a single shared entry to zero.> >> > I'm not sure if ordinary users can understand what \"shared oid\" means. Instead,> > what about \"Resets statistics for a single relation in the current database or> > shared across all databases in the cluster to zero.\"?> >>> Thank you for the review here. As per the comments, attached the> latest patch here...>Thanks Sadhu for the updated patch.Patch looks good to me and I don't have any more comments.I marked this patch as 'ready for committer'.https://commitfest.postgresql.org/34/3282/-- Thanks and RegardsMahendra Singh ThalorEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Tue, 24 Aug 2021 09:37:40 +0530", "msg_from": "Mahendra Singh Thalor <mahi6run@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On 2021/08/24 13:07, Mahendra Singh Thalor wrote:\n> Thanks Sadhu for the updated patch.\n> \n> Patch looks good to me and I don't have any more comments.\n> \n> I marked this patch as 'ready for committer'.\n> https://commitfest.postgresql.org/34/3282/ <https://commitfest.postgresql.org/34/3282/>\n\nAttached is the updated version of the patch. In this patch, I updated\nthe description for pg_stat_reset_single_table_counters() in pg_proc.dat.\nBarring any objection, I will commit this patch.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION", "msg_date": "Wed, 1 Sep 2021 21:01:15 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "On Wed, Sep 1, 2021 at 5:31 PM Fujii Masao <masao.fujii@oss.nttdata.com> wrote:\n>\n>\n>\n> On 2021/08/24 13:07, Mahendra Singh Thalor wrote:\n> > Thanks Sadhu for the updated patch.\n> >\n> > Patch looks good to me and I don't have any more comments.\n> >\n> > I marked this patch as 'ready for committer'.\n> > https://commitfest.postgresql.org/34/3282/ <https://commitfest.postgresql.org/34/3282/>\n>\n> Attached is the updated version of the patch. In this patch, I updated\n> the description for pg_stat_reset_single_table_counters() in pg_proc.dat.\n> Barring any objection, I will commit this patch.\n\nHi Fujii,\n\nYes this update is fine.. Please commit this patch...\n\nThanks & Regards\nSadhuPrasad\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 2 Sep 2021 10:06:52 +0530", "msg_from": "Sadhuprasad Patro <b.sadhu@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" }, { "msg_contents": "\n\nOn 2021/09/02 13:36, Sadhuprasad Patro wrote:\n> Yes this update is fine.. Please commit this patch...\n\nYeah, pushed. Thanks!\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 2 Sep 2021 14:04:56 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Support reset of Shared objects statistics in \"pg_stat_reset\"\n function" } ]
[ { "msg_contents": "Hi,\n\nI have been working on analyzing the performance of sending the tuple\nfrom workers to the Gather using the tuple queue. In the past there\nwere many off-list discussions around this area, basically, the main\npoint is that when the \"shm_mq\" was implemented that time maybe this\nwas one of the best ways to implement this. But now, we have other\nchoices like DSA for allocating shared memory on-demand, shared\ntemporary files for non-blocking tuple queue.\n\nSo my motivation for looking into this area is that now, we have\nanother flexible alternative so can we use them to make gather faster\nand if so then\n1. Can we actually reduce the tuple transfer cost and enable\nparallelism in more cases by reducing parallel_tuple_cost.\n2. Can we use the tuple queue in more places, e.g., to implement the\nredistribute operator where we need to transfer data between the\nworkers.\n\nIMHO for #1, it will be good enough if we can make the tuple transfer\nfaster, but for #2, we will have to make a) tuple transfer faster\nbecause then we will have to transfer the tuples between the workers\nas well b) Infinite non-blocking tuple queue(maybe using shared temp\nfile) so that there is no deadlock while workers are redistributing\ntuples to each other.\n\nSo I have done some quick performance tests and analysis using perf,\nand some experiments with small prototypes for targeting a different\nset of problems.\n\n--Setup\nSET parallel_tuple_cost TO 0 -- to test parallelism in the extreme case\nCREATE TABLE t (a int, b varchar);\nINSERT INTO t SELECT i, repeat('a', 200) from generate_series(1,200000000) as i;\nANALYZE t;\nTest query: EXPLAIN ANALYZE SELECT * FROM t;\n\nPerf analysis: Gather Node\n - 43.57% shm_mq_receive\n - 78.94% shm_mq_receive_bytes\n - 91.27% pg_atomic_read_u64\n - pg_atomic_read_u64_impl\n - apic_timer_interrupt\n smp_apic_timer_interrupt\n\nPerf analysis: Worker Node\n - 99.14% shm_mq_sendv\n - 74.10% shm_mq_send_bytes\n + 42.35% shm_mq_inc_bytes_written\n - 32.56% pg_atomic_read_u64\n - pg_atomic_read_u64_impl\n - 86.27% apic_timer_interrupt\n + 17.93% WaitLatch\n\n From the perf results and also from the code analysis I can think of\ntwo main problems here\n1. Schyncronization between the worker and gather node, just to\nidentify the bytes written and read they need to do at least 2-3\natomic operations for each tuple and I think that is having huge\npenalty due to a) frequent cache line invalidation b) a lot of atomic\noperations.\n\n2. If the tuple queue is full then the worker might need to wait for\nthe gather to consume the tuple.\n\nExperiment #1:\nAs part of this experiment, I have modified the sender to keep the\nlocal copy of \"mq_bytes_read\" and \"mq_bytes_written\" in the local mqh\nhandle so that we don't need to frequently read/write cache sensitive\nshared memory variables. So now we only read/write from the shared\nmemory in the below conditions\n\n1) If the number of available bytes is not enough to send the tuple,\nread the updated value of bytes read and also inform the reader about\nthe new writes.\n2) After every 4k bytes written, update the shared memory variable and\ninform the reader.\n3) on detach for sending any remaining data.\n\nMachine information:\nArchitecture: x86_64\nCPU op-mode(s): 32-bit, 64-bit\nCPU(s): 56\nOn-line CPU(s) list: 0-55\nThread(s) per core: 2\nCore(s) per socket: 14\nSocket(s): 2\nNUMA node(s): 2\n\nResults: (query EXPLAIN ANALYZE SELECT * FROM t;)\n1) Non-parallel (default)\n Execution Time: 31627.492 ms\n\n2) Parallel with 4 workers (force by setting parallel_tuple_cost to 0)\n Execution Time: 37498.672 ms\n\n3) Same as above (2) but with the patch.\nExecution Time: 23649.287 ms\n\nObservation:\n- As expected the results show that forcing the parallelism (by\nreducing the parallel_tuple_cost), drastically impacts the\nperformance.\n- But in the same scenario, with the patch, we can see a huge gain of ~40%\n- Even if we compare it with the non-parallel plan we have gain ~25%.\n- With this, I think we can conclude that there is a huge potential\nfor improvement if we communicate the tuple in batches, 1) one simple\napproach is what I used in my experiment, I think we can do some\noptimization in the reader as well, that instead of reading\nbytes_written every time from shared memory remember the previous\nvalue and once we have exhausted that then only read back the updated\nvalue from the shared memory. 2) Instead of copying the whole tuple\nin the tuple queue we can copy store the dsa_pointers of the tuple\nbatch, I think Thomas Munro also suggested a similar approach to\nRobert, got to know this in offlist discussion with Robert.\n\nExperiment #2: See the behavior by increasing the parallel tuple queue\nsize on head\n(for this I created a small patch to make parallel_tuple_queue size\nconfigurable)\n\n-- Results\n4 WORKERS (tup_queue size= 64kB) : 38337.046 ms\n4 WORKERS (tup_queue size= 1MB) : 36186.883 ms\n4 WORKERS (tup_queue size= 4MB) : 36252.740 ms\n\n8 WORKERS (tup_queue size= 64kB) : 42296.731 ms\n8 WORKERS (tup_queue size= 1MB) : 37403.872 ms\n8 WORKERS (tup_queue size= 4MB) : 39184.319 ms\n\n16 WORKERS (tup_queue size= 64kB) : 42726.139 ms\n16 WORKERS (tup_queue size= 1MB) : 36219.975 ms\n16 WORKERS (tup_queue size= 4MB) : 39117.109 ms\n\nObservation:\n- There are some gains by increasing the tuple queue size but that is\nlimited up to 1MB, even tried with more data but the gain is not\nlinear and performance starts to drop after 4MB.\n- If I apply both Experiment#1 and Experiment#2 patches together then,\nwe can further reduce the execution time to 20963.539 ms (with 4\nworkers and 4MB tuple queue size)\n\nConclusion:\nWith the above experiments,\n1) I see a huge potential in the first idea so maybe we can do more\nexperiments based on the prototype implemented in the first idea and\nwe can expand the same for the reader and we can also try out the idea\nof the dsa_pointers.\n\n2) with the second idea of tuple queue size, I see some benefit but\nthat is not scaling so maybe, for now, there is no much point in\npursuing in this direction, but I think in the future if we want to\nimplement the redistribute operator then it is must for providing an\ninfinite tuple queue (maybe using temp file) to avoid deadlock.\n\nNote: POC patches are not attached, I will send them after some more\nexperiments and cleanup, maybe I will try to optimize the reader part\nas well before sending them.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 6 Aug 2021 14:00:48 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Gather performance analysis" }, { "msg_contents": "On Fri, Aug 6, 2021 at 2:00 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> Experiment #1:\n> As part of this experiment, I have modified the sender to keep the\n> local copy of \"mq_bytes_read\" and \"mq_bytes_written\" in the local mqh\n> handle so that we don't need to frequently read/write cache sensitive\n> shared memory variables. So now we only read/write from the shared\n> memory in the below conditions\n>\n> 1) If the number of available bytes is not enough to send the tuple,\n> read the updated value of bytes read and also inform the reader about\n> the new writes.\n> 2) After every 4k bytes written, update the shared memory variable and\n> inform the reader.\n> 3) on detach for sending any remaining data.\n...\n> Results: (query EXPLAIN ANALYZE SELECT * FROM t;)\n> 1) Non-parallel (default)\n> Execution Time: 31627.492 ms\n>\n> 2) Parallel with 4 workers (force by setting parallel_tuple_cost to 0)\n> Execution Time: 37498.672 ms\n>\n> 3) Same as above (2) but with the patch.\n> Execution Time: 23649.287 ms\n\nHere is the POC patch for the same, apart from this extreme case I am\nable to see improvement with this patch for normal parallel queries as\nwell.\n\nNext, I will perform some more tests with different sets of queries to\nsee the improvements and post the results. I will also try to\noptimize the reader on the similar line.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Sat, 7 Aug 2021 13:47:50 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Fri, Aug 6, 2021 at 4:31 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> Results: (query EXPLAIN ANALYZE SELECT * FROM t;)\n> 1) Non-parallel (default)\n> Execution Time: 31627.492 ms\n>\n> 2) Parallel with 4 workers (force by setting parallel_tuple_cost to 0)\n> Execution Time: 37498.672 ms\n>\n> 3) Same as above (2) but with the patch.\n> Execution Time: 23649.287 ms\n\nThis strikes me as an amazingly good result. I guess before seeing\nthese results, I would have said that you can't reasonably expect\nparallel query to win on a query like this because there isn't enough\nfor the workers to do. It's not like they are spending time evaluating\nfilter conditions or anything like that - they're just fetching tuples\noff of disk pages and sticking them into a queue. And it's unclear to\nme why it should be better to have a bunch of processes doing that\ninstead of just one. I would have thought, looking at just (1) and\n(2), that parallelism gained nothing and communication overhead lost 6\nseconds.\n\nBut what this suggests is that parallelism gained at least 8 seconds,\nand communication overhead lost at least 14 seconds. In fact...\n\n> - If I apply both Experiment#1 and Experiment#2 patches together then,\n> we can further reduce the execution time to 20963.539 ms (with 4\n> workers and 4MB tuple queue size)\n\n...this suggests that parallelism actually gained at least 10-11\nseconds, and the communication overhead lost at least 15-16 seconds.\nIf that's accurate, it's pretty crazy. We might need to drastically\nreduce the value of parallel_tuple_cost if these results hold up and\nthis patch gets committed.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 24 Aug 2021 11:18:04 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Tue, Aug 24, 2021 at 8:48 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Fri, Aug 6, 2021 at 4:31 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> > Results: (query EXPLAIN ANALYZE SELECT * FROM t;)\n> > 1) Non-parallel (default)\n> > Execution Time: 31627.492 ms\n> >\n> > 2) Parallel with 4 workers (force by setting parallel_tuple_cost to 0)\n> > Execution Time: 37498.672 ms\n> >\n> > 3) Same as above (2) but with the patch.\n> > Execution Time: 23649.287 ms\n>\n> This strikes me as an amazingly good result. I guess before seeing\n> these results, I would have said that you can't reasonably expect\n> parallel query to win on a query like this because there isn't enough\n> for the workers to do. It's not like they are spending time evaluating\n> filter conditions or anything like that - they're just fetching tuples\n> off of disk pages and sticking them into a queue. And it's unclear to\n> me why it should be better to have a bunch of processes doing that\n> instead of just one. I would have thought, looking at just (1) and\n> (2), that parallelism gained nothing and communication overhead lost 6\n> seconds.\n>\n> But what this suggests is that parallelism gained at least 8 seconds,\n> and communication overhead lost at least 14 seconds. In fact...\n>\n\nRight, good observation.\n\n\n> > - If I apply both Experiment#1 and Experiment#2 patches together then,\n> > we can further reduce the execution time to 20963.539 ms (with 4\n> > workers and 4MB tuple queue size)\n>\n> ...this suggests that parallelism actually gained at least 10-11\n> seconds, and the communication overhead lost at least 15-16 seconds.\n>\n\nYes\n\n\n> If that's accurate, it's pretty crazy. We might need to drastically\n> reduce the value of parallel_tuple_cost if these results hold up and\n> this patch gets committed.\n>\n\nIn one of my experiments[Test1] I have noticed that even on the head the\nforce parallel plan is significantly faster compared to the non-parallel\nplan, but with patch it is even better. The point is now also there might\nbe some cases where the force parallel plans are faster but we are not sure\nwhether we can reduce the parallel_tuple_cost or not. But with the patch\nit is definitely sure that the parallel tuple queue is faster compared to\nwhat we have now, So I agree we should consider reducing the\nparallel_tuple_cost after this patch.\n\nAdditionally, I've done some more experiments with artificial workloads, as\nwell as workloads where the parallel plan is selected by default, and in\nall cases I've seen a significant improvement. The gain is directly\nproportional to the load on the tuple queue, as expected.\n\nTest1: (Worker returns all tuples but only few tuples returns to the client)\n----------------------------------------------------\nINSERT INTO t SELECT i%10, repeat('a', 200) from\ngenerate_series(1,200000000) as i;\nset max_parallel_workers_per_gather=4;\n\nTarget Query: SELECT random() FROM t GROUP BY a;\n\nNon-parallel (default plan): 77170.421 ms\nParallel (parallel_tuple_cost=0): 53794.324 ms\nParallel with patch (parallel_tuple_cost=0): 42567.850 ms\n\n20% gain compared force parallel, 45% gain compared to default plan.\n\nTest2: (Parallel case with default parallel_tuple_cost)\n----------------------------------------------\nINSERT INTO t SELECT i, repeat('a', 200) from generate_series(1,200000000)\nas i;\n\nset max_parallel_workers_per_gather=4;\nSELECT * from t WHERE a < 17500000;\nParallel(default plan): 23730.054 ms\nParallel with patch (default plan): 21614.251 ms\n\n8 to 10 % gain compared to the default parallel plan.\n\nI have done cleanup in the patch and I will add this to the September\ncommitfest.\n\nI am planning to do further testing for identifying the optimal batch size\nin different workloads. WIth above workload I am seeing similar results\nwith batch size 4k to 16k (1/4 of the ring size) so in the attached patch I\nhave kept as 1/4 of the ring size. We might change that based on more\nanalysis and testing.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Sat, 28 Aug 2021 12:40:39 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Sat, Aug 28, 2021 at 12:11 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n\n> On Tue, Aug 24, 2021 at 8:48 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n>> On Fri, Aug 6, 2021 at 4:31 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>> > Results: (query EXPLAIN ANALYZE SELECT * FROM t;)\n>> > 1) Non-parallel (default)\n>> > Execution Time: 31627.492 ms\n>> >\n>> > 2) Parallel with 4 workers (force by setting parallel_tuple_cost to 0)\n>> > Execution Time: 37498.672 ms\n>> >\n>> > 3) Same as above (2) but with the patch.\n>> > Execution Time: 23649.287 ms\n>>\n>> This strikes me as an amazingly good result. I guess before seeing\n>> these results, I would have said that you can't reasonably expect\n>> parallel query to win on a query like this because there isn't enough\n>> for the workers to do. It's not like they are spending time evaluating\n>> filter conditions or anything like that - they're just fetching tuples\n>> off of disk pages and sticking them into a queue. And it's unclear to\n>> me why it should be better to have a bunch of processes doing that\n>> instead of just one. I would have thought, looking at just (1) and\n>> (2), that parallelism gained nothing and communication overhead lost 6\n>> seconds.\n>>\n>> But what this suggests is that parallelism gained at least 8 seconds,\n>> and communication overhead lost at least 14 seconds. In fact...\n>>\n>\n> Right, good observation.\n>\n>\n>> > - If I apply both Experiment#1 and Experiment#2 patches together then,\n>> > we can further reduce the execution time to 20963.539 ms (with 4\n>> > workers and 4MB tuple queue size)\n>>\n>> ...this suggests that parallelism actually gained at least 10-11\n>> seconds, and the communication overhead lost at least 15-16 seconds.\n>>\n>\n> Yes\n>\n>\n>> If that's accurate, it's pretty crazy. We might need to drastically\n>> reduce the value of parallel_tuple_cost if these results hold up and\n>> this patch gets committed.\n>>\n>\n> In one of my experiments[Test1] I have noticed that even on the head the\n> force parallel plan is significantly faster compared to the non-parallel\n> plan, but with patch it is even better. The point is now also there might\n> be some cases where the force parallel plans are faster but we are not sure\n> whether we can reduce the parallel_tuple_cost or not. But with the patch\n> it is definitely sure that the parallel tuple queue is faster compared to\n> what we have now, So I agree we should consider reducing the\n> parallel_tuple_cost after this patch.\n>\n> Additionally, I've done some more experiments with artificial workloads,\n> as well as workloads where the parallel plan is selected by default, and in\n> all cases I've seen a significant improvement. The gain is directly\n> proportional to the load on the tuple queue, as expected.\n>\n> Test1: (Worker returns all tuples but only few tuples returns to the\n> client)\n> ----------------------------------------------------\n> INSERT INTO t SELECT i%10, repeat('a', 200) from\n> generate_series(1,200000000) as i;\n> set max_parallel_workers_per_gather=4;\n>\n> Target Query: SELECT random() FROM t GROUP BY a;\n>\n> Non-parallel (default plan): 77170.421 ms\n> Parallel (parallel_tuple_cost=0): 53794.324 ms\n> Parallel with patch (parallel_tuple_cost=0): 42567.850 ms\n>\n> 20% gain compared force parallel, 45% gain compared to default plan.\n>\n> Test2: (Parallel case with default parallel_tuple_cost)\n> ----------------------------------------------\n> INSERT INTO t SELECT i, repeat('a', 200) from generate_series(1,200000000)\n> as i;\n>\n> set max_parallel_workers_per_gather=4;\n> SELECT * from t WHERE a < 17500000;\n> Parallel(default plan): 23730.054 ms\n> Parallel with patch (default plan): 21614.251 ms\n>\n> 8 to 10 % gain compared to the default parallel plan.\n>\n> I have done cleanup in the patch and I will add this to the September\n> commitfest.\n>\n> I am planning to do further testing for identifying the optimal batch size\n> in different workloads. WIth above workload I am seeing similar results\n> with batch size 4k to 16k (1/4 of the ring size) so in the attached patch I\n> have kept as 1/4 of the ring size. We might change that based on more\n> analysis and testing.\n>\n> --\n> Regards,\n> Dilip Kumar\n> EnterpriseDB: http://www.enterprisedb.com\n>\nHi,\nSome minor comments.\nFor shm_mq.c, existing comment says:\n\n * mqh_partial_bytes, mqh_expected_bytes, and mqh_length_word_complete\n\n+ Size mqh_send_pending;\n bool mqh_length_word_complete;\n bool mqh_counterparty_attached;\n\nI wonder if mqh_send_pending should be declared\nafter mqh_length_word_complete - this way, the order of fields matches the\norder of explanation for the fields.\n\n+ if (mqh->mqh_send_pending > mq->mq_ring_size / 4 || force_flush)\n\nThe above can be written as:\n\n+ if (force_flush || mqh->mqh_send_pending > (mq->mq_ring_size >> 1))\n\nso that when force_flush is true, the other condition is not evaluated.\n\nCheers\n\nOn Sat, Aug 28, 2021 at 12:11 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:On Tue, Aug 24, 2021 at 8:48 PM Robert Haas <robertmhaas@gmail.com> wrote:On Fri, Aug 6, 2021 at 4:31 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> Results: (query EXPLAIN ANALYZE SELECT * FROM t;)\n> 1) Non-parallel (default)\n>  Execution Time: 31627.492 ms\n>\n> 2) Parallel with 4 workers (force by setting parallel_tuple_cost to 0)\n>  Execution Time: 37498.672 ms\n>\n> 3) Same as above (2) but with the patch.\n> Execution Time: 23649.287 ms\n\nThis strikes me as an amazingly good result. I guess before seeing\nthese results, I would have said that you can't reasonably expect\nparallel query to win on a query like this because there isn't enough\nfor the workers to do. It's not like they are spending time evaluating\nfilter conditions or anything like that - they're just fetching tuples\noff of disk pages and sticking them into a queue. And it's unclear to\nme why it should be better to have a bunch of processes doing that\ninstead of just one. I would have thought, looking at just (1) and\n(2), that parallelism gained nothing and communication overhead lost 6\nseconds.\n\nBut what this suggests is that parallelism gained at least 8 seconds,\nand communication overhead lost at least 14 seconds. In fact...Right, good observation. \n\n> - If I apply both Experiment#1 and Experiment#2 patches together then,\n> we can further reduce the execution time to 20963.539 ms (with 4\n> workers and 4MB tuple queue size)\n\n...this suggests that parallelism actually gained at least 10-11\nseconds, and the communication overhead lost at least 15-16 seconds.Yes \nIf that's accurate, it's pretty crazy. We might need to drastically\nreduce the value of parallel_tuple_cost if these results hold up and\nthis patch gets committed.In one of my experiments[Test1] I have noticed that even on the head the force parallel plan is significantly faster compared to the non-parallel plan, but with patch it is even better.  The point is now also there might be some cases where the force parallel plans are faster but we are not sure whether we can reduce the parallel_tuple_cost or not.  But with the patch it is definitely sure that the parallel tuple queue is faster compared to what we have now, So I agree we should consider reducing the parallel_tuple_cost after this patch.Additionally, I've done some more experiments with artificial workloads, as well as workloads where the parallel plan is selected by default, and in all cases I've seen a significant improvement.  The gain is directly proportional to the load on the tuple queue, as expected.Test1: (Worker returns all tuples but only few tuples returns to the client)----------------------------------------------------INSERT INTO t SELECT i%10, repeat('a', 200) from generate_series(1,200000000) as i;set max_parallel_workers_per_gather=4;Target Query: SELECT random() FROM t GROUP BY a;Non-parallel (default plan): 77170.421 msParallel (parallel_tuple_cost=0):  53794.324 msParallel with patch (parallel_tuple_cost=0): 42567.850 ms20% gain compared force parallel, 45% gain compared to default plan.Test2: (Parallel case with default parallel_tuple_cost)----------------------------------------------INSERT INTO t SELECT i, repeat('a', 200) from generate_series(1,200000000) as i;set max_parallel_workers_per_gather=4;SELECT * from t WHERE a < 17500000;Parallel(default plan): 23730.054 msParallel with patch (default plan): 21614.251 ms8 to 10 % gain compared to the default parallel plan.I have done cleanup in the patch and I will add this to the September commitfest.I am planning to do further testing for identifying the optimal batch size in different workloads.  WIth above workload I am seeing similar results with batch size 4k to 16k (1/4 of the ring size) so in the attached patch I have kept as 1/4 of the ring size.  We might change that based on more analysis and testing.-- Regards,Dilip KumarEnterpriseDB: http://www.enterprisedb.comHi,Some minor comments.For shm_mq.c, existing comment says: * mqh_partial_bytes, mqh_expected_bytes, and mqh_length_word_complete +   Size        mqh_send_pending;    bool        mqh_length_word_complete;    bool        mqh_counterparty_attached;I wonder if mqh_send_pending should be declared after mqh_length_word_complete - this way, the order of fields matches the order of explanation for the fields.+   if (mqh->mqh_send_pending > mq->mq_ring_size / 4 || force_flush)The above can be written as:+   if (force_flush || mqh->mqh_send_pending > (mq->mq_ring_size >> 1))so that when force_flush is true, the other condition is not evaluated.Cheers", "msg_date": "Sat, 28 Aug 2021 04:29:08 -0700", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Sat, Aug 28, 2021 at 4:29 AM Zhihong Yu <zyu@yugabyte.com> wrote:\n\n>\n>\n> On Sat, Aug 28, 2021 at 12:11 AM Dilip Kumar <dilipbalaut@gmail.com>\n> wrote:\n>\n>> On Tue, Aug 24, 2021 at 8:48 PM Robert Haas <robertmhaas@gmail.com>\n>> wrote:\n>>\n>>> On Fri, Aug 6, 2021 at 4:31 AM Dilip Kumar <dilipbalaut@gmail.com>\n>>> wrote:\n>>> > Results: (query EXPLAIN ANALYZE SELECT * FROM t;)\n>>> > 1) Non-parallel (default)\n>>> > Execution Time: 31627.492 ms\n>>> >\n>>> > 2) Parallel with 4 workers (force by setting parallel_tuple_cost to 0)\n>>> > Execution Time: 37498.672 ms\n>>> >\n>>> > 3) Same as above (2) but with the patch.\n>>> > Execution Time: 23649.287 ms\n>>>\n>>> This strikes me as an amazingly good result. I guess before seeing\n>>> these results, I would have said that you can't reasonably expect\n>>> parallel query to win on a query like this because there isn't enough\n>>> for the workers to do. It's not like they are spending time evaluating\n>>> filter conditions or anything like that - they're just fetching tuples\n>>> off of disk pages and sticking them into a queue. And it's unclear to\n>>> me why it should be better to have a bunch of processes doing that\n>>> instead of just one. I would have thought, looking at just (1) and\n>>> (2), that parallelism gained nothing and communication overhead lost 6\n>>> seconds.\n>>>\n>>> But what this suggests is that parallelism gained at least 8 seconds,\n>>> and communication overhead lost at least 14 seconds. In fact...\n>>>\n>>\n>> Right, good observation.\n>>\n>>\n>>> > - If I apply both Experiment#1 and Experiment#2 patches together then,\n>>> > we can further reduce the execution time to 20963.539 ms (with 4\n>>> > workers and 4MB tuple queue size)\n>>>\n>>> ...this suggests that parallelism actually gained at least 10-11\n>>> seconds, and the communication overhead lost at least 15-16 seconds.\n>>>\n>>\n>> Yes\n>>\n>>\n>>> If that's accurate, it's pretty crazy. We might need to drastically\n>>> reduce the value of parallel_tuple_cost if these results hold up and\n>>> this patch gets committed.\n>>>\n>>\n>> In one of my experiments[Test1] I have noticed that even on the head the\n>> force parallel plan is significantly faster compared to the non-parallel\n>> plan, but with patch it is even better. The point is now also there might\n>> be some cases where the force parallel plans are faster but we are not sure\n>> whether we can reduce the parallel_tuple_cost or not. But with the patch\n>> it is definitely sure that the parallel tuple queue is faster compared to\n>> what we have now, So I agree we should consider reducing the\n>> parallel_tuple_cost after this patch.\n>>\n>> Additionally, I've done some more experiments with artificial workloads,\n>> as well as workloads where the parallel plan is selected by default, and in\n>> all cases I've seen a significant improvement. The gain is directly\n>> proportional to the load on the tuple queue, as expected.\n>>\n>> Test1: (Worker returns all tuples but only few tuples returns to the\n>> client)\n>> ----------------------------------------------------\n>> INSERT INTO t SELECT i%10, repeat('a', 200) from\n>> generate_series(1,200000000) as i;\n>> set max_parallel_workers_per_gather=4;\n>>\n>> Target Query: SELECT random() FROM t GROUP BY a;\n>>\n>> Non-parallel (default plan): 77170.421 ms\n>> Parallel (parallel_tuple_cost=0): 53794.324 ms\n>> Parallel with patch (parallel_tuple_cost=0): 42567.850 ms\n>>\n>> 20% gain compared force parallel, 45% gain compared to default plan.\n>>\n>> Test2: (Parallel case with default parallel_tuple_cost)\n>> ----------------------------------------------\n>> INSERT INTO t SELECT i, repeat('a', 200) from\n>> generate_series(1,200000000) as i;\n>>\n>> set max_parallel_workers_per_gather=4;\n>> SELECT * from t WHERE a < 17500000;\n>> Parallel(default plan): 23730.054 ms\n>> Parallel with patch (default plan): 21614.251 ms\n>>\n>> 8 to 10 % gain compared to the default parallel plan.\n>>\n>> I have done cleanup in the patch and I will add this to the September\n>> commitfest.\n>>\n>> I am planning to do further testing for identifying the optimal batch\n>> size in different workloads. WIth above workload I am seeing similar\n>> results with batch size 4k to 16k (1/4 of the ring size) so in the attached\n>> patch I have kept as 1/4 of the ring size. We might change that based on\n>> more analysis and testing.\n>>\n>> --\n>> Regards,\n>> Dilip Kumar\n>> EnterpriseDB: http://www.enterprisedb.com\n>>\n> Hi,\n> Some minor comments.\n> For shm_mq.c, existing comment says:\n>\n> * mqh_partial_bytes, mqh_expected_bytes, and mqh_length_word_complete\n>\n> + Size mqh_send_pending;\n> bool mqh_length_word_complete;\n> bool mqh_counterparty_attached;\n>\n> I wonder if mqh_send_pending should be declared\n> after mqh_length_word_complete - this way, the order of fields matches the\n> order of explanation for the fields.\n>\n> + if (mqh->mqh_send_pending > mq->mq_ring_size / 4 || force_flush)\n>\n> The above can be written as:\n>\n> + if (force_flush || mqh->mqh_send_pending > (mq->mq_ring_size >> 1))\n>\n> so that when force_flush is true, the other condition is not evaluated.\n>\n> Cheers\n>\n\nThere was a typo in suggested code above. It should be:\n\n+ if (force_flush || mqh->mqh_send_pending > (mq->mq_ring_size >> 2))\n\nCheers\n\nOn Sat, Aug 28, 2021 at 4:29 AM Zhihong Yu <zyu@yugabyte.com> wrote:On Sat, Aug 28, 2021 at 12:11 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:On Tue, Aug 24, 2021 at 8:48 PM Robert Haas <robertmhaas@gmail.com> wrote:On Fri, Aug 6, 2021 at 4:31 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> Results: (query EXPLAIN ANALYZE SELECT * FROM t;)\n> 1) Non-parallel (default)\n>  Execution Time: 31627.492 ms\n>\n> 2) Parallel with 4 workers (force by setting parallel_tuple_cost to 0)\n>  Execution Time: 37498.672 ms\n>\n> 3) Same as above (2) but with the patch.\n> Execution Time: 23649.287 ms\n\nThis strikes me as an amazingly good result. I guess before seeing\nthese results, I would have said that you can't reasonably expect\nparallel query to win on a query like this because there isn't enough\nfor the workers to do. It's not like they are spending time evaluating\nfilter conditions or anything like that - they're just fetching tuples\noff of disk pages and sticking them into a queue. And it's unclear to\nme why it should be better to have a bunch of processes doing that\ninstead of just one. I would have thought, looking at just (1) and\n(2), that parallelism gained nothing and communication overhead lost 6\nseconds.\n\nBut what this suggests is that parallelism gained at least 8 seconds,\nand communication overhead lost at least 14 seconds. In fact...Right, good observation. \n\n> - If I apply both Experiment#1 and Experiment#2 patches together then,\n> we can further reduce the execution time to 20963.539 ms (with 4\n> workers and 4MB tuple queue size)\n\n...this suggests that parallelism actually gained at least 10-11\nseconds, and the communication overhead lost at least 15-16 seconds.Yes \nIf that's accurate, it's pretty crazy. We might need to drastically\nreduce the value of parallel_tuple_cost if these results hold up and\nthis patch gets committed.In one of my experiments[Test1] I have noticed that even on the head the force parallel plan is significantly faster compared to the non-parallel plan, but with patch it is even better.  The point is now also there might be some cases where the force parallel plans are faster but we are not sure whether we can reduce the parallel_tuple_cost or not.  But with the patch it is definitely sure that the parallel tuple queue is faster compared to what we have now, So I agree we should consider reducing the parallel_tuple_cost after this patch.Additionally, I've done some more experiments with artificial workloads, as well as workloads where the parallel plan is selected by default, and in all cases I've seen a significant improvement.  The gain is directly proportional to the load on the tuple queue, as expected.Test1: (Worker returns all tuples but only few tuples returns to the client)----------------------------------------------------INSERT INTO t SELECT i%10, repeat('a', 200) from generate_series(1,200000000) as i;set max_parallel_workers_per_gather=4;Target Query: SELECT random() FROM t GROUP BY a;Non-parallel (default plan): 77170.421 msParallel (parallel_tuple_cost=0):  53794.324 msParallel with patch (parallel_tuple_cost=0): 42567.850 ms20% gain compared force parallel, 45% gain compared to default plan.Test2: (Parallel case with default parallel_tuple_cost)----------------------------------------------INSERT INTO t SELECT i, repeat('a', 200) from generate_series(1,200000000) as i;set max_parallel_workers_per_gather=4;SELECT * from t WHERE a < 17500000;Parallel(default plan): 23730.054 msParallel with patch (default plan): 21614.251 ms8 to 10 % gain compared to the default parallel plan.I have done cleanup in the patch and I will add this to the September commitfest.I am planning to do further testing for identifying the optimal batch size in different workloads.  WIth above workload I am seeing similar results with batch size 4k to 16k (1/4 of the ring size) so in the attached patch I have kept as 1/4 of the ring size.  We might change that based on more analysis and testing.-- Regards,Dilip KumarEnterpriseDB: http://www.enterprisedb.comHi,Some minor comments.For shm_mq.c, existing comment says: * mqh_partial_bytes, mqh_expected_bytes, and mqh_length_word_complete +   Size        mqh_send_pending;    bool        mqh_length_word_complete;    bool        mqh_counterparty_attached;I wonder if mqh_send_pending should be declared after mqh_length_word_complete - this way, the order of fields matches the order of explanation for the fields.+   if (mqh->mqh_send_pending > mq->mq_ring_size / 4 || force_flush)The above can be written as:+   if (force_flush || mqh->mqh_send_pending > (mq->mq_ring_size >> 1))so that when force_flush is true, the other condition is not evaluated.Cheers There  was a typo in suggested code above. It should be:+   if (force_flush || mqh->mqh_send_pending > (mq->mq_ring_size >> 2))Cheers", "msg_date": "Sat, 28 Aug 2021 04:33:59 -0700", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "Hi,\n\nThe numbers presented in this thread seem very promising - clearly\nthere's significant potential for improvements. I'll run similar\nbenchmarks too, to get a better understanding of this.\n\nCan you share some basic details about the hardware you used?\nParticularly the CPU model - I guess this might explain some of the\nresults, e.g. if CPU caches are ~1MB, that'd explain why setting\ntup_queue_size to 1MB improves things, but 4MB is a bit slower.\nSimilarly, number of cores might explain why 4 workers perform better\nthan 8 or 16 workers.\n\nNow, this is mostly expected, but the consequence is that maybe things\nlike queue size should be tunable/dynamic, not hard-coded?\n\nAs for the patches, I think the proposed changes are sensible, but I\nwonder what queries might get slower. For example with the batching\n(updating the counter only once every 4kB, that pretty much transfers\ndata in larger chunks with higher latency. So what if the query needs\nonly a small chunk, like a LIMIT query? Similarly, this might mean the\nupper parts of the plan have to wait for the data for longer, and thus\ncan't start some async operation (like send them to a FDW, or something\nlike that). I do admit those are theoretical queries, I haven't tried\ncreating such query.\n\nFWIW I've tried applying both patches at the same time, but there's a\nconflict in shm_mq_sendv - not a complex one, but I'm not sure what's\nthe correct solution. Can you share a \"combined\" patch?\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 7 Sep 2021 17:11:47 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "Hi,\n\nOn 2021-08-06 14:00:48 +0530, Dilip Kumar wrote:\n> --Setup\n> SET parallel_tuple_cost TO 0 -- to test parallelism in the extreme case\n> CREATE TABLE t (a int, b varchar);\n> INSERT INTO t SELECT i, repeat('a', 200) from generate_series(1,200000000) as i;\n> ANALYZE t;\n> Test query: EXPLAIN ANALYZE SELECT * FROM t;\n> \n> Perf analysis: Gather Node\n> - 43.57% shm_mq_receive\n> - 78.94% shm_mq_receive_bytes\n> - 91.27% pg_atomic_read_u64\n> - pg_atomic_read_u64_impl\n> - apic_timer_interrupt\n> smp_apic_timer_interrupt\n> \n> Perf analysis: Worker Node\n> - 99.14% shm_mq_sendv\n> - 74.10% shm_mq_send_bytes\n> + 42.35% shm_mq_inc_bytes_written\n> - 32.56% pg_atomic_read_u64\n> - pg_atomic_read_u64_impl\n> - 86.27% apic_timer_interrupt\n> + 17.93% WaitLatch\n> \n> From the perf results and also from the code analysis I can think of\n> two main problems here\n\nLooking at this profile made me wonder if this was a build without\noptimizations. The pg_atomic_read_u64()/pg_atomic_read_u64_impl() calls should\nbe inlined. And while perf can reconstruct inlined functions when using\n--call-graph=dwarf, they show up like \"pg_atomic_read_u64 (inlined)\" for me.\n\nFWIW, I see times like this\n\npostgres[4144648][1]=# EXPLAIN (ANALYZE, TIMING OFF) SELECT * FROM t;\n┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────┐\n│ QUERY PLAN │\n├──────────────────────────────────────────────────────────────────────────────────────────────────────────────┤\n│ Gather (cost=1000.00..6716686.33 rows=200000000 width=208) (actual rows=200000000 loops=1) │\n│ Workers Planned: 2 │\n│ Workers Launched: 2 │\n│ -> Parallel Seq Scan on t (cost=0.00..6715686.33 rows=83333333 width=208) (actual rows=66666667 loops=3) │\n│ Planning Time: 0.043 ms │\n│ Execution Time: 24954.012 ms │\n└──────────────────────────────────────────────────────────────────────────────────────────────────────────────┘\n(6 rows)\n\n\nLooking at a profile I see the biggest bottleneck in the leader (which is the\nbottleneck as soon as the worker count is increased) to be reading the length\nword of the message. I do see shm_mq_receive_bytes() in the profile, but the\ncostly part there is the \"read % (uint64) ringsize\" - divisions are slow. We\ncould just compute a mask instead of the size.\n\nWe also should probably split the read-mostly data in shm_mq (ring_size,\ndetached, ring_offset, receiver, sender) into a separate cacheline from the\nread/write data. Or perhaps copy more info into the handle, particularly the\nringsize (or mask).\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 7 Sep 2021 14:38:44 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Tue, Sep 7, 2021 at 8:41 PM Tomas Vondra <tomas.vondra@enterprisedb.com>\nwrote:\n\n> Hi,\n>\n> The numbers presented in this thread seem very promising - clearly\n> there's significant potential for improvements. I'll run similar\n> benchmarks too, to get a better understanding of this.\n>\n\nThanks for showing interest.\n\n\n>\n> Can you share some basic details about the hardware you used?\n> Particularly the CPU model - I guess this might explain some of the\n> results, e.g. if CPU caches are ~1MB, that'd explain why setting\n> tup_queue_size to 1MB improves things, but 4MB is a bit slower.\n> Similarly, number of cores might explain why 4 workers perform better\n> than 8 or 16 workers.\n>\n\nI have attached the output of the lscpu. I think batching the data before\nupdating in the shared memory will win because we are avoiding the frequent\ncache misses and IMHO the benefit will be more in the machine with more CPU\nsockets.\n\nNow, this is mostly expected, but the consequence is that maybe things\n> like queue size should be tunable/dynamic, not hard-coded?\n>\n\nActually, my intention behind the tuple queue size was to just see the\nbehavior. Do we really have the problem of workers stalling on queue while\nsending the tuple, the perf report showed some load on WaitLatch on the\nworker side so I did this experiment. I saw some benefits but it was not\nreally huge. I am not sure whether we want to just increase the tuple\nqueue size or make it tunable, but if we want to support redistribute\noperators in future sometime then maybe we should make it dynamically\ngrowing at runtime, maybe using dsa or dsa + shared files.\n\n\n> As for the patches, I think the proposed changes are sensible, but I\n> wonder what queries might get slower. For example with the batching\n> (updating the counter only once every 4kB, that pretty much transfers\n> data in larger chunks with higher latency. So what if the query needs\n> only a small chunk, like a LIMIT query? Similarly, this might mean the\n> upper parts of the plan have to wait for the data for longer, and thus\n> can't start some async operation (like send them to a FDW, or something\n> like that). I do admit those are theoretical queries, I haven't tried\n> creating such query.\n>\n\nYeah, I was thinking about such cases, basically, this design can increase\nthe startup cost of the Gather node, I will also try to derive such cases\nand test them.\n\n\n>\n> FWIW I've tried applying both patches at the same time, but there's a\n> conflict in shm_mq_sendv - not a complex one, but I'm not sure what's\n> the correct solution. Can you share a \"combined\" patch?\n>\n\nActually, these both patches are the same,\n\"v1-0001-Optimize-parallel-tuple-send-shm_mq_send_bytes.patch\" is the\ncleaner version of the first patch. For configurable tuple queue size I\ndid not send a patch, because that is I just used for the testing purpose\nand never intended to to propose anything. My most of the latest\nperformance data I sent with only\n\"v1-0001-Optimize-parallel-tuple-send-shm_mq_send_bytes.patch\" and with\ndefault tuple queue size.\n\nBut I am attaching both the patches in case you want to play around.\n\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Wed, 8 Sep 2021 11:35:55 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Wed, Sep 8, 2021 at 3:08 AM Andres Freund <andres@anarazel.de> wrote:\r\n\r\n\r\n> Looking at this profile made me wonder if this was a build without\r\n> optimizations. The pg_atomic_read_u64()/pg_atomic_read_u64_impl() calls\r\n> should\r\n> be inlined. And while perf can reconstruct inlined functions when using\r\n> --call-graph=dwarf, they show up like \"pg_atomic_read_u64 (inlined)\" for\r\n> me.\r\n>\r\n\r\nYeah, for profiling generally I build without optimizations so that I can\r\nsee all the functions in the stack, so yeah profile results are without\r\noptimizations build but the performance results are with optimizations\r\nbuild.\r\n\r\n\r\n>\r\n> FWIW, I see times like this\r\n>\r\n> postgres[4144648][1]=# EXPLAIN (ANALYZE, TIMING OFF) SELECT * FROM t;\r\n>\r\n> ┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────┐\r\n> │ QUERY PLAN\r\n> │\r\n>\r\n> ├──────────────────────────────────────────────────────────────────────────────────────────────────────────────┤\r\n> │ Gather (cost=1000.00..6716686.33 rows=200000000 width=208) (actual\r\n> rows=200000000 loops=1) │\r\n> │ Workers Planned: 2\r\n> │\r\n> │ Workers Launched: 2\r\n> │\r\n> │ -> Parallel Seq Scan on t (cost=0.00..6715686.33 rows=83333333\r\n> width=208) (actual rows=66666667 loops=3) │\r\n> │ Planning Time: 0.043 ms\r\n> │\r\n> │ Execution Time: 24954.012 ms\r\n> │\r\n>\r\n> └──────────────────────────────────────────────────────────────────────────────────────────────────────────────┘\r\n> (6 rows)\r\n>\r\n>\r\nIs this with or without patch, I mean can we see a comparison that patch\r\nimproved anything in your environment?\r\n\r\nLooking at a profile I see the biggest bottleneck in the leader (which is\r\n> the\r\n> bottleneck as soon as the worker count is increased) to be reading the\r\n> length\r\n> word of the message. I do see shm_mq_receive_bytes() in the profile, but\r\n> the\r\n> costly part there is the \"read % (uint64) ringsize\" - divisions are slow.\r\n> We\r\n> could just compute a mask instead of the size.\r\n>\r\n\r\nYeah that could be done, I can test with this change as well that how much\r\nwe gain with this.\r\n\r\n\r\n>\r\n> We also should probably split the read-mostly data in shm_mq (ring_size,\r\n> detached, ring_offset, receiver, sender) into a separate cacheline from the\r\n> read/write data. Or perhaps copy more info into the handle, particularly\r\n> the\r\n> ringsize (or mask).\r\n>\r\n\r\nGood suggestion, I will do some experiments around this.\r\n\r\n-- \r\nRegards,\r\nDilip Kumar\r\nEnterpriseDB: http://www.enterprisedb.com\r\n\nOn Wed, Sep 8, 2021 at 3:08 AM Andres Freund <andres@anarazel.de> wrote: \r\nLooking at this profile made me wonder if this was a build without\r\noptimizations. The pg_atomic_read_u64()/pg_atomic_read_u64_impl() calls should\r\nbe inlined. And while perf can reconstruct inlined functions when using\r\n--call-graph=dwarf, they show up like \"pg_atomic_read_u64 (inlined)\" for me.Yeah, for profiling generally I build without optimizations so that I can see all the functions in the stack, so yeah profile results are without optimizations build but the performance results are with optimizations build. \n\r\nFWIW, I see times like this\n\r\npostgres[4144648][1]=# EXPLAIN (ANALYZE, TIMING OFF) SELECT * FROM t;\r\n┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────┐\r\n│                                                  QUERY PLAN                                                  │\r\n├──────────────────────────────────────────────────────────────────────────────────────────────────────────────┤\r\n│ Gather  (cost=1000.00..6716686.33 rows=200000000 width=208) (actual rows=200000000 loops=1)                  │\r\n│   Workers Planned: 2                                                                                         │\r\n│   Workers Launched: 2                                                                                        │\r\n│   ->  Parallel Seq Scan on t  (cost=0.00..6715686.33 rows=83333333 width=208) (actual rows=66666667 loops=3) │\r\n│ Planning Time: 0.043 ms                                                                                      │\r\n│ Execution Time: 24954.012 ms                                                                                 │\r\n└──────────────────────────────────────────────────────────────────────────────────────────────────────────────┘\r\n(6 rows)\nIs this with or without patch, I mean can we see a comparison that patch improved anything in your environment?\r\nLooking at a profile I see the biggest bottleneck in the leader (which is the\r\nbottleneck as soon as the worker count is increased) to be reading the length\r\nword of the message. I do see shm_mq_receive_bytes() in the profile, but the\r\ncostly part there is the \"read % (uint64) ringsize\" - divisions are slow. We\r\ncould just compute a mask instead of the size.Yeah that could be done, I can test with this change as well that how much we gain with this. \n\r\nWe also should probably split the read-mostly data in shm_mq (ring_size,\r\ndetached, ring_offset, receiver, sender) into a separate cacheline from the\r\nread/write data. Or perhaps copy more info into the handle, particularly the\r\nringsize (or mask).\nGood suggestion, I will do some experiments around this.-- Regards,Dilip KumarEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Wed, 8 Sep 2021 11:45:16 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "Hi,\n\nOn 2021-09-08 11:45:16 +0530, Dilip Kumar wrote:\n> On Wed, Sep 8, 2021 at 3:08 AM Andres Freund <andres@anarazel.de> wrote:\n> \n> \n> > Looking at this profile made me wonder if this was a build without\n> > optimizations. The pg_atomic_read_u64()/pg_atomic_read_u64_impl() calls\n> > should\n> > be inlined. And while perf can reconstruct inlined functions when using\n> > --call-graph=dwarf, they show up like \"pg_atomic_read_u64 (inlined)\" for\n> > me.\n> >\n> \n> Yeah, for profiling generally I build without optimizations so that I can\n> see all the functions in the stack, so yeah profile results are without\n> optimizations build but the performance results are with optimizations\n> build.\n\nI'm afraid that makes the profiles just about meaningless :(.\n\n\n> Is this with or without patch, I mean can we see a comparison that patch\n> improved anything in your environment?\n\nIt was without any patches. I'll try the patch in a bit.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 7 Sep 2021 23:33:47 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Wed, Sep 8, 2021 at 12:03 PM Andres Freund <andres@anarazel.de> wrote:\n\n> Hi,\n>\n> On 2021-09-08 11:45:16 +0530, Dilip Kumar wrote:\n> > On Wed, Sep 8, 2021 at 3:08 AM Andres Freund <andres@anarazel.de> wrote:\n> >\n> >\n> > > Looking at this profile made me wonder if this was a build without\n> > > optimizations. The pg_atomic_read_u64()/pg_atomic_read_u64_impl() calls\n> > > should\n> > > be inlined. And while perf can reconstruct inlined functions when using\n> > > --call-graph=dwarf, they show up like \"pg_atomic_read_u64 (inlined)\"\n> for\n> > > me.\n> > >\n> >\n> > Yeah, for profiling generally I build without optimizations so that I can\n> > see all the functions in the stack, so yeah profile results are without\n> > optimizations build but the performance results are with optimizations\n> > build.\n>\n> I'm afraid that makes the profiles just about meaningless :(.\n>\n\nMaybe it can be misleading sometimes, but I feel sometimes it is more\ninformative compared to the optimized build where it makes some function\ninline, and then it becomes really hard to distinguish which function\nreally has the problem. But your point is taken and I will run with an\noptimized build.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Wed, Sep 8, 2021 at 12:03 PM Andres Freund <andres@anarazel.de> wrote:Hi,\n\nOn 2021-09-08 11:45:16 +0530, Dilip Kumar wrote:\n> On Wed, Sep 8, 2021 at 3:08 AM Andres Freund <andres@anarazel.de> wrote:\n> \n> \n> > Looking at this profile made me wonder if this was a build without\n> > optimizations. The pg_atomic_read_u64()/pg_atomic_read_u64_impl() calls\n> > should\n> > be inlined. And while perf can reconstruct inlined functions when using\n> > --call-graph=dwarf, they show up like \"pg_atomic_read_u64 (inlined)\" for\n> > me.\n> >\n> \n> Yeah, for profiling generally I build without optimizations so that I can\n> see all the functions in the stack, so yeah profile results are without\n> optimizations build but the performance results are with optimizations\n> build.\n\nI'm afraid that makes the profiles just about meaningless :(.Maybe it can be misleading sometimes, but I feel sometimes it is more informative compared to the optimized build where it makes some function inline, and then it becomes really hard to distinguish which function really has the problem.  But your point is taken and I will run with an optimized build.-- Regards,Dilip KumarEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Wed, 8 Sep 2021 13:10:44 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On 9/8/21 9:40 AM, Dilip Kumar wrote:\n> On Wed, Sep 8, 2021 at 12:03 PM Andres Freund <andres@anarazel.de\n> <mailto:andres@anarazel.de>> wrote:\n> \n> Hi,\n> \n> On 2021-09-08 11:45:16 +0530, Dilip Kumar wrote:\n> > On Wed, Sep 8, 2021 at 3:08 AM Andres Freund <andres@anarazel.de\n> <mailto:andres@anarazel.de>> wrote:\n> >\n> >\n> > > Looking at this profile made me wonder if this was a build without\n> > > optimizations. The\n> pg_atomic_read_u64()/pg_atomic_read_u64_impl() calls\n> > > should\n> > > be inlined. And while perf can reconstruct inlined functions\n> when using\n> > > --call-graph=dwarf, they show up like \"pg_atomic_read_u64\n> (inlined)\" for\n> > > me.\n> > >\n> >\n> > Yeah, for profiling generally I build without optimizations so\n> that I can\n> > see all the functions in the stack, so yeah profile results are\n> without\n> > optimizations build but the performance results are with optimizations\n> > build.\n> \n> I'm afraid that makes the profiles just about meaningless :(.\n> \n> \n> Maybe it can be misleading sometimes, but I feel sometimes it is more\n> informative compared to the optimized build where it makes some function\n> inline, and then it becomes really hard to distinguish which function\n> really has the problem.  But your point is taken and I will run with an\n> optimized build.\n> \n\nIMHO Andres is right optimization may make profiles mostly useless in\nmost cases - it may skew timings for different parts differently, so\nsomething that'd be optimized out may take much more time.\n\nIt may provide valuable insights, but we definitely should not use such\nbinaries for benchmarking and comparisons of the patches.\n\nAs mentioned, I did some benchmarks, and I do see some nice improvements\neven with properly optimized builds -O2.\n\nAttached is a simple script that varies a bunch of parameters (number of\nworkers, number of rows/columns, ...) and then measures duration of a\nsimple query, similar to what you did. I haven't varied the queue size,\nthat might be interesting too.\n\nThe PDF shows a comparison of master and the two patches. For 10k rows\nthere's not much difference, but for 1M and 10M rows there are some nice\nimprovements in the 20-30% range. Of course, it's just a single query in\na simple benchmark.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Wed, 8 Sep 2021 11:58:22 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Wed, Sep 8, 2021 at 3:28 PM Tomas Vondra <tomas.vondra@enterprisedb.com>\nwrote:\n\nOn 9/8/21 9:40 AM, Dilip Kumar wrote:\n>\n> > Maybe it can be misleading sometimes, but I feel sometimes it is more\n> > informative compared to the optimized build where it makes some function\n> > inline, and then it becomes really hard to distinguish which function\n> > really has the problem. But your point is taken and I will run with an\n> > optimized build.\n> >\n>\n> IMHO Andres is right optimization may make profiles mostly useless in\n> most cases - it may skew timings for different parts differently, so\n> something that'd be optimized out may take much more time.\n>\n> It may provide valuable insights, but we definitely should not use such\n> binaries for benchmarking and comparisons of the patches.\n>\n\nYeah, I completely agree that those binaries should not be used for\nbenchmarking and patch comparison and I never used it for that purpose. I\nwas also making the same point that with debug binaries sometimes we get\nsome valuable insight during profiling.\n\n\n\n> As mentioned, I did some benchmarks, and I do see some nice improvements\n> even with properly optimized builds -O2.\n>\n> Attached is a simple script that varies a bunch of parameters (number of\n> workers, number of rows/columns, ...) and then measures duration of a\n> simple query, similar to what you did. I haven't varied the queue size,\n> that might be interesting too.\n>\n> The PDF shows a comparison of master and the two patches. For 10k rows\n> there's not much difference, but for 1M and 10M rows there are some nice\n> improvements in the 20-30% range. Of course, it's just a single query in\n> a simple benchmark.\n>\n\nThanks for the benchmarking.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Wed, Sep 8, 2021 at 3:28 PM Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\nOn 9/8/21 9:40 AM, Dilip Kumar wrote:\n> Maybe it can be misleading sometimes, but I feel sometimes it is more\n> informative compared to the optimized build where it makes some function\n> inline, and then it becomes really hard to distinguish which function\n> really has the problem.  But your point is taken and I will run with an\n> optimized build.\n> \n\nIMHO Andres is right optimization may make profiles mostly useless in\nmost cases - it may skew timings for different parts differently, so\nsomething that'd be optimized out may take much more time.\n\nIt may provide valuable insights, but we definitely should not use such\nbinaries for benchmarking and comparisons of the patches.Yeah, I completely agree that those binaries should not be used for benchmarking and patch comparison and I never used it for that purpose.  I was also making the same point that with debug binaries sometimes we get some valuable insight during profiling. \nAs mentioned, I did some benchmarks, and I do see some nice improvements\neven with properly optimized builds -O2.\n\nAttached is a simple script that varies a bunch of parameters (number of\nworkers, number of rows/columns, ...) and then measures duration of a\nsimple query, similar to what you did. I haven't varied the queue size,\nthat might be interesting too.\n\nThe PDF shows a comparison of master and the two patches. For 10k rows\nthere's not much difference, but for 1M and 10M rows there are some nice\nimprovements in the 20-30% range. Of course, it's just a single query in\na simple benchmark.Thanks for the benchmarking.-- Regards,Dilip KumarEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Wed, 8 Sep 2021 16:41:54 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Wed, Sep 8, 2021 at 4:41 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n\nBased on various suggestions, I have some more experiments with the patch.\n\n1) I have measured the cache misses count and I see a ~20% reduction\nin cache misses with the patch (updating shared memory counter only\nafter we written certain amount of data).\ncommand: perf stat -e\ncycles,instructions,cache-references,cache-misses -p <receiver-pid>\nHead:\n 13,918,480,258 cycles\n 21,082,968,730 instructions # 1.51 insn per\ncycle\n 13,206,426 cache-references\n 12,432,402 cache-misses # 94.139 % of all\ncache refs\n\nPatch:\n 14,119,691,844 cycles\n 29,497,239,984 instructions # 2.09 insn per\ncycle\n 4,245,819 cache-references\n 3,085,047 cache-misses # 72.661 % of all cache refs\n\nI have taken multiple samples with different execution times, and I\ncan see the cache-misses with the patch is 72-74% whereas without the\npatch it is 92-94%. So as expected these results clearly showing we\nare saving a lot by avoiding cache misses.\n\n2) As pointed by Tomas, I have tried different test cases, where this\npatch can regress the performance\n\nCREATE TABLE t (a int, b varchar);\nINSERT INTO t SELECT i, repeat('a', 200) from generate_series(1,200000000) as i;\nset enable_gathermerge=off;\nQuery: select * from t1 where a < 100000 order by a;\n\nPlan:\nSort (cost=1714422.10..1714645.24 rows=89258 width=15)\n -> Gather (cost=1000.00..1707082.55 rows=89258 width=15)\n -> Parallel Seq Scan on t1 (cost=0.00..1706082.55\nrows=22314 width=15)\n Filter: (a < 100000)\n\nSo the idea is, that without a patch we should immediately get the\ntuple to the sort node whereas with a patch there would be some delay\nbefore we send the tuple to the gather node as we are batching. With\nthis also, I did not notice any consistent regression with the patch,\nhowever, with explain analyze I have noticed 2-3 % drop with the\npatch.\n\n3. I tried some other optimizations, pointed by Andres,\na) Separating read-only and read-write data in shm_mq and also moving\nsome fields out of shm_mq\n\nstruct shm_mq (after change)\n{\n/* mostly read-only field*/\n\nPGPROC *mq_receiver;\nPGPROC *mq_sender;\nbool mq_detached;\nslock_t mq_mutex;\n\n/* read-write fields*/\npg_atomic_uint64 mq_bytes_read;\npg_atomic_uint64 mq_bytes_written;\nchar mq_ring[FLEXIBLE_ARRAY_MEMBER];\n};\n\nNote: mq_ring_size and mq_ring_offset moved to shm_mq_handle.\n\nI did not see any extra improvement with this idea.\n\n4. Another thought about changing the \"mq_ring_size\" to a mask\n- I think this could improve something, but currently, \"mq_ring_size\"\nis not the 2's power value so we can not convert this to a mask\ndirectly.\n\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 15 Sep 2021 12:56:25 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Sat, Aug 28, 2021 at 5:04 PM Zhihong Yu <zyu@yugabyte.com> wrote:\n>\n\n>>\n>> * mqh_partial_bytes, mqh_expected_bytes, and mqh_length_word_complete\n>>\n>> + Size mqh_send_pending;\n>> bool mqh_length_word_complete;\n>> bool mqh_counterparty_attached;\n>>\n>> I wonder if mqh_send_pending should be declared after mqh_length_word_complete - this way, the order of fields matches the order of explanation for the fields.\n\nMoved it after mqh_consume_pending and moved comment as well in the\ncorrect order.\n>\n> There was a typo in suggested code above. It should be:\n>\n> + if (force_flush || mqh->mqh_send_pending > (mq->mq_ring_size >> 2))\n\nDone\n\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Thu, 16 Sep 2021 12:55:06 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "\n\nOn 9/8/21 8:05 AM, Dilip Kumar wrote:\n> On Tue, Sep 7, 2021 at 8:41 PM Tomas Vondra \n> <tomas.vondra@enterprisedb.com <mailto:tomas.vondra@enterprisedb.com>> \n> wrote:\n> \n> Hi,\n> \n> The numbers presented in this thread seem very promising - clearly\n> there's significant potential for improvements. I'll run similar\n> benchmarks too, to get a better understanding of this.\n> \n> \n> Thanks for showing interest.\n> \n> \n> Can you share some basic details about the hardware you used?\n> Particularly the CPU model - I guess this might explain some of the\n> results, e.g. if CPU caches are ~1MB, that'd explain why setting\n> tup_queue_size to 1MB improves things, but 4MB is a bit slower.\n> Similarly, number of cores might explain why 4 workers perform better\n> than 8 or 16 workers.\n> \n> \n> I have attached the output of the lscpu.  I think batching the data \n> before updating in the shared memory will win because we are avoiding \n> the frequent cache misses and IMHO the benefit will be more in the \n> machine with more CPU sockets.\n> \n> Now, this is mostly expected, but the consequence is that maybe things\n> like queue size should be tunable/dynamic, not hard-coded?\n> \n> \n> Actually, my intention behind the tuple queue size was to just see the \n> behavior. Do we really have the problem of workers stalling on queue \n> while sending the tuple, the perf report showed some load on WaitLatch \n> on the worker side so I did this experiment.  I saw some benefits but it \n> was not really huge.  I am not sure whether we want to just increase the \n> tuple queue size or make it tunable,  but if we want to support \n> redistribute operators in future sometime then maybe we should make it \n> dynamically growing at runtime, maybe using dsa or dsa + shared files.\n> \n\nThanks. I ran a couple more benchmarks, with different queue sizes \n(16kB, 64kB, 256kB and 1MB) and according to the results the queue size \nreally makes almost no difference. It might make a difference for some \nqueries, but I wouldn't bother tuning this until we have a plausible \nexample - increasing the queue size is not free either.\n\nSo it was worth checking, but I'd just leave it as 64kB for now. We may \nrevisit this later in a separate patch/thread.\n\n> As for the patches, I think the proposed changes are sensible, but I\n> wonder what queries might get slower. For example with the batching\n> (updating the counter only once every 4kB, that pretty much transfers\n> data in larger chunks with higher latency. So what if the query needs\n> only a small chunk, like a LIMIT query? Similarly, this might mean the\n> upper parts of the plan have to wait for the data for longer, and thus\n> can't start some async operation (like send them to a FDW, or something\n> like that). I do admit those are theoretical queries, I haven't tried\n> creating such query.\n> \n> \n> Yeah, I was thinking about such cases, basically, this design can \n> increase the startup cost of the Gather node, I will also try to derive \n> such cases and test them.\n> \n> \n> FWIW I've tried applying both patches at the same time, but there's a\n> conflict in shm_mq_sendv - not a complex one, but I'm not sure what's\n> the correct solution. Can you share a \"combined\" patch?\n> \n> \n> Actually, these both patches are the same, \n> \"v1-0001-Optimize-parallel-tuple-send-shm_mq_send_bytes.patch\" is the \n> cleaner version of the first patch.  For configurable tuple queue size I \n> did not send a patch, because that is I just used for the testing \n> purpose and never intended to to propose anything.  My most of the \n> latest performance data I sent with only \n> \"v1-0001-Optimize-parallel-tuple-send-shm_mq_send_bytes.patch\" and with \n> default tuple queue size.\n> \n> But I am attaching both the patches in case you want to play around.\n> \n\nAh, silly me. I should have noticed the second patch is just a refined \nversion of the first one.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Sat, 18 Sep 2021 15:18:43 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Wed, Sep 8, 2021 at 2:06 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> But I am attaching both the patches in case you want to play around.\n\nI don't really see any reason not to commit 0001. Perhaps some very\nminor grammatical nitpicking is in order here, but apart from that I\ncan't really see anything to criticize with this approach. It seems\nsafe enough, it's not invasive in any way that matters, and we have\nbenchmark results showing that it works well. If someone comes up with\nsomething even better, no harm done, we can always change it again.\n\nObjections?\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 23 Sep 2021 15:31:56 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On 9/23/21 9:31 PM, Robert Haas wrote:\n> On Wed, Sep 8, 2021 at 2:06 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>> But I am attaching both the patches in case you want to play around.\n> \n> I don't really see any reason not to commit 0001. Perhaps some very\n> minor grammatical nitpicking is in order here, but apart from that I\n> can't really see anything to criticize with this approach. It seems\n> safe enough, it's not invasive in any way that matters, and we have\n> benchmark results showing that it works well. If someone comes up with\n> something even better, no harm done, we can always change it again.\n> \n> Objections?\n\nYeah, it seems like a fairly clear win, according to the benchmarks.\n\nI did find some suspicious behavior on the bigger box I have available \n(with 2x xeon e5-2620v3), see the attached spreadsheet. But it seems \npretty weird because the worst affected case is with no parallel workers \n(so the queue changes should affect it). Not sure how to explain it, but \nthe behavior seems consistent.\n\nAnyway, the other machine with a single CPU seems perfectly clean.\n\n\n\nregards\n\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Thu, 23 Sep 2021 22:00:02 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Thu, Sep 23, 2021 at 4:00 PM Tomas Vondra\n<tomas.vondra@enterprisedb.com> wrote:\n> I did find some suspicious behavior on the bigger box I have available\n> (with 2x xeon e5-2620v3), see the attached spreadsheet. But it seems\n> pretty weird because the worst affected case is with no parallel workers\n> (so the queue changes should affect it). Not sure how to explain it, but\n> the behavior seems consistent.\n\nThat is pretty odd. I'm inclined to mostly discount the runs with\n10000 tuples because sending such a tiny number of tuples doesn't\nreally take any significant amount of time, and it seems possible that\nvariations in the runtime of other code due to code movement effects\ncould end up mattering more than the changes to the performance of\nshm_mq. However, the results with a million tuples seem like they're\nprobably delivering statistically significant results ... and I guess\nmaybe what's happening is that the patch hurts when the tuples are too\nbig relative to the queue size.\n\nI guess your columns are an md5 value each, which is 32 bytes +\noverhead, so a 20-columns tuple is ~1kB. Since Dilip's patch flushes\nthe value to shared memory when more than a quarter of the queue has\nbeen filled, that probably means we flush every 4-5 tuples. I wonder\nif that means we need a smaller threshold, like 1/8 of the queue size?\nOr maybe the behavior should be adaptive somehow, depending on whether\nthe receiver ends up waiting for data? Or ... perhaps only small\ntuples are worth batching, so that the threshold for posting to shared\nmemory should be a constant rather than a fraction of the queue size?\nI guess we need to know why we see the time spike up in those cases,\nif we want to improve them.\n\n--\nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 23 Sep 2021 16:31:09 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "\n\nOn 9/23/21 10:31 PM, Robert Haas wrote:\n> On Thu, Sep 23, 2021 at 4:00 PM Tomas Vondra\n> <tomas.vondra@enterprisedb.com> wrote:\n>> I did find some suspicious behavior on the bigger box I have available\n>> (with 2x xeon e5-2620v3), see the attached spreadsheet. But it seems\n>> pretty weird because the worst affected case is with no parallel workers\n>> (so the queue changes should affect it). Not sure how to explain it, but\n>> the behavior seems consistent.\n> \n> That is pretty odd. I'm inclined to mostly discount the runs with\n> 10000 tuples because sending such a tiny number of tuples doesn't\n> really take any significant amount of time, and it seems possible that\n> variations in the runtime of other code due to code movement effects\n> could end up mattering more than the changes to the performance of\n> shm_mq. However, the results with a million tuples seem like they're\n> probably delivering statistically significant results ... and I guess\n> maybe what's happening is that the patch hurts when the tuples are too\n> big relative to the queue size.\n> \n\nAgreed on 10k rows being too small, we can ignore that. And yes, binary \nlayout might make a difference, of course. My rule of thumb is 5% (in \nboth directions) is about the difference that might make, and most \nresults are within that range.\n\n> I guess your columns are an md5 value each, which is 32 bytes +\n> overhead, so a 20-columns tuple is ~1kB. Since Dilip's patch flushes\n> the value to shared memory when more than a quarter of the queue has\n> been filled, that probably means we flush every 4-5 tuples. I wonder\n> if that means we need a smaller threshold, like 1/8 of the queue size?\n> Or maybe the behavior should be adaptive somehow, depending on whether\n> the receiver ends up waiting for data? Or ... perhaps only small\n> tuples are worth batching, so that the threshold for posting to shared\n> memory should be a constant rather than a fraction of the queue size?\n> I guess we need to know why we see the time spike up in those cases,\n> if we want to improve them.\n> \n\nNot sure about this, because\n\n(a) That should affect both CPUs, I think, but i5-2500k does not have \nany such issue.\n\n(b) One thing I haven't mentioned is I tried with larger queue sizes too \n(that's the 16kB, 64kB, 256kB and 1MB in columns). Although it's true \nlarger queue improve the situation a bit.\n\n(c) This can't explain the slowdown for cases without any Gather nodes \n(and it's ~17%, so unlikely due to binary layout).\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 23 Sep 2021 23:36:34 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Thu, Sep 23, 2021 at 5:36 PM Tomas Vondra\n<tomas.vondra@enterprisedb.com> wrote:\n> (c) This can't explain the slowdown for cases without any Gather nodes\n> (and it's ~17%, so unlikely due to binary layout).\n\nYeah, but none of the modified code would even execute in those cases,\nso it's either binary layout, something wrong in your test\nenvironment, or gremlins.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 23 Sep 2021 19:43:00 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Fri, Sep 24, 2021 at 2:01 AM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> On Thu, Sep 23, 2021 at 4:00 PM Tomas Vondra\n> <tomas.vondra@enterprisedb.com> wrote:\n> > I did find some suspicious behavior on the bigger box I have available\n> > (with 2x xeon e5-2620v3), see the attached spreadsheet. But it seems\n> > pretty weird because the worst affected case is with no parallel workers\n> > (so the queue changes should affect it). Not sure how to explain it, but\n> > the behavior seems consistent.\n>\n> That is pretty odd. I'm inclined to mostly discount the runs with\n> 10000 tuples because sending such a tiny number of tuples doesn't\n> really take any significant amount of time, and it seems possible that\n> variations in the runtime of other code due to code movement effects\n> could end up mattering more than the changes to the performance of\n> shm_mq. However, the results with a million tuples seem like they're\n> probably delivering statistically significant results ... and I guess\n> maybe what's happening is that the patch hurts when the tuples are too\n> big relative to the queue size.\n\nI am looking at the \"query-results.ods\" file shared by Tomas, with a\nmillion tuple I do not really see where the patch hurts? because I am\nseeing in most of the cases the time taken by the patch is 60-80%\ncompared to the head. And the worst case with a million tuple is\n100.32% are are we pointing to that 0.32% or there is something else\nthat I am missing here.\n\n>\n> I guess your columns are an md5 value each, which is 32 bytes +\n> overhead, so a 20-columns tuple is ~1kB. Since Dilip's patch flushes\n> the value to shared memory when more than a quarter of the queue has\n> been filled, that probably means we flush every 4-5 tuples. I wonder\n> if that means we need a smaller threshold, like 1/8 of the queue size?\n> Or maybe the behavior should be adaptive somehow, depending on whether\n> the receiver ends up waiting for data? Or ... perhaps only small\n> tuples are worth batching, so that the threshold for posting to shared\n> memory should be a constant rather than a fraction of the queue size?\n> I guess we need to know why we see the time spike up in those cases,\n> if we want to improve them.\n\nI will test with the larger tuple sizes and will see the behavior with\ndifferent thresholds. With 250 bytes tuple size, I have tested with\ndifferent thresholds and it appeared that 1/4 of the queue size works\nbest. But I will do more detailed testing and share the results.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 24 Sep 2021 10:49:01 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Fri, Sep 24, 2021 at 1:30 AM Tomas Vondra\n<tomas.vondra@enterprisedb.com> wrote:\n>\n> On 9/23/21 9:31 PM, Robert Haas wrote:\n> > On Wed, Sep 8, 2021 at 2:06 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >> But I am attaching both the patches in case you want to play around.\n> >\n> > I don't really see any reason not to commit 0001. Perhaps some very\n> > minor grammatical nitpicking is in order here, but apart from that I\n> > can't really see anything to criticize with this approach. It seems\n> > safe enough, it's not invasive in any way that matters, and we have\n> > benchmark results showing that it works well. If someone comes up with\n> > something even better, no harm done, we can always change it again.\n> >\n> > Objections?\n>\n> Yeah, it seems like a fairly clear win, according to the benchmarks.\n>\n> I did find some suspicious behavior on the bigger box I have available\n> (with 2x xeon e5-2620v3), see the attached spreadsheet. But it seems\n> pretty weird because the worst affected case is with no parallel workers\n> (so the queue changes should affect it). Not sure how to explain it, but\n> the behavior seems consistent.\n>\n> Anyway, the other machine with a single CPU seems perfectly clean.\n\nTomas, can you share your test script, I would like to repeat the same\ntest in my environment and with different batching sizes.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 24 Sep 2021 13:20:35 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Fri, Sep 24, 2021 at 3:50 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> Tomas, can you share your test script, I would like to repeat the same\n> test in my environment and with different batching sizes.\n\nI think it's probably the run.sh file attached to\nhttp://postgr.es/m/d76a759d-9240-94f5-399e-ae244e5f0285@enterprisedb.com\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 24 Sep 2021 13:08:28 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Fri, Sep 24, 2021 at 1:19 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> I am looking at the \"query-results.ods\" file shared by Tomas, with a\n> million tuple I do not really see where the patch hurts? because I am\n> seeing in most of the cases the time taken by the patch is 60-80%\n> compared to the head. And the worst case with a million tuple is\n> 100.32% are are we pointing to that 0.32% or there is something else\n> that I am missing here.\n\nThe spreadsheet has two tabs. Flip to \"xeon e5-2620v3\" and scroll all\nthe way down.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 24 Sep 2021 13:10:55 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On 9/24/21 1:43 AM, Robert Haas wrote:\n> On Thu, Sep 23, 2021 at 5:36 PM Tomas Vondra\n> <tomas.vondra@enterprisedb.com> wrote:\n>> (c) This can't explain the slowdown for cases without any Gather nodes\n>> (and it's ~17%, so unlikely due to binary layout).\n> \n> Yeah, but none of the modified code would even execute in those cases,\n> so it's either binary layout, something wrong in your test\n> environment, or gremlins.\n> \n\nI'm not going to the office all that often these days, but I think I'm \nsure I'd notice a bunch of gremlins running around ... so it's probably \nthe binary layout thing. But still, strange.\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Fri, 24 Sep 2021 22:44:32 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On 9/24/21 7:08 PM, Robert Haas wrote:\n> On Fri, Sep 24, 2021 at 3:50 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>> Tomas, can you share your test script, I would like to repeat the same\n>> test in my environment and with different batching sizes.\n> \n> I think it's probably the run.sh file attached to\n> http://postgr.es/m/d76a759d-9240-94f5-399e-ae244e5f0285@enterprisedb.com\n> \n\nYep. I've used a slightly modified version, which also varies the queue \nsize, but we can ignore that and the rest of the script is the same.\n\nAs for the config, I've used only slightly tuned postgresql.conf, with \nshared_buffers set to 1GB, and increased worker limits.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Fri, 24 Sep 2021 22:48:37 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Sat, Sep 25, 2021 at 2:18 AM Tomas Vondra\n<tomas.vondra@enterprisedb.com> wrote:\n>\n> On 9/24/21 7:08 PM, Robert Haas wrote:\n> > On Fri, Sep 24, 2021 at 3:50 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >> Tomas, can you share your test script, I would like to repeat the same\n> >> test in my environment and with different batching sizes.\n\nFor now I have tested for 1M and 10M rows, shared buffers=16GM, for\nnow tested with default batching 1/4th of the queue size and I can see\nthe performance gain is huge. Time taken with the patch is in the\nrange of 37-90% compared to the master. Please refer to the attached\nfile for more detailed results. I could not see any regression that\nTomas saw, still I am planning to repeat it with different batch\nsizes.\n\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Sun, 26 Sep 2021 11:21:52 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Sun, Sep 26, 2021 at 11:21 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Sat, Sep 25, 2021 at 2:18 AM Tomas Vondra\n> <tomas.vondra@enterprisedb.com> wrote:\n> >\n> > On 9/24/21 7:08 PM, Robert Haas wrote:\n> > > On Fri, Sep 24, 2021 at 3:50 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> > >> Tomas, can you share your test script, I would like to repeat the same\n> > >> test in my environment and with different batching sizes.\n>\n> For now I have tested for 1M and 10M rows, shared buffers=16GM, for\n> now tested with default batching 1/4th of the queue size and I can see\n> the performance gain is huge. Time taken with the patch is in the\n> range of 37-90% compared to the master. Please refer to the attached\n> file for more detailed results. I could not see any regression that\n> Tomas saw, still I am planning to repeat it with different batch\n> sizes.\n\nI have done testing with different batch sizes, 16k (which is the same\nas 1/4 of the queue size with 64k queue size) , 8k, 4k, 2k.\n\nIn the attached sheet I have done a comparison of\n1. head vs patch (1/4 queue size) = execution time reduced to 37% to\n90% this is the same as the old sheet.\n2. patch (1/4 queue size) vs patch(8k batch) = both are same, but 8k\nbatch size is slow in some cases.\n3. patch (1/4 queue size) vs patch(4k batch) = both are same, but 4k\nbatch size is slow in some cases (even slower than 8k batch size).\n4. patch (1/4 queue size) vs patch(2k batch) = 2k batch size is\nsignificantly slow.\n\nWith these results, 1/4 of the queue size seems to be the winner and I\nthink we might go for that value, however someone might think that 4k\nbatch size is optimal because it is just marginally slow and with that\nwe will have to worry less about increasing the latency in some worse\ncase.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Mon, 27 Sep 2021 10:52:29 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Mon, Sep 27, 2021 at 1:22 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> I have done testing with different batch sizes, 16k (which is the same\n> as 1/4 of the queue size with 64k queue size) , 8k, 4k, 2k.\n>\n> In the attached sheet I have done a comparison of\n> 1. head vs patch (1/4 queue size) = execution time reduced to 37% to\n> 90% this is the same as the old sheet.\n> 2. patch (1/4 queue size) vs patch(8k batch) = both are same, but 8k\n> batch size is slow in some cases.\n> 3. patch (1/4 queue size) vs patch(4k batch) = both are same, but 4k\n> batch size is slow in some cases (even slower than 8k batch size).\n> 4. patch (1/4 queue size) vs patch(2k batch) = 2k batch size is\n> significantly slow.\n\nGenerally these results seem to show that a larger batch size is\nbetter than a smaller one, but we know that's not true everywhere and\nunder all circumstances, because some of Tomas's numbers are worse\nthan the unpatched cases. And I think we don't really understand the\nreason for those results. Now it could be that there's no really good\nreason for those results, and it's just something weird or not very\ngenerally interesting.\n\nOn the other hand, while it's easy to see that batching can be a win\nif it avoids contention, it also seems easy to imagine that it can be\na loss. By postponing the update to shared memory, we are essentially\ngambling. If nobody would have read the updated value anyway, we win,\nbecause we avoided doing work that wasn't really needed by\nconsolidating multiple updates of shared memory down to one. However,\nimagine the scenario where someone reads a value that is small enough\nthat they have to block, because they think there's no more data\navailable. If there really is more data available and we just didn't\nupdate shared memory, then we lose.\n\nHere, the wins are going to be much smaller than the losses. Cache\nline contention isn't cheap, but it's a lot cheaper than actually\nhaving a process go to sleep and having to wake it up again. So\nessentially the patch is betting that the winning scenario is much\nmore common than the losing scenario - the occasional big losses when\nthe reader sleeps unnecessarily will be more than counterbalanced by\nthe small wins every time we skip an update to shared memory without\ncausing that to happen.\n\nAnd most of the time, that's probably a good bet. But, if you do\nsomehow hit the losing case repeatedly, then you could see a\nsignificant regression. And that might explain Tomas's results.\nPerhaps for some reason they just happen to hit that case over and\nover again. If that's true, it would be useful to know why it happens\nin that case and not others, because then maybe we could avoid the\nproblem somehow. However, I'm not sure how to figure that out, and I'm\nnot even entirely sure it's important to figure it out.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 27 Sep 2021 13:22:31 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Mon, Sep 27, 2021 at 10:52 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n>\n> And most of the time, that's probably a good bet. But, if you do\n> somehow hit the losing case repeatedly, then you could see a\n> significant regression. And that might explain Tomas's results.\n> Perhaps for some reason they just happen to hit that case over and\n> over again. If that's true, it would be useful to know why it happens\n> in that case and not others, because then maybe we could avoid the\n> problem somehow. However, I'm not sure how to figure that out, and I'm\n> not even entirely sure it's important to figure it out.\n>\n\nYeah, if it is losing in some cases then it is definitely good to know\nthe reason, I was just looking into the performance numbers shared by\nTomas in query-results, I can see the worst case is\nwith 10000000 rows, 10 columns and 4 threads and queue size 64k.\nBasically, if we see the execution time with head is ~804ms whereas\nwith patch it is ~1277 ms. But then I just tried to notice the\npattern with different queue size so number are like below,\n\n 16k 64k 256k 1024k\nHead 1232.779 804.24 1134.723 901.257\nPatch 1371.493 1277.705 862.598 783.481\n\nSo what I have noticed is that in most of the cases on head as well as\nwith the patch, increasing the queue size make it faster, but with\nhead suddenly for this particular combination of rows, column and\nthread the execution time is very low for 64k queue size and then\nagain the execution time increased with 256k queue size and then\nfollow the pattern. So this particular dip in the execution time on\nthe head looks a bit suspicious to me. I mean how could we justify\nthis sudden big dip in execution time w.r.t the other pattern.\n\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 28 Sep 2021 12:18:46 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Tue, Sep 28, 2021 at 12:19 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Mon, Sep 27, 2021 at 10:52 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> >\n> > And most of the time, that's probably a good bet. But, if you do\n> > somehow hit the losing case repeatedly, then you could see a\n> > significant regression. And that might explain Tomas's results.\n> > Perhaps for some reason they just happen to hit that case over and\n> > over again. If that's true, it would be useful to know why it happens\n> > in that case and not others, because then maybe we could avoid the\n> > problem somehow. However, I'm not sure how to figure that out, and I'm\n> > not even entirely sure it's important to figure it out.\n> >\n>\n> Yeah, if it is losing in some cases then it is definitely good to know\n> the reason, I was just looking into the performance numbers shared by\n> Tomas in query-results, I can see the worst case is\n> with 10000000 rows, 10 columns and 4 threads and queue size 64k.\n> Basically, if we see the execution time with head is ~804ms whereas\n> with patch it is ~1277 ms. But then I just tried to notice the\n> pattern with different queue size so number are like below,\n>\n> 16k 64k 256k 1024k\n> Head 1232.779 804.24 1134.723 901.257\n> Patch 1371.493 1277.705 862.598 783.481\n>\n> So what I have noticed is that in most of the cases on head as well as\n> with the patch, increasing the queue size make it faster, but with\n> head suddenly for this particular combination of rows, column and\n> thread the execution time is very low for 64k queue size and then\n> again the execution time increased with 256k queue size and then\n> follow the pattern. So this particular dip in the execution time on\n> the head looks a bit suspicious to me.\n>\n\nI concur with your observation. Isn't it possible to repeat the same\ntest in the same environment to verify these results?\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 28 Sep 2021 16:23:21 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On 9/28/21 12:53 PM, Amit Kapila wrote:\n> On Tue, Sep 28, 2021 at 12:19 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>>\n>> On Mon, Sep 27, 2021 at 10:52 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>>\n>>>\n>>> And most of the time, that's probably a good bet. But, if you do\n>>> somehow hit the losing case repeatedly, then you could see a\n>>> significant regression. And that might explain Tomas's results.\n>>> Perhaps for some reason they just happen to hit that case over and\n>>> over again. If that's true, it would be useful to know why it happens\n>>> in that case and not others, because then maybe we could avoid the\n>>> problem somehow. However, I'm not sure how to figure that out, and I'm\n>>> not even entirely sure it's important to figure it out.\n>>>\n>>\n>> Yeah, if it is losing in some cases then it is definitely good to know\n>> the reason, I was just looking into the performance numbers shared by\n>> Tomas in query-results, I can see the worst case is\n>> with 10000000 rows, 10 columns and 4 threads and queue size 64k.\n>> Basically, if we see the execution time with head is ~804ms whereas\n>> with patch it is ~1277 ms. But then I just tried to notice the\n>> pattern with different queue size so number are like below,\n>>\n>> 16k 64k 256k 1024k\n>> Head 1232.779 804.24 1134.723 901.257\n>> Patch 1371.493 1277.705 862.598 783.481\n>>\n>> So what I have noticed is that in most of the cases on head as well as\n>> with the patch, increasing the queue size make it faster, but with\n>> head suddenly for this particular combination of rows, column and\n>> thread the execution time is very low for 64k queue size and then\n>> again the execution time increased with 256k queue size and then\n>> follow the pattern. So this particular dip in the execution time on\n>> the head looks a bit suspicious to me.\n>>\n> \n> I concur with your observation. Isn't it possible to repeat the same\n> test in the same environment to verify these results?\n> \n\nI can repeat any tests we need on that machine, of course.\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 28 Sep 2021 13:51:35 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Tue, Sep 28, 2021 at 5:21 PM Tomas Vondra\n<tomas.vondra@enterprisedb.com> wrote:\n> >> Yeah, if it is losing in some cases then it is definitely good to know\n> >> the reason, I was just looking into the performance numbers shared by\n> >> Tomas in query-results, I can see the worst case is\n> >> with 10000000 rows, 10 columns and 4 threads and queue size 64k.\n> >> Basically, if we see the execution time with head is ~804ms whereas\n> >> with patch it is ~1277 ms. But then I just tried to notice the\n> >> pattern with different queue size so number are like below,\n> >>\n> >> 16k 64k 256k 1024k\n> >> Head 1232.779 804.24 1134.723 901.257\n> >> Patch 1371.493 1277.705 862.598 783.481\n> >>\n> >> So what I have noticed is that in most of the cases on head as well as\n> >> with the patch, increasing the queue size make it faster, but with\n> >> head suddenly for this particular combination of rows, column and\n> >> thread the execution time is very low for 64k queue size and then\n> >> again the execution time increased with 256k queue size and then\n> >> follow the pattern. So this particular dip in the execution time on\n> >> the head looks a bit suspicious to me.\n> >>\n> >\n> > I concur with your observation. Isn't it possible to repeat the same\n> > test in the same environment to verify these results?\n> >\n>\n> I can repeat any tests we need on that machine, of course.\n>\n\nI think that would be great, can we just test this specific target\nwhere we are seeing a huge dip with the patch, e.g.\nwith 10000000 rows, 10 columns and 4 threads, and queue size 64k. In\nmy performance machine, I tried to run this test multiple times but on\nthe head, it is taking ~2000 ms whereas with the patch it is ~1500 ms,\nso I am not able to reproduce this. So it would be good if you can\nrun only this specific test and repeat it a couple of times on your\nperformance machine.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 28 Sep 2021 17:30:42 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Tue, Sep 28, 2021 at 2:49 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> 16k 64k 256k 1024k\n> Head 1232.779 804.24 1134.723 901.257\n> Patch 1371.493 1277.705 862.598 783.481\n>\n> So what I have noticed is that in most of the cases on head as well as\n> with the patch, increasing the queue size make it faster, but with\n> head suddenly for this particular combination of rows, column and\n> thread the execution time is very low for 64k queue size and then\n> again the execution time increased with 256k queue size and then\n> follow the pattern. So this particular dip in the execution time on\n> the head looks a bit suspicious to me. I mean how could we justify\n> this sudden big dip in execution time w.r.t the other pattern.\n\nOh, interesting. So there's not really a performance regression here\nso much as that one particular case ran exceptionally fast on the\nunpatched code.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 29 Sep 2021 12:39:50 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On 9/28/21 14:00, Dilip Kumar wrote:\n>\n> I think that would be great, can we just test this specific target\n> where we are seeing a huge dip with the patch, e.g.\n> with 10000000 rows, 10 columns and 4 threads, and queue size 64k. In\n> my performance machine, I tried to run this test multiple times but on\n> the head, it is taking ~2000 ms whereas with the patch it is ~1500 ms,\n> so I am not able to reproduce this. So it would be good if you can\n> run only this specific test and repeat it a couple of times on your\n> performance machine.\n> \n\nI ran the benchmark again, with 10 runs instead of 5, the results and \nscripts are attached. It seems the worst case got much better and is now \nin line with the rest of the results, so it probably was a coincidence.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Tue, 12 Oct 2021 15:10:51 +0200", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Tue, Oct 12, 2021 at 6:41 PM Tomas Vondra\n<tomas.vondra@enterprisedb.com> wrote:\n>\n> On 9/28/21 14:00, Dilip Kumar wrote:\n> >\n> > I think that would be great, can we just test this specific target\n> > where we are seeing a huge dip with the patch, e.g.\n> > with 10000000 rows, 10 columns and 4 threads, and queue size 64k. In\n> > my performance machine, I tried to run this test multiple times but on\n> > the head, it is taking ~2000 ms whereas with the patch it is ~1500 ms,\n> > so I am not able to reproduce this. So it would be good if you can\n> > run only this specific test and repeat it a couple of times on your\n> > performance machine.\n> >\n>\n> I ran the benchmark again, with 10 runs instead of 5, the results and\n> scripts are attached. It seems the worst case got much better and is now\n> in line with the rest of the results, so it probably was a coincidence.\n\nThanks, yeah now it looks in line with other results.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 12 Oct 2021 19:43:44 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Tue, Oct 12, 2021 at 10:14 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> Thanks, yeah now it looks in line with other results.\n\nSince it seems there are no remaining concerns here, and we have\nbenchmarking results showing that the patch helps, I have committed\nthe patch.\n\nI wonder whether the new code in shm_mq_send_bytes() should guard\nagainst calling shm_mq_inc_bytes_written() with a second argument of\n0, or alternatively whether shm_mq_inc_bytes_written() should have an\ninternal defense against that. It might save some writes to shared\nmemory, but it would also add a branch, which isn't free, either.\n\nI also think that, as a followup action item, we need to reassess\nparallel_tuple_cost.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 14 Oct 2021 16:18:29 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Fri, Oct 15, 2021 at 1:48 AM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> On Tue, Oct 12, 2021 at 10:14 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> > Thanks, yeah now it looks in line with other results.\n>\n> Since it seems there are no remaining concerns here, and we have\n> benchmarking results showing that the patch helps, I have committed\n> the patch.\n>\n\nCan we mark the corresponding CF entry [1] as committed?\n\n[1] - https://commitfest.postgresql.org/35/3304/\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 26 Oct 2021 14:31:25 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Gather performance analysis" }, { "msg_contents": "On Tue, Oct 26, 2021 at 2:31 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Fri, Oct 15, 2021 at 1:48 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> >\n> > On Tue, Oct 12, 2021 at 10:14 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> > > Thanks, yeah now it looks in line with other results.\n> >\n> > Since it seems there are no remaining concerns here, and we have\n> > benchmarking results showing that the patch helps, I have committed\n> > the patch.\n> >\n>\n> Can we mark the corresponding CF entry [1] as committed?\n>\n> [1] - https://commitfest.postgresql.org/35/3304/\n\nDone!\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 26 Oct 2021 14:33:14 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Gather performance analysis" } ]
[ { "msg_contents": "Hi Everyone,\n\nI've ran into an issue where the OpenSSL API function \"ssl_get_fd\" fails, due to the underlying BIO object created by Postgres is not being flagged properly.\n\nPrevious to OpenSSL version 1.1.0, the BIO methods object would be copied directly from the existing socket type and then its read\\write functions would be replaced.\nWith 1.1.0 and up, the object is created from scratch and then all its methods are initialized to be the ones of the socket type, except read/write which are custom.\nIn this newer way, a new type is given to it by calling \"BIO_get_new_index\", but the related type flags aren't added.\n\nFor more information please see: https://www.openssl.org/docs/man1.1.0/man3/BIO_get_new_index.html\nIn this case, the type should have both BIO_TYPE_SOURCE_SINK and BIO_TYPE_DESCRIPTOR.\n\nThe proposed patch will add these flags to the BIO type on creation. I have compiled it with OpenSSL, enabled encryption and verified that basic queries work fine.\n\nI don't believe this affects Postgres, since the code has been this way for 5 years. I ran into it because I'm writing auditing code that hooks on Postgres calls. I've already found a workaround by adding these flags myself with an additional hook, but thought it would be worth bringing up here and see if you think it's worth patching.\n\nRegards,\nItamar Gafni\nImperva\n-------------------------------------------\nNOTICE:\nThis email and all attachments are confidential, may be proprietary, and may be privileged or otherwise protected from disclosure. They are intended solely for the individual or entity to whom the email is addressed. However, mistakes sometimes happen in addressing emails. If you believe that you are not an intended recipient, please stop reading immediately. Do not copy, forward, or rely on the contents in any way. Notify the sender and/or Imperva, Inc. by telephone at +1 (650) 832-6006 and then delete or destroy any copy of this email and its attachments. The sender reserves and asserts all rights to confidentiality, as well as any privileges that may apply. Any disclosure, copying, distribution or action taken or omitted to be taken by an unintended recipient in reliance on this message is prohibited and may be unlawful.\nPlease consider the environment before printing this email.", "msg_date": "Fri, 6 Aug 2021 10:16:07 +0000", "msg_from": "Itamar Gafni <itamar.gafni@imperva.com>", "msg_from_op": true, "msg_subject": "[PATCH] OpenSSL: Mark underlying BIO with the appropriate type flags" }, { "msg_contents": "> On 6 Aug 2021, at 12:16, Itamar Gafni <itamar.gafni@imperva.com> wrote:\n\n> Previous to OpenSSL version 1.1.0, the BIO methods object would be copied directly from the existing socket type and then its read\\write functions would be replaced.\n> With 1.1.0 and up, the object is created from scratch and then all its methods are initialized to be the ones of the socket type, except read/write which are custom.\n> In this newer way, a new type is given to it by calling “BIO_get_new_index”, but the related type flags aren’t added.\n\nAccording to the documentation (I haven't tested it yet but will) I think you\nare right that the type should be set with the appropriate BIO_TYPE_ flags.\n\nFor OpenSSL 1.0.1 and 1.0.2, wouldn't we need to set the .type with a randomly\nchosen index anded with BIO_TYPE_DESCRIPTOR and BIO_TYPE_SOURCE_SINK as well?\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Mon, 9 Aug 2021 17:35:59 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: [PATCH] OpenSSL: Mark underlying BIO with the appropriate type\n flags" }, { "msg_contents": "Not sure what is the expected use with previous versions. It used to be that the BIO_s_socket() would return a non-const pointer, so the original socket methods object could be edited.\r\nCopying it means there are two BIO_METHOD objects with the same type (ortig socket and its copy) but it's unclear if that's an issue.\r\n\r\nItamar Gafni\r\nImperva\r\n\r\n-----Original Message-----\r\nFrom: Daniel Gustafsson <daniel@yesql.se>\r\nSent: Monday, 9 August 2021 18:36\r\nTo: Itamar Gafni <itamar.gafni@imperva.com>\r\nCc: pgsql-hackers@lists.postgresql.org\r\nSubject: Re: [PATCH] OpenSSL: Mark underlying BIO with the appropriate type flags\r\n\r\nCAUTION: This message was sent from outside the company. Do not click links or open attachments unless you recognize the sender and know the content is safe.\r\n\r\n\r\n> On 6 Aug 2021, at 12:16, Itamar Gafni <itamar.gafni@imperva.com> wrote:\r\n\r\n> Previous to OpenSSL version 1.1.0, the BIO methods object would be copied directly from the existing socket type and then its read\\write functions would be replaced.\r\n> With 1.1.0 and up, the object is created from scratch and then all its methods are initialized to be the ones of the socket type, except read/write which are custom.\r\n> In this newer way, a new type is given to it by calling “BIO_get_new_index”, but the related type flags aren’t added.\r\n\r\nAccording to the documentation (I haven't tested it yet but will) I think you are right that the type should be set with the appropriate BIO_TYPE_ flags.\r\n\r\nFor OpenSSL 1.0.1 and 1.0.2, wouldn't we need to set the .type with a randomly chosen index anded with BIO_TYPE_DESCRIPTOR and BIO_TYPE_SOURCE_SINK as well?\r\n\r\n--\r\nDaniel Gustafsson https://vmware.com/\r\n\r\n-------------------------------------------\r\nNOTICE:\r\nThis email and all attachments are confidential, may be proprietary, and may be privileged or otherwise protected from disclosure. They are intended solely for the individual or entity to whom the email is addressed. However, mistakes sometimes happen in addressing emails. If you believe that you are not an intended recipient, please stop reading immediately. Do not copy, forward, or rely on the contents in any way. Notify the sender and/or Imperva, Inc. by telephone at +1 (650) 832-6006 and then delete or destroy any copy of this email and its attachments. The sender reserves and asserts all rights to confidentiality, as well as any privileges that may apply. Any disclosure, copying, distribution or action taken or omitted to be taken by an unintended recipient in reliance on this message is prohibited and may be unlawful.\r\nPlease consider the environment before printing this email.\r\n", "msg_date": "Thu, 12 Aug 2021 10:00:24 +0000", "msg_from": "Itamar Gafni <itamar.gafni@imperva.com>", "msg_from_op": true, "msg_subject": "RE: [PATCH] OpenSSL: Mark underlying BIO with the appropriate type\n flags" }, { "msg_contents": "> On 12 Aug 2021, at 12:00, Itamar Gafni <itamar.gafni@imperva.com> wrote:\n\n> Copying it means there are two BIO_METHOD objects with the same type (ortig\n> socket and its copy) but it's unclear if that's an issue.\n\n\nReading code there doesn't seem to be a concensus really, Apple is doing it in\nthe Swift TLS code but otheres aren't. Considering there's been no complaints\non this and OpenSSL < 1.1.0 is EOL I say we leave it for now.\n\nBarring objections I will go ahead with your proposed patch on HEAD and\nbackpatch it all the way, once I've done more testing on it.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Thu, 12 Aug 2021 15:32:27 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: [PATCH] OpenSSL: Mark underlying BIO with the appropriate type\n flags" }, { "msg_contents": "> On 12 Aug 2021, at 15:32, Daniel Gustafsson <daniel@yesql.se> wrote:\n\n> Barring objections I will go ahead with your proposed patch on HEAD and\n> backpatch it all the way, once I've done more testing on it.\n\nI’ve tested this with old and new OpenSSL versions, and have now applied it\nbackpatched to 9.6 as it’s been wrong for a long time. Thanks!\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Tue, 17 Aug 2021 14:43:08 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: [PATCH] OpenSSL: Mark underlying BIO with the appropriate type\n flags" } ]
[ { "msg_contents": "Hi\n\nCommit 6bf0bc842 replaced float.c's CHECKFLOATVAL() macro with static inline subroutines, \nbut the fix introduced a performance regression as Tom Lane pointed out and fixed at 607f8ce74.\n\nFound obsolete CHECKFLOATVAL usage in contrib/btree_gist, and tried to fix it according to 607f8ce74.\nThe attached patch has been testified in master. All tap tests passed.\n\nRegards,\nTang", "msg_date": "Fri, 6 Aug 2021 14:14:21 +0000", "msg_from": "\"tanghy.fnst@fujitsu.com\" <tanghy.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "[PATCH]Remove obsolete macro CHECKFLOATVAL in btree_gist" }, { "msg_contents": "On Friday, August 6, 2021 11:14 PM, tanghy.fnst@fujitsu.com <tanghy.fnst@fujitsu.com> wrote:\n>Commit 6bf0bc842 replaced float.c's CHECKFLOATVAL() macro with static inline subroutines, \n>but the fix introduced a performance regression as Tom Lane pointed out and fixed at 607f8ce74.\n>\n>Found obsolete CHECKFLOATVAL usage in contrib/btree_gist, and tried to fix it according to 607f8ce74.\n\nAdded above patch in commit fest:\nhttps://commitfest.postgresql.org/34/3287/\n\nRegards,\nTang\n\n\n", "msg_date": "Tue, 17 Aug 2021 11:08:59 +0000", "msg_from": "\"tanghy.fnst@fujitsu.com\" <tanghy.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [PATCH]Remove obsolete macro CHECKFLOATVAL in btree_gist" }, { "msg_contents": "On Tue, Aug 17, 2021 at 11:08:59AM +0000, tanghy.fnst@fujitsu.com wrote:\n> On Friday, August 6, 2021 11:14 PM, tanghy.fnst@fujitsu.com <tanghy.fnst@fujitsu.com> wrote:\n>> Commit 6bf0bc842 replaced float.c's CHECKFLOATVAL() macro with static inline subroutines, \n>> but the fix introduced a performance regression as Tom Lane pointed out and fixed at 607f8ce74.\n>>\n>> Found obsolete CHECKFLOATVAL usage in contrib/btree_gist, and tried to fix it according to 607f8ce74.\n> \n> Added above patch in commit fest:\n> https://commitfest.postgresql.org/34/3287/\n\nYes, that does not seem wise on performance grounds. The case of\n!zero_is_valid is never reached, so it seems like this code was just a\ncopy-paste from the float code in the backend. Your patch looks right\nto me.\n--\nMichael", "msg_date": "Wed, 18 Aug 2021 10:04:04 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [PATCH]Remove obsolete macro CHECKFLOATVAL in btree_gist" }, { "msg_contents": "On Wed, Aug 18, 2021 at 10:04:04AM +0900, Michael Paquier wrote:\n> Yes, that does not seem wise on performance grounds. The case of\n> !zero_is_valid is never reached, so it seems like this code was just a\n> copy-paste from the float code in the backend. Your patch looks right\n> to me.\n\nApplied.\n--\nMichael", "msg_date": "Thu, 19 Aug 2021 12:28:07 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [PATCH]Remove obsolete macro CHECKFLOATVAL in btree_gist" }, { "msg_contents": "On Thursday, August 19, 2021 12:28 PM, Michael Paquier <michael@paquier.xyz> wrote\n>On Wed, Aug 18, 2021 at 10:04:04AM +0900, Michael Paquier wrote:\n>> Yes, that does not seem wise on performance grounds. The case of\n>> !zero_is_valid is never reached, so it seems like this code was just a\n>> copy-paste from the float code in the backend. Your patch looks right\n>> to me.\n>\n>Applied.\n\nThanks for you check and commit, I've changed the patch's commit fest status to 'committed'.\nhttps://commitfest.postgresql.org/34/3287/\n\nRegards,\nTang\n\n\n", "msg_date": "Thu, 19 Aug 2021 05:10:07 +0000", "msg_from": "\"tanghy.fnst@fujitsu.com\" <tanghy.fnst@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: [PATCH]Remove obsolete macro CHECKFLOATVAL in btree_gist" } ]
[ { "msg_contents": "I've pushed the first draft for $SUBJECT at\n\nhttps://git.postgresql.org/pg/commitdiff/2f38ec6a157b60291ece1deb072bfff84f317334\n\nPlease send comments/corrections by Sunday.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 06 Aug 2021 14:57:39 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Release notes for August minor releases" } ]
[ { "msg_contents": "pgstat: Bring up pgstat in BaseInit() to fix uninitialized use of pgstat by AV.\n\nPreviously pgstat_initialize() was called in InitPostgres() and\nAuxiliaryProcessMain(). As it turns out there was at least one case where we\nreported stats before pgstat_initialize() was called, see\nAutoVacWorkerMain()'s intentionally early call to pgstat_report_autovac().\n\nThis turns out to not be a problem with the current pgstat implementation as\npgstat_initialize() only registers a shutdown callback. But in the shared\nmemory based stats implementation we are working towards pgstat_initialize()\nhas to do more work.\n\nAfter b406478b87e BaseInit() is a central place where initialization shared by\nnormal backends and auxiliary backends can be put. Obviously BaseInit() is\ncalled before InitPostgres() registers ShutdownPostgres. Previously\nShutdownPostgres was the first before_shmem_exit callback, now that's commonly\npgstats. That should be fine.\n\nPreviously pgstat_initialize() was not called in bootstrap mode, but there\ndoes not appear to be a need for that. It's now done unconditionally.\n\nTo detect future issues like this, assertions are added to a few places\nverifying that the pgstat subsystem is initialized and not yet shut down.\n\nAuthor: Andres Freund <andres@anarazel.de>\nDiscussion: https://postgr.es/m/20210405092914.mmxqe7j56lsjfsej@alap3.anarazel.de\nDiscussion: https://postgr.es/m/20210802164124.ufo5buo4apl6yuvs@alap3.anarazel.de\n\nBranch\n------\nmaster\n\nDetails\n-------\nhttps://git.postgresql.org/pg/commitdiff/ee3f8d3d3aec0d7c961d6b398d31504bb272a450\n\nModified Files\n--------------\nsrc/backend/postmaster/auxprocess.c | 2 --\nsrc/backend/postmaster/pgstat.c | 53 +++++++++++++++++++++++++++++++++++--\nsrc/backend/utils/init/postinit.c | 23 +++++++++-------\n3 files changed, 65 insertions(+), 13 deletions(-)", "msg_date": "Sat, 07 Aug 2021 02:30:26 +0000", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized use\n o" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> pgstat: Bring up pgstat in BaseInit() to fix uninitialized use of pgstat by AV.\n\nsifaka took exception to this, or at least I guess it was this one out\nof the four you pushed at once:\n\nTRAP: FailedAssertion(\"pgstat_is_initialized && !pgstat_is_shutdown\", File: \"pgstat.c\", Line: 4810, PID: 74447)\n0 postgres 0x0000000100e5a520 ExceptionalCondition + 124\n1 postgres 0x0000000100ca1dec pgstat_reset_counters + 0\n2 postgres 0x0000000100ca2548 pgstat_report_tempfile + 80\n3 postgres 0x0000000100d07ca4 FileClose + 536\n4 postgres 0x0000000100d09764 CleanupTempFiles + 160\n5 postgres 0x0000000100d0f8c0 proc_exit_prepare + 228\n6 postgres 0x0000000100d0f79c proc_exit + 24\n7 postgres 0x0000000100e5ae04 errfinish + 856\n8 postgres 0x0000000100f1a804 ProcessInterrupts.cold.9 + 88\n9 postgres 0x0000000100d36a98 ProcessInterrupts + 604\n10 postgres 0x0000000100cd93c4 sendDir + 1516\n11 postgres 0x0000000100cd83a0 perform_base_backup + 3592\n12 postgres 0x0000000100cd72c0 SendBaseBackup + 256\n13 postgres 0x0000000100ce6a48 exec_replication_command + 1852\n14 postgres 0x0000000100d39190 PostgresMain + 3260\n15 postgres 0x0000000100ca9c78 process_startup_packet_die + 0\n16 postgres 0x0000000100ca94ec ClosePostmasterPorts + 0\n17 postgres 0x0000000100ca6a0c PostmasterMain + 4584\n18 postgres 0x0000000100c0b798 help + 0\n19 libdyld.dylib 0x0000000184391430 start + 4\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 06 Aug 2021 22:44:07 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "Hi,\n\nOn 2021-08-06 22:44:07 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > pgstat: Bring up pgstat in BaseInit() to fix uninitialized use of pgstat by AV.\n> \n> sifaka took exception to this, or at least I guess it was this one out\n> of the four you pushed at once:\n\nLongfin as well. It's the assertions from ee3f8d3d3ae, but possibly only\nexposed after fb2c5028e63.\n\nNot sure why it's your two animals that report this issue, but not others? Why\nwould a backend doing SendBaseBackup() previously have allocated temp files?\n\nDon't get me wrong - it's good that they surfaced the issue, and it's an issue\nindependent of the specific trigger.\n\nGlad I added the assertions...\n\n\nSee also https://www.postgresql.org/message-id/20210803023612.iziacxk5syn2r4ut%40alap3.anarazel.de\n\n> TRAP: FailedAssertion(\"pgstat_is_initialized && !pgstat_is_shutdown\", File: \"pgstat.c\", Line: 4810, PID: 74447)\n> 0 postgres 0x0000000100e5a520 ExceptionalCondition + 124\n> 1 postgres 0x0000000100ca1dec pgstat_reset_counters + 0\n> 2 postgres 0x0000000100ca2548 pgstat_report_tempfile + 80\n> 3 postgres 0x0000000100d07ca4 FileClose + 536\n> 4 postgres 0x0000000100d09764 CleanupTempFiles + 160\n> 5 postgres 0x0000000100d0f8c0 proc_exit_prepare + 228\n> 6 postgres 0x0000000100d0f79c proc_exit + 24\n> 7 postgres 0x0000000100e5ae04 errfinish + 856\n> 8 postgres 0x0000000100f1a804 ProcessInterrupts.cold.9 + 88\n> 9 postgres 0x0000000100d36a98 ProcessInterrupts + 604\n> 10 postgres 0x0000000100cd93c4 sendDir + 1516\n> 11 postgres 0x0000000100cd83a0 perform_base_backup + 3592\n> 12 postgres 0x0000000100cd72c0 SendBaseBackup + 256\n> 13 postgres 0x0000000100ce6a48 exec_replication_command + 1852\n> 14 postgres 0x0000000100d39190 PostgresMain + 3260\n> 15 postgres 0x0000000100ca9c78 process_startup_packet_die + 0\n> 16 postgres 0x0000000100ca94ec ClosePostmasterPorts + 0\n> 17 postgres 0x0000000100ca6a0c PostmasterMain + 4584\n> 18 postgres 0x0000000100c0b798 help + 0\n> 19 libdyld.dylib 0x0000000184391430 start + 4\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 6 Aug 2021 20:06:52 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> Not sure why it's your two animals that report this issue, but not others? Why\n> would a backend doing SendBaseBackup() previously have allocated temp files?\n\nGuessing the common factor is \"macOS\", but that's just a guess.\nI can poke into it tomorrow.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 06 Aug 2021 23:13:28 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "Hi,\n\nOn 2021-08-06 23:13:28 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > Not sure why it's your two animals that report this issue, but not others? Why\n> > would a backend doing SendBaseBackup() previously have allocated temp files?\n> \n> Guessing the common factor is \"macOS\", but that's just a guess.\n\nProbably not a bad one...\n\n\n> I can poke into it tomorrow.\n\nThanks! Might be interesting to run the pg_basebackup tests with\nlog_temp_files=0...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 6 Aug 2021 20:20:22 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "I wrote:\n> Guessing the common factor is \"macOS\", but that's just a guess.\n> I can poke into it tomorrow.\n\nI did try it real quick on my Mac laptop, and that fails too.\nHere's a more accurate backtrace, in case that helps.\n\n(lldb) bt\n* thread #1, stop reason = signal SIGSTOP\n * frame #0: 0x00007fff2033e92e libsystem_kernel.dylib`__pthread_kill + 10\n frame #1: 0x00007fff2036d5bd libsystem_pthread.dylib`pthread_kill + 263\n frame #2: 0x00007fff202c2406 libsystem_c.dylib`abort + 125\n frame #3: 0x0000000108cdf87f postgres`ExceptionalCondition(conditionName=<unavailable>, errorType=<unavailable>, fileName=<unavailable>, lineNumber=<unavailable>) at assert.c:69:2 [opt]\n frame #4: 0x0000000108b0f551 postgres`pgstat_send [inlined] pgstat_assert_is_up at pgstat.c:4810:2 [opt]\n frame #5: 0x0000000108b0f532 postgres`pgstat_send(msg=<unavailable>, len=<unavailable>) at pgstat.c:3032 [opt]\n frame #6: 0x0000000108b0fbef postgres`pgstat_report_tempfile(filesize=<unavailable>) at pgstat.c:1812:2 [opt]\n frame #7: 0x0000000108b7abfe postgres`FileClose [inlined] ReportTemporaryFileUsage(path=\"base/pgsql_tmp/pgsql_tmp35840.0\", size=0) at fd.c:1483:2 [opt]\n frame #8: 0x0000000108b7abf6 postgres`FileClose(file=1) at fd.c:1987 [opt]\n frame #9: 0x0000000108b7c3b8 postgres`CleanupTempFiles(isCommit=false, isProcExit=true) at fd.c:0 [opt]\n frame #10: 0x0000000108b82661 postgres`proc_exit_prepare(code=1) at ipc.c:209:3 [opt]\n frame #11: 0x0000000108b8253d postgres`proc_exit(code=1) at ipc.c:107:2 [opt]\n frame #12: 0x0000000108ce0201 postgres`errfinish(filename=<unavailable>, lineno=<unavailable>, funcname=<unavailable>) at elog.c:666:3 [opt]\n frame #13: 0x0000000108db362b postgres`ProcessInterrupts.cold.9 at postgres.c:3222:3 [opt]\n frame #14: 0x0000000108baa2a4 postgres`ProcessInterrupts at postgres.c:3218:22 [opt]\n frame #15: 0x0000000108b49f4a postgres`sendDir(path=\".\", basepathlen=1, sizeonly=false, tablespaces=0x00007fb47f0719c8, sendtblspclinks=true, manifest=<unavailable>, spcoid=0x0000000000000000) at basebackup.c:1277:3 [opt]\n frame #16: 0x0000000108b48dc8 postgres`perform_base_backup(opt=0x00007ffee73ae0a0) at basebackup.c:432:5 [opt]\n frame #17: 0x0000000108b47bf0 postgres`SendBaseBackup(cmd=<unavailable>) at basebackup.c:949:2 [opt]\n frame #18: 0x0000000108b58055 postgres`exec_replication_command(cmd_string=\"BASE_BACKUP LABEL 'pg_basebackup base backup' PROGRESS NOWAIT MANIFEST 'yes' \") at walsender.c:1625:4 [opt]\n frame #19: 0x0000000108bac8aa postgres`PostgresMain(argc=<unavailable>, argv=<unavailable>, dbname=<unavailable>, username=<unavailable>) at postgres.c:4484:12 [opt]\n frame #20: 0x0000000108b178db postgres`BackendRun(port=<unavailable>) at postmaster.c:4519:2 [opt]\n frame #21: 0x0000000108b17178 postgres`ServerLoop [inlined] BackendStartup(port=<unavailable>) at postmaster.c:4241:3 [opt]\n frame #22: 0x0000000108b17154 postgres`ServerLoop at postmaster.c:1758 [opt]\n frame #23: 0x0000000108b1421b postgres`PostmasterMain(argc=4, argv=0x00007fb47ec06640) at postmaster.c:1430:11 [opt]\n frame #24: 0x0000000108a6ac13 postgres`main(argc=<unavailable>, argv=<unavailable>) at main.c:199:3 [opt]\n frame #25: 0x00007fff20388f3d libdyld.dylib`start + 1\n\nI see two core dumps with what seem to be this same trace after\nrunning pg_basebackup's tests.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 06 Aug 2021 23:22:36 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "Hi,\n\nOn 2021-08-06 23:22:36 -0400, Tom Lane wrote:\n> I wrote:\n> > Guessing the common factor is \"macOS\", but that's just a guess.\n> > I can poke into it tomorrow.\n>\n> I did try it real quick on my Mac laptop, and that fails too.\n> Here's a more accurate backtrace, in case that helps.\n\nThanks!\n\nI now managed to reproduce it on a CI system (after some initial\nfailed attempts due to pg_upgrade tests failing due to path length issues):\nhttps://api.cirrus-ci.com/v1/artifact/task/4863568911794176/log/src/bin/pg_basebackup/tmp_check/log/010_pg_basebackup_main.log\n\n2021-08-06 21:18:40.096 PDT [22031] 010_pg_basebackup.pl LOG: received replication command: BASE_BACKUP LABEL 'pg_basebackup base backup' PROGRESS NOWAIT MANIFEST 'yes' \n2021-08-06 21:18:40.096 PDT [22031] 010_pg_basebackup.pl STATEMENT: BASE_BACKUP LABEL 'pg_basebackup base backup' PROGRESS NOWAIT MANIFEST 'yes' \n2021-08-06 21:18:42.210 PDT [22031] 010_pg_basebackup.pl LOG: could not send data to client: Broken pipe\n2021-08-06 21:18:42.210 PDT [22031] 010_pg_basebackup.pl STATEMENT: BASE_BACKUP LABEL 'pg_basebackup base backup' PROGRESS NOWAIT MANIFEST 'yes' \n2021-08-06 21:18:42.210 PDT [22031] 010_pg_basebackup.pl FATAL: connection to client lost\n2021-08-06 21:18:42.210 PDT [22031] 010_pg_basebackup.pl STATEMENT: BASE_BACKUP LABEL 'pg_basebackup base backup' PROGRESS NOWAIT MANIFEST 'yes' \nTRAP: FailedAssertion(\"pgstat_is_initialized && !pgstat_is_shutdown\", File: \"pgstat.c\", Line: 4810, PID: 22031)\n\nvs what I locally get:\n2021-08-06 20:52:06.163 PDT [1397252] 010_pg_basebackup.pl LOG: received replication command: BASE_BACKUP LABEL 'pg_basebackup base backup' PROGRESS NOWAIT MANIFEST 'yes' \n2021-08-06 20:52:06.163 PDT [1397252] 010_pg_basebackup.pl STATEMENT: BASE_BACKUP LABEL 'pg_basebackup base backup' PROGRESS NOWAIT MANIFEST 'yes' \n2021-08-06 20:52:08.189 PDT [1397252] 010_pg_basebackup.pl LOG: could not send data to client: Broken pipe\n2021-08-06 20:52:08.189 PDT [1397252] 010_pg_basebackup.pl STATEMENT: BASE_BACKUP LABEL 'pg_basebackup base backup' PROGRESS NOWAIT MANIFEST 'yes' \n2021-08-06 20:52:08.189 PDT [1397252] 010_pg_basebackup.pl ERROR: base backup could not send data, aborting backup\n2021-08-06 20:52:08.189 PDT [1397252] 010_pg_basebackup.pl STATEMENT: BASE_BACKUP LABEL 'pg_basebackup base backup' PROGRESS NOWAIT MANIFEST 'yes' \n2021-08-06 20:52:08.189 PDT [1397252] 010_pg_basebackup.pl FATAL: connection to client lost\n\nNote that OSX version doesn't have the \"base backup could not send data,\naborting backup\" message. I guess that is what leads to the difference in\nbehaviour:\n\nThe temp file is created by InitializeBackupManifest(). In the !OSX case, we\nfirst abort via an ERROR, which triggers the cleanup via\nWalSndResourceCleanup(). On OSX however, we immediately error out with FATAL\nfor some reason (timing? network buffering differences?), which will never\nreach WalSndErrorCleanup(). Therefore the temp file only gets deleted during\nproc_exit(), which triggers the issue...\n\nNot yet really sure what the best way to deal with this is. Presumably this\nissue would be fixed if AtProcExit_Files()/CleanupTempFiles() were scheduled\nvia before_shmem_exit(). And perhaps it's not too off to schedule\nCleanupTempFiles() there - but it doesn't quite seem entirely right either.\n\nI'd kinda like to avoid having to overhaul the process exit infrastructure as\na prerequisite to getting the shared memory stats patch in :(.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 6 Aug 2021 21:49:52 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "Hi,\n\nOn 2021-08-06 21:49:52 -0700, Andres Freund wrote:\n> The temp file is created by InitializeBackupManifest(). In the !OSX case, we\n> first abort via an ERROR, which triggers the cleanup via\n> WalSndResourceCleanup(). On OSX however, we immediately error out with FATAL\n> for some reason (timing? network buffering differences?), which will never\n> reach WalSndErrorCleanup(). Therefore the temp file only gets deleted during\n> proc_exit(), which triggers the issue...\n> \n> Not yet really sure what the best way to deal with this is. Presumably this\n> issue would be fixed if AtProcExit_Files()/CleanupTempFiles() were scheduled\n> via before_shmem_exit(). And perhaps it's not too off to schedule\n> CleanupTempFiles() there - but it doesn't quite seem entirely right either.\n\nHuh. I just noticed that AtProcExit_Files() is not even scheduled via\non_shmem_exit() but on_proc_exit(). That means that even before fb2c5028e63\nwe sent pgstat messages *well* after pgstat_shutdown_hook() already\nran. Crufty.\n\nJust hacking in an earlier CleanupTempFiles() does \"fix\" the OSX issue:\nhttps://cirrus-ci.com/task/5941265494704128?logs=macos_basebackup#L4\n\nI'm inclined to leave things as-is until tomorrow to see if other things are\nshaken loose and then either commit a bandaid along those lines or revert the\npatch. Or something proper if we can figure it out till then.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 6 Aug 2021 22:11:49 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2021-08-06 21:49:52 -0700, Andres Freund wrote:\n>> Not yet really sure what the best way to deal with this is. Presumably this\n>> issue would be fixed if AtProcExit_Files()/CleanupTempFiles() were scheduled\n>> via before_shmem_exit(). And perhaps it's not too off to schedule\n>> CleanupTempFiles() there - but it doesn't quite seem entirely right either.\n\n> Huh. I just noticed that AtProcExit_Files() is not even scheduled via\n> on_shmem_exit() but on_proc_exit(). That means that even before fb2c5028e63\n> we sent pgstat messages *well* after pgstat_shutdown_hook() already\n> ran. Crufty.\n\n> Just hacking in an earlier CleanupTempFiles() does \"fix\" the OSX issue:\n> https://cirrus-ci.com/task/5941265494704128?logs=macos_basebackup#L4\n\nSo if I have the lay of the land correctly:\n\n1. Somebody decided it'd be a great idea for temp file cleanup to send\nstats collector messages.\n\n2. Temp file cleanup happens after shmem disconnection.\n\n3. This accidentally worked, up to now, because stats transmission happens\nvia a separate socket not shared memory.\n\n4. We can't keep both #1 and #2 if we'd like to switch to shmem-based\nstats collection.\n\nIntuitively it seems like temp file management should be a low-level,\nbackend-local function and therefore should be okay to run after\nshmem disconnection. I do not have a warm feeling about reversing that\nmodule layering --- what's to stop someone from breaking things by\ntrying to use a temp file in their on_proc_exit or on_shmem_exit hook?\nMaybe what needs to go overboard is point 1.\n\nMore generally, this points up the fact that we don't have a well-defined\nmodule hierarchy that would help us understand what code can safely do which.\nI'm not volunteering to design that, but maybe it needs to happen soon.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 07 Aug 2021 11:43:07 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "Hi,\n\nOn 2021-08-07 11:43:07 -0400, Tom Lane wrote:\n> So if I have the lay of the land correctly:\n> \n> 1. Somebody decided it'd be a great idea for temp file cleanup to send\n> stats collector messages.\n> \n> 2. Temp file cleanup happens after shmem disconnection.\n> \n> 3. This accidentally worked, up to now, because stats transmission happens\n> via a separate socket not shared memory.\n> \n> 4. We can't keep both #1 and #2 if we'd like to switch to shmem-based\n> stats collection.\n\nSounds accurate to me.\n\n\n> Intuitively it seems like temp file management should be a low-level,\n> backend-local function and therefore should be okay to run after\n> shmem disconnection. I do not have a warm feeling about reversing that\n> module layering --- what's to stop someone from breaking things by\n> trying to use a temp file in their on_proc_exit or on_shmem_exit hook?\n\nWe could just add an assert preventing that from happening. It's hard to\nbelieve that there could be a good reason to use temp files in those hook\npoints.\n\nI'm somewhat inclined to split InitFileAccess() into two by separating out\nInitTemporaryFileAccess() or such. InitFileAccess() would continue to happen\nearly and register a proc exit hook that errors out when there's a temp file\n(as a backstop for non cassert builds). The new InitTemporaryFileAccess()\nwould happen a bit later and schedule CleanupTempFiles() to happen via\nbefore_shmem_access(). And we add a Assert(!proc_exit_inprogress) to the\nroutines for opening a temp file.\n\n\n> Maybe what needs to go overboard is point 1.\n\nKeeping stats of temp files seems useful enough that I'm a bit hesitant to go\nthere. I guess we could just prevent pgstats_report_tempfile() from being\ncalled when CleanupTempFiles() is called during proc exit, but that doesn't\nseem great.\n\n\n> More generally, this points up the fact that we don't have a well-defined\n> module hierarchy that would help us understand what code can safely do which.\n> I'm not volunteering to design that, but maybe it needs to happen soon.\n\nI agree. Part of the reason for whacking around process startup (in both\npushed and still pending commits) was that previously it wasn't just poorly\ndefined, it differed significantly between platforms. And I'm quite unhappy\nwith the vagueness in which we defined the meaning of the various shutdown\ncallbacks ([1]).\n\nI suspect to even get to the point of doing a useful redesign of the module\nhierarchy, we'd need to unify more of the process initialization between\nEXEC_BACKEND and normal builds.\n\nI've bitten by all this often enough to be motivated to propose\nsomething. However I want to get the basics of the shared memory stats stuff\nin first - it's a pain to keep it upated, and we'll need to find and solve all\nof the issues it has anyway, even if we go for a redesign of module / startup\n/ shutdown layering.\n\nGreetings,\n\nAndres Freund\n\n[1] https://www.postgresql.org/message-id/20210803023612.iziacxk5syn2r4ut%40alap3.anarazel.de\n\n\n", "msg_date": "Sat, 7 Aug 2021 09:48:50 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2021-08-07 11:43:07 -0400, Tom Lane wrote:\n>> Intuitively it seems like temp file management should be a low-level,\n>> backend-local function and therefore should be okay to run after\n>> shmem disconnection. I do not have a warm feeling about reversing that\n>> module layering --- what's to stop someone from breaking things by\n>> trying to use a temp file in their on_proc_exit or on_shmem_exit hook?\n\n> We could just add an assert preventing that from happening. It's hard to\n> believe that there could be a good reason to use temp files in those hook\n> points.\n\nThe bigger picture here is that anyplace anybody ever wants to add stats\ncollection in suddenly becomes a \"must run before shmem disconnection\"\nmodule. I think that way madness lies --- we can't have the entire\nbackend shut down before shmem disconnection. So I feel like there's\na serious design problem here, and it's not confined to temp files,\nor at least it won't stay confined to temp files. (There may indeed\nbe other problems already, that we just haven't had the good luck to\nhave buildfarm timing vagaries expose to us.)\n\nMaybe the solution is to acknowledge that we might lose some events\nduring backend shutdown, and redefine the behavior as \"we ignore\nevent reports after pgstat shutdown\", not \"we assert that there never\ncan be any such reports\".\n\n> I'm somewhat inclined to split InitFileAccess() into two by separating out\n> InitTemporaryFileAccess() or such. InitFileAccess() would continue to happen\n> early and register a proc exit hook that errors out when there's a temp file\n> (as a backstop for non cassert builds). The new InitTemporaryFileAccess()\n> would happen a bit later and schedule CleanupTempFiles() to happen via\n> before_shmem_access(). And we add a Assert(!proc_exit_inprogress) to the\n> routines for opening a temp file.\n\nMaybe that would work, but after you multiply it by a bunch of different\nscenarios in different modules, it's going to get less and less attractive.\n\n> I've bitten by all this often enough to be motivated to propose\n> something. However I want to get the basics of the shared memory stats stuff\n> in first - it's a pain to keep it upated, and we'll need to find and solve all\n> of the issues it has anyway, even if we go for a redesign of module / startup\n> / shutdown layering.\n\nFair. But I suggest that the first cut should look more like what\nI suggest above, ie just be willing to lose events during shutdown.\nThe downsides of that are not so enormous that we should be willing\nto undertake major klugery to avoid it before we've even got a\nsemi-working system.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 07 Aug 2021 13:06:47 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "Hi,\n\nOn 2021-08-07 13:06:47 -0400, Tom Lane wrote:\n> The bigger picture here is that anyplace anybody ever wants to add stats\n> collection in suddenly becomes a \"must run before shmem disconnection\"\n> module. I think that way madness lies --- we can't have the entire\n> backend shut down before shmem disconnection. So I feel like there's\n> a serious design problem here, and it's not confined to temp files,\n> or at least it won't stay confined to temp files. (There may indeed\n> be other problems already, that we just haven't had the good luck to\n> have buildfarm timing vagaries expose to us.)\n\nI think more often it should not end up as \"must run before shmem\ndisconnection\" as a whole, but should be split into a portion running at that\npoint.\n\n\n> Maybe the solution is to acknowledge that we might lose some events\n> during backend shutdown, and redefine the behavior as \"we ignore\n> event reports after pgstat shutdown\", not \"we assert that there never\n> can be any such reports\".\n\nI think it's fine to make such calls, but that it ought to reside in the stats\nemitting modules. Only it can decide whether needing to emit stats during\nshutdown is a rare edge case or a commonly expected path. E.g. the case of\nparallel worker shutdown sending stats too late is something common enough to\nbe problematic, so I don't want to make it too hard to detect such cases.\n\n\n> > I'm somewhat inclined to split InitFileAccess() into two by separating out\n> > InitTemporaryFileAccess() or such. InitFileAccess() would continue to happen\n> > early and register a proc exit hook that errors out when there's a temp file\n> > (as a backstop for non cassert builds). The new InitTemporaryFileAccess()\n> > would happen a bit later and schedule CleanupTempFiles() to happen via\n> > before_shmem_access(). And we add a Assert(!proc_exit_inprogress) to the\n> > routines for opening a temp file.\n>\n> Maybe that would work, but after you multiply it by a bunch of different\n> scenarios in different modules, it's going to get less and less attractive.\n\nI'm not quite convinced. Even if we had a nicer ordering / layering of\nsubsystems, we'd still have to deal with subsystems that don't fit nicely\nbecause they have conflicting needs. And we'd still need detection of use of\nsubsystems that already have not been initialized / are already shut down.\n\nOne example of that is imo fd.c being a very low level module that might be\nneeded during shutdown of other modules but which also currently depends on\nthe stats subsystem for temp file management. Which doesn't really make sense,\nbecause stats very well could depend on fd.c routines.\n\nI think needing to split the current fd.c subsystem into a lower-level (file\naccess) and a higher level (temporary file management) module is precisely\nwhat a better designed module layering system will *force* us to do.\n\n\n> > I've bitten by all this often enough to be motivated to propose\n> > something. However I want to get the basics of the shared memory stats stuff\n> > in first - it's a pain to keep it upated, and we'll need to find and solve all\n> > of the issues it has anyway, even if we go for a redesign of module / startup\n> > / shutdown layering.\n>\n> Fair. But I suggest that the first cut should look more like what\n> I suggest above, ie just be willing to lose events during shutdown.\n> The downsides of that are not so enormous that we should be willing\n> to undertake major klugery to avoid it before we've even got a\n> semi-working system.\n\nI think that's more likely to hide bugs unfortunately. Consider fa91d4c91f2 -\nI might not have found that if we had just ignored \"too late\" pgstats activity\nin pgstats.c or fd.c, and that's not an edge case.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sat, 7 Aug 2021 10:25:56 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2021-08-07 13:06:47 -0400, Tom Lane wrote:\n>> Fair. But I suggest that the first cut should look more like what\n>> I suggest above, ie just be willing to lose events during shutdown.\n>> The downsides of that are not so enormous that we should be willing\n>> to undertake major klugery to avoid it before we've even got a\n>> semi-working system.\n\n> I think that's more likely to hide bugs unfortunately. Consider fa91d4c91f2 -\n> I might not have found that if we had just ignored \"too late\" pgstats activity\n> in pgstats.c or fd.c, and that's not an edge case.\n\nDepends what you want to define as a bug. What I am not happy about\nis the prospect of random assertion failures for the next six months\nwhile you finish redesigning half of the system. The rest of us\nhave work we want to get done, too. I don't object to the idea of\nmaking no-lost-events an end goal, but we are clearly not ready\nfor that today.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 07 Aug 2021 13:37:16 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "Hi,\n\nOn 2021-08-07 13:37:16 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > On 2021-08-07 13:06:47 -0400, Tom Lane wrote:\n> >> Fair. But I suggest that the first cut should look more like what\n> >> I suggest above, ie just be willing to lose events during shutdown.\n> >> The downsides of that are not so enormous that we should be willing\n> >> to undertake major klugery to avoid it before we've even got a\n> >> semi-working system.\n> \n> > I think that's more likely to hide bugs unfortunately. Consider fa91d4c91f2 -\n> > I might not have found that if we had just ignored \"too late\" pgstats activity\n> > in pgstats.c or fd.c, and that's not an edge case.\n> \n> Depends what you want to define as a bug. What I am not happy about\n> is the prospect of random assertion failures for the next six months\n> while you finish redesigning half of the system. The rest of us\n> have work we want to get done, too. I don't object to the idea of\n> making no-lost-events an end goal, but we are clearly not ready\n> for that today.\n\nI don't know what to do about that. How would we even find these cases if they\naren't hit during regression tests on my machine (nor on a lot of others)?\nObviously I had ran the regression tests many times before pushing the earlier\nchanges.\n\nThe check for pgstat being up is in one central place and thus easily can be\nturned into a warning if problems around the shutdown sequence become a\nfrequent issue on HEAD. If you think it's better to turn that into a WARNING\nnow and then arm into an assert later, I can live with that as well, but I\ndon't think it'll lead to a better outcome.\n\nThe shared memory stats stuff isn't my personal project - it's\nHoriguchi-san's. I picked it up because it seems like an important thing to\naddress and because it'd been in maybe a dozen CFs without a lot of\nprogress. It just turns out that there's a lot of prerequisite changes :(.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sat, 7 Aug 2021 11:51:41 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "Hi,\n\nOn 2021-08-07 09:48:50 -0700, Andres Freund wrote:\n> I'm somewhat inclined to split InitFileAccess() into two by separating out\n> InitTemporaryFileAccess() or such. InitFileAccess() would continue to happen\n> early and register a proc exit hook that errors out when there's a temp file\n> (as a backstop for non cassert builds). The new InitTemporaryFileAccess()\n> would happen a bit later and schedule CleanupTempFiles() to happen via\n> before_shmem_access(). And we add a Assert(!proc_exit_inprogress) to the\n> routines for opening a temp file.\n\nAttached is a patch showing how this could look like. Note that the PANIC\nshould likely not be that but a WARNING, but the PANIC more useful for running\nsome initial tests...\n\nI'm not sure whether we'd want to continue having the proc exit hook? It seems\nto me that asserts would provide a decent enough protection against\nintroducing new temp files during shutdown.\n\nAlternatively we could make the asserts in OpenTemporaryFile et al\nelog(ERROR)s, and be pretty certain that no temp files would be open too late?\n\nGreetings,\n\nAndres Freund", "msg_date": "Sat, 7 Aug 2021 12:01:31 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2021-08-07 13:37:16 -0400, Tom Lane wrote:\n>> Depends what you want to define as a bug. What I am not happy about\n>> is the prospect of random assertion failures for the next six months\n>> while you finish redesigning half of the system. The rest of us\n>> have work we want to get done, too. I don't object to the idea of\n>> making no-lost-events an end goal, but we are clearly not ready\n>> for that today.\n\n> I don't know what to do about that. How would we even find these cases if they\n> aren't hit during regression tests on my machine (nor on a lot of others)?\n\nThe regression tests really aren't that helpful for testing the problem\nscenario here, which basically is SIGTERM'ing a query-in-progress.\nI'm rather surprised that the buildfarm managed to exercise that at all.\n\nYou might try setting up a test scaffold that runs the core regression\ntests and SIGINT's the postmaster, or alternatively SIGTERM's some\nindividual session, at random times partway through. Obviously this\nwill make the regression tests report failure, but what to look for\nis if anything dumps core on the way out.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 07 Aug 2021 15:12:38 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "Hi,\n\nOn 2021-08-07 15:12:38 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > On 2021-08-07 13:37:16 -0400, Tom Lane wrote:\n> >> Depends what you want to define as a bug. What I am not happy about\n> >> is the prospect of random assertion failures for the next six months\n> >> while you finish redesigning half of the system. The rest of us\n> >> have work we want to get done, too. I don't object to the idea of\n> >> making no-lost-events an end goal, but we are clearly not ready\n> >> for that today.\n> \n> > I don't know what to do about that. How would we even find these cases if they\n> > aren't hit during regression tests on my machine (nor on a lot of others)?\n> \n> The regression tests really aren't that helpful for testing the problem\n> scenario here, which basically is SIGTERM'ing a query-in-progress.\n> I'm rather surprised that the buildfarm managed to exercise that at all.\n\nThey're also not that helpful because this problem likely is unreachable for\nany tempfiles other than the one in InitializeBackupManifest(). Pretty much\nall, or even all, the other tempfiles are cleaned up either via transaction\nand/or resowner cleanup.\n\n\nI wonder if we should do something about WalSndResourceCleanup() not being\nreached for FATALs? I think at least a note in WalSndResourceCleanup()\ncommenting on that fact seems like it might be a good idea?\n\nIt seems like it could eventually be a problem that the resowners added in\n0d8c9c1210c4 aren't ever cleaned up in case of a FATAL error. Most resowner\ncleanup actions are also backstopped with some form of on-exit hook, but I\ndon't think it's all - e.g. buffer pins aren't.\n\nI guess I should start a thread about this on -hackers...\n\n\n> You might try setting up a test scaffold that runs the core regression\n> tests and SIGINT's the postmaster, or alternatively SIGTERM's some\n> individual session, at random times partway through. Obviously this\n> will make the regression tests report failure, but what to look for\n> is if anything dumps core on the way out.\n\nWorth trying.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sat, 7 Aug 2021 14:03:49 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "Hi,\n\nOn 2021-08-07 12:01:31 -0700, Andres Freund wrote:\n> Attached is a patch showing how this could look like. Note that the PANIC\n> should likely not be that but a WARNING, but the PANIC more useful for running\n> some initial tests...\n\nI pushed a slightly evolved version of this. As the commit message noted, this\nmay not be the best approach, but we can revise after further discussion.\n\n\n> I'm not sure whether we'd want to continue having the proc exit hook? It seems\n> to me that asserts would provide a decent enough protection against\n> introducing new temp files during shutdown.\n\n> Alternatively we could make the asserts in OpenTemporaryFile et al\n> elog(ERROR)s, and be pretty certain that no temp files would be open too late?\n\nI ended up removing the proc exit hook and not converting the asserts to an\nelog(). Happy to change either.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sat, 7 Aug 2021 19:24:35 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "On Sat, Aug 7, 2021 at 11:43 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Intuitively it seems like temp file management should be a low-level,\n> backend-local function and therefore should be okay to run after\n> shmem disconnection. I do not have a warm feeling about reversing that\n> module layering --- what's to stop someone from breaking things by\n> trying to use a temp file in their on_proc_exit or on_shmem_exit hook?\n> Maybe what needs to go overboard is point 1.\n>\n> More generally, this points up the fact that we don't have a well-defined\n> module hierarchy that would help us understand what code can safely do which.\n> I'm not volunteering to design that, but maybe it needs to happen soon.\n\nYeah, I was quite surprised when I saw this commit, because my first\nreaction was - why in the world would temporary file shutdown properly\nprecede DSM shutdown, given that temporary files are a low-level\nmechanism? The explanation that we're trying to send statistics at\nthat point makes sense as far as it goes, but it seems to me that we\ncannot be far from having a circular dependency. All we need is to\nhave DSM require the use of temporary files, and we'll end up needing\nDSM shutdown to happen both before and after temporary file cleanup.\n\n/me wonders idly about dynamic_shared_memory_type=file\n\nI think that subsystems like \"memory\" and \"files\" really ought to be\nthe lowest-level things we have, and should be shut down last. Stuff\nlike \"send a message to the stats collector\" seems like a higher level\nthing that may require those lower-level facilities in order to\noperate, and must therefore be shut down first. Maybe some subsystems\nneed to be divided into upper and lower levels to make this work, or,\nwell, I don't know, something else. But I'm deeply suspicious that\nlifting stuff like this to the front of the shutdown sequence is just\npapering over the problem, and not actually solving it.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 9 Aug 2021 11:46:30 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "Hi,\n\nOn 2021-08-09 11:46:30 -0400, Robert Haas wrote:\n> I think that subsystems like \"memory\" and \"files\" really ought to be\n> the lowest-level things we have, and should be shut down last.\n\nI don't disagree with that - but there's a difference between having that as\nan abstract goal, and having it a dependency of committing somebodies patch.\n\n\n> Stuff like \"send a message to the stats collector\" seems like a higher level\n> thing that may require those lower-level facilities in order to operate, and\n> must therefore be shut down first.\n\nYep.\n\n\n> Maybe some subsystems need to be divided into upper and lower levels to make\n> this work, or, well, I don't know, something else.\n\nThat's what I ended up doing, right? There's now InitFileAccess() and\nInitTemporaryFileAccess().\n\n\n> But I'm deeply suspicious that lifting stuff like this to the front of the\n> shutdown sequence is just papering over the problem, and not actually\n> solving it.\n\nIf you have a concrete proposal that you think makes sense to tie shared\nmemory stats to, I'm happy to entertain it. One main motivator for b406478b87e\netc was to allow rejiggering things like this more easily.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 9 Aug 2021 10:34:53 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "Hi,\n\nOn Sun, Aug 8, 2021 at 11:24 AM Andres Freund <andres@anarazel.de> wrote:\n>\n> Hi,\n>\n> On 2021-08-07 12:01:31 -0700, Andres Freund wrote:\n> > Attached is a patch showing how this could look like. Note that the PANIC\n> > should likely not be that but a WARNING, but the PANIC more useful for running\n> > some initial tests...\n>\n> I pushed a slightly evolved version of this. As the commit message noted, this\n> may not be the best approach, but we can revise after further discussion.\n\nWhile testing streaming logical replication, I got another assertion\nfailure with the current HEAD (e2ce88b58f) when the apply worker\nraised an error during applying spooled changes:\n\nTRAP: FailedAssertion(\"pgstat_is_initialized && !pgstat_is_shutdown\",\nFile: \"pgstat.c\", Line: 4810, PID: 11084)\n0 postgres 0x000000010704fd9a\nExceptionalCondition + 234\n1 postgres 0x0000000106d41e62\npgstat_assert_is_up + 66\n2 postgres 0x0000000106d43854 pgstat_send + 20\n3 postgres 0x0000000106d4433e\npgstat_report_tempfile + 94\n4 postgres 0x0000000106df9519\nReportTemporaryFileUsage + 25\n5 postgres 0x0000000106df945a\nPathNameDeleteTemporaryFile + 282\n6 postgres 0x0000000106df8c7e\nunlink_if_exists_fname + 174\n7 postgres 0x0000000106df8b3a walkdir + 426\n8 postgres 0x0000000106df8982\nPathNameDeleteTemporaryDir + 82\n9 postgres 0x0000000106dfe591\nSharedFileSetDeleteAll + 113\n10 postgres 0x0000000106dfdf62\nSharedFileSetDeleteOnProcExit + 66\n11 postgres 0x0000000106e05275\nproc_exit_prepare + 325\n12 postgres 0x0000000106e050a3 proc_exit + 19\n13 postgres 0x0000000106d3ba99\nStartBackgroundWorker + 649\n14 postgres 0x0000000106d54e85\ndo_start_bgworker + 613\n15 postgres 0x0000000106d4ef26\nmaybe_start_bgworkers + 486\n16 postgres 0x0000000106d4d767 sigusr1_handler + 631\n17 libsystem_platform.dylib 0x00007fff736705fd _sigtramp + 29\n18 ??? 0x0000000000000000 0x0 + 0\n19 postgres 0x0000000106d4c990 PostmasterMain + 6640\n20 postgres 0x0000000106c24fa3 main + 819\n21 libdyld.dylib 0x00007fff73477cc9 start + 1\n\nThe apply worker registers SharedFileSetDeleteOnProcExit() when\ncreating a file set to serialize the changes. When it raises an error\ndue to conflict during applying the change, the callback eventually\nreports the temp file statistics but pgstat already shut down,\nresulting in this assertion failure.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Tue, 10 Aug 2021 20:06:45 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Tue, Aug 10, 2021 at 4:37 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> The apply worker registers SharedFileSetDeleteOnProcExit() when\n> creating a file set to serialize the changes. When it raises an error\n> due to conflict during applying the change, the callback eventually\n> reports the temp file statistics but pgstat already shut down,\n> resulting in this assertion failure.\n>\n\nI think we can try to fix this by registering to clean up these files\nvia before_shmem_exit() as done by Andres in commit 675c945394.\nSimilar to that commit, we can change the function name\nSharedFileSetDeleteOnProcExit to SharedFileSetDeleteOnShmExit and\nregister it via before_shmem_exit() instead of on_proc_exit(). Can you\ntry that and see if it fixes the issue for you unless you have better\nideas to try out?\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Wed, 11 Aug 2021 19:17:07 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Wed, Aug 11, 2021 at 10:47 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Tue, Aug 10, 2021 at 4:37 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > The apply worker registers SharedFileSetDeleteOnProcExit() when\n> > creating a file set to serialize the changes. When it raises an error\n> > due to conflict during applying the change, the callback eventually\n> > reports the temp file statistics but pgstat already shut down,\n> > resulting in this assertion failure.\n> >\n>\n> I think we can try to fix this by registering to clean up these files\n> via before_shmem_exit() as done by Andres in commit 675c945394.\n> Similar to that commit, we can change the function name\n> SharedFileSetDeleteOnProcExit to SharedFileSetDeleteOnShmExit and\n> register it via before_shmem_exit() instead of on_proc_exit(). Can you\n> try that and see if it fixes the issue for you unless you have better\n> ideas to try out?\n\nIt seems to me that moving the shared fileset cleanup to\nbefore_shmem_exit() is the right approach to fix this problem. The\nissue is fixed by the attached patch.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/", "msg_date": "Thu, 12 Aug 2021 11:09:10 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Thu, Aug 12, 2021 at 7:39 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Wed, Aug 11, 2021 at 10:47 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > On Tue, Aug 10, 2021 at 4:37 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> > >\n> > > The apply worker registers SharedFileSetDeleteOnProcExit() when\n> > > creating a file set to serialize the changes. When it raises an error\n> > > due to conflict during applying the change, the callback eventually\n> > > reports the temp file statistics but pgstat already shut down,\n> > > resulting in this assertion failure.\n> > >\n> >\n> > I think we can try to fix this by registering to clean up these files\n> > via before_shmem_exit() as done by Andres in commit 675c945394.\n> > Similar to that commit, we can change the function name\n> > SharedFileSetDeleteOnProcExit to SharedFileSetDeleteOnShmExit and\n> > register it via before_shmem_exit() instead of on_proc_exit(). Can you\n> > try that and see if it fixes the issue for you unless you have better\n> > ideas to try out?\n>\n> It seems to me that moving the shared fileset cleanup to\n> before_shmem_exit() is the right approach to fix this problem. The\n> issue is fixed by the attached patch.\n\n+1, the fix makes sense to me.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 12 Aug 2021 11:38:03 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Thu, Aug 12, 2021 at 11:38 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Thu, Aug 12, 2021 at 7:39 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > On Wed, Aug 11, 2021 at 10:47 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > >\n> > > On Tue, Aug 10, 2021 at 4:37 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> > > >\n> > > > The apply worker registers SharedFileSetDeleteOnProcExit() when\n> > > > creating a file set to serialize the changes. When it raises an error\n> > > > due to conflict during applying the change, the callback eventually\n> > > > reports the temp file statistics but pgstat already shut down,\n> > > > resulting in this assertion failure.\n> > > >\n> > >\n> > > I think we can try to fix this by registering to clean up these files\n> > > via before_shmem_exit() as done by Andres in commit 675c945394.\n> > > Similar to that commit, we can change the function name\n> > > SharedFileSetDeleteOnProcExit to SharedFileSetDeleteOnShmExit and\n> > > register it via before_shmem_exit() instead of on_proc_exit(). Can you\n> > > try that and see if it fixes the issue for you unless you have better\n> > > ideas to try out?\n> >\n> > It seems to me that moving the shared fileset cleanup to\n> > before_shmem_exit() is the right approach to fix this problem. The\n> > issue is fixed by the attached patch.\n>\n> +1, the fix makes sense to me.\n>\n\nI have also tested and fix works for me. The fix works because\npgstat_initialize() is called before we register clean up in\nSharedFileSetInit(). I am not sure if we need an Assert to ensure that\nand if so how we can do that? Any suggestions?\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Thu, 12 Aug 2021 11:46:09 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Thu, Aug 12, 2021 at 3:16 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Thu, Aug 12, 2021 at 11:38 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n> > On Thu, Aug 12, 2021 at 7:39 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> > >\n> > > On Wed, Aug 11, 2021 at 10:47 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > > >\n> > > > On Tue, Aug 10, 2021 at 4:37 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> > > > >\n> > > > > The apply worker registers SharedFileSetDeleteOnProcExit() when\n> > > > > creating a file set to serialize the changes. When it raises an error\n> > > > > due to conflict during applying the change, the callback eventually\n> > > > > reports the temp file statistics but pgstat already shut down,\n> > > > > resulting in this assertion failure.\n> > > > >\n> > > >\n> > > > I think we can try to fix this by registering to clean up these files\n> > > > via before_shmem_exit() as done by Andres in commit 675c945394.\n> > > > Similar to that commit, we can change the function name\n> > > > SharedFileSetDeleteOnProcExit to SharedFileSetDeleteOnShmExit and\n> > > > register it via before_shmem_exit() instead of on_proc_exit(). Can you\n> > > > try that and see if it fixes the issue for you unless you have better\n> > > > ideas to try out?\n> > >\n> > > It seems to me that moving the shared fileset cleanup to\n> > > before_shmem_exit() is the right approach to fix this problem. The\n> > > issue is fixed by the attached patch.\n> >\n> > +1, the fix makes sense to me.\n> >\n>\n> I have also tested and fix works for me. The fix works because\n> pgstat_initialize() is called before we register clean up in\n> SharedFileSetInit(). I am not sure if we need an Assert to ensure that\n> and if so how we can do that? Any suggestions?\n\nI think that the assertion added by ee3f8d3d3ae ensures that\npgstat_initialize() is callbed before the callback for fileset cleanup\nis registered, no?\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Thu, 12 Aug 2021 16:43:11 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Thu, Aug 12, 2021 at 1:13 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Thu, Aug 12, 2021 at 3:16 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > On Thu, Aug 12, 2021 at 11:38 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> > >\n> > > On Thu, Aug 12, 2021 at 7:39 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> > > >\n> > > > On Wed, Aug 11, 2021 at 10:47 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > > > >\n> > > > > On Tue, Aug 10, 2021 at 4:37 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> > > > > >\n> > > > > > The apply worker registers SharedFileSetDeleteOnProcExit() when\n> > > > > > creating a file set to serialize the changes. When it raises an error\n> > > > > > due to conflict during applying the change, the callback eventually\n> > > > > > reports the temp file statistics but pgstat already shut down,\n> > > > > > resulting in this assertion failure.\n> > > > > >\n> > > > >\n> > > > > I think we can try to fix this by registering to clean up these files\n> > > > > via before_shmem_exit() as done by Andres in commit 675c945394.\n> > > > > Similar to that commit, we can change the function name\n> > > > > SharedFileSetDeleteOnProcExit to SharedFileSetDeleteOnShmExit and\n> > > > > register it via before_shmem_exit() instead of on_proc_exit(). Can you\n> > > > > try that and see if it fixes the issue for you unless you have better\n> > > > > ideas to try out?\n> > > >\n> > > > It seems to me that moving the shared fileset cleanup to\n> > > > before_shmem_exit() is the right approach to fix this problem. The\n> > > > issue is fixed by the attached patch.\n> > >\n> > > +1, the fix makes sense to me.\n> > >\n> >\n> > I have also tested and fix works for me. The fix works because\n> > pgstat_initialize() is called before we register clean up in\n> > SharedFileSetInit(). I am not sure if we need an Assert to ensure that\n> > and if so how we can do that? Any suggestions?\n>\n> I think that the assertion added by ee3f8d3d3ae ensures that\n> pgstat_initialize() is callbed before the callback for fileset cleanup\n> is registered, no?\n\nRight, it ensures that callback for fileset, is called after\npgstat_initialize() and before pgstat_shutdown.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 12 Aug 2021 13:42:24 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Thu, Aug 12, 2021 at 1:13 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Thu, Aug 12, 2021 at 3:16 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> >\n> > I have also tested and fix works for me. The fix works because\n> > pgstat_initialize() is called before we register clean up in\n> > SharedFileSetInit(). I am not sure if we need an Assert to ensure that\n> > and if so how we can do that? Any suggestions?\n>\n> I think that the assertion added by ee3f8d3d3ae ensures that\n> pgstat_initialize() is callbed before the callback for fileset cleanup\n> is registered, no?\n>\n\nI think I am missing something here, can you please explain?\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Thu, 12 Aug 2021 13:48:23 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "Hi,\n\nOn 2021-08-12 11:46:09 +0530, Amit Kapila wrote:\n> On Thu, Aug 12, 2021 at 11:38 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> > On Thu, Aug 12, 2021 at 7:39 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> > > It seems to me that moving the shared fileset cleanup to\n> > > before_shmem_exit() is the right approach to fix this problem. The\n> > > issue is fixed by the attached patch.\n> >\n> > +1, the fix makes sense to me.\n\nI'm not so sure. Why does sharedfileset have its own proc exit hook in the\nfirst place? ISTM that this should be dealt with using resowners, rathers than\na sharedfileset specific mechanism?\n\nThat said, I think it's fine to go for the ordering change in the short term.\n\n\n> I have also tested and fix works for me. The fix works because\n> pgstat_initialize() is called before we register clean up in\n> SharedFileSetInit(). I am not sure if we need an Assert to ensure that\n> and if so how we can do that? Any suggestions?\n\nI don't think we need to assert that - we'd see failures soon enough if\nthat rule were violated...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 12 Aug 2021 01:22:37 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "On Thu, Aug 12, 2021 at 1:52 PM Andres Freund <andres@anarazel.de> wrote:\n>\n> On 2021-08-12 11:46:09 +0530, Amit Kapila wrote:\n> > On Thu, Aug 12, 2021 at 11:38 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> > > On Thu, Aug 12, 2021 at 7:39 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> > > > It seems to me that moving the shared fileset cleanup to\n> > > > before_shmem_exit() is the right approach to fix this problem. The\n> > > > issue is fixed by the attached patch.\n> > >\n> > > +1, the fix makes sense to me.\n>\n> I'm not so sure. Why does sharedfileset have its own proc exit hook in the\n> first place? ISTM that this should be dealt with using resowners, rathers than\n> a sharedfileset specific mechanism?\n>\n\nThe underlying temporary files need to be closed at xact end but need\nto survive across transactions. These are registered with the resource\nowner via PathNameOpenTemporaryFile/PathNameCreateTemporaryFile and\nthen closed at xact end. So, we need a way to remove the files used by\nthe process (apply worker in this particular case) before process exit\nand used this proc_exit hook (possibly on the lines of\nAtProcExit_Files).\n\n> That said, I think it's fine to go for the ordering change in the short term.\n>\n>\n> > I have also tested and fix works for me. The fix works because\n> > pgstat_initialize() is called before we register clean up in\n> > SharedFileSetInit(). I am not sure if we need an Assert to ensure that\n> > and if so how we can do that? Any suggestions?\n>\n> I don't think we need to assert that - we'd see failures soon enough if\n> that rule were violated...\n>\n\nFair enough.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Thu, 12 Aug 2021 15:06:23 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "Hi,\n\nOn 2021-08-12 15:06:23 +0530, Amit Kapila wrote:\n> On Thu, Aug 12, 2021 at 1:52 PM Andres Freund <andres@anarazel.de> wrote:\n> > I'm not so sure. Why does sharedfileset have its own proc exit hook in the\n> > first place? ISTM that this should be dealt with using resowners, rathers than\n> > a sharedfileset specific mechanism?\n> >\n\n> The underlying temporary files need to be closed at xact end but need\n> to survive across transactions.\n\nWhy do they need to be closed at xact end? To avoid wasting memory due to too\nmany buffered files?\n\n\n> These are registered with the resource owner via\n> PathNameOpenTemporaryFile/PathNameCreateTemporaryFile and then closed\n> at xact end. So, we need a way to remove the files used by the process\n> (apply worker in this particular case) before process exit and used\n> this proc_exit hook (possibly on the lines of AtProcExit_Files).\n\nWhat I'm wondering is why it is a good idea to have a SharedFileSet specific\ncleanup mechanism. One that only operates on process lifetime level, rather\nthan something more granular. I get that the of the files here needs to be\nlonger than a transaction, but that can easily be addressed by having a longer\nlived resource owner.\n\nProcess lifetime may work well for the current worker.c, but even there it\ndoesn't seem optimal. One e.g. could easily imagine that we'd want to handle\nconnection errors or configuration changes without restarting the worker, in\nwhich case process lifetime obviously isn't a good idea anymore.\n\n\nI think SharedFileSetInit() needs a comment explaining that it needs to be\ncalled in a process-lifetime memory context if used without dsm\nsegments. Because otherwise SharedFileSetDeleteOnProcExit() will access\nalready freed memory (both for filesetlist and the SharedFileSet itself).\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 12 Aug 2021 05:48:19 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "Hi,\n\nOn 2021-08-12 05:48:19 -0700, Andres Freund wrote:\n> I think SharedFileSetInit() needs a comment explaining that it needs to be\n> called in a process-lifetime memory context if used without dsm\n> segments. Because otherwise SharedFileSetDeleteOnProcExit() will access\n> already freed memory (both for filesetlist and the SharedFileSet itself).\n\nOh. And I think it's not ok that SharedFileSetDeleteAll() unconditionally does\nSharedFileSetUnregister(). SharedFileSetUnregister() asserts out if there's no\nmatch, but DSM based sets are never entered into filesetlist. So one cannot\nhave a non-DSM and DSM set coexisting. Which seems surprising.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 12 Aug 2021 05:54:21 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "On Thu, Aug 12, 2021 at 6:18 PM Andres Freund <andres@anarazel.de> wrote:\n>\n> Hi,\n>\n> On 2021-08-12 15:06:23 +0530, Amit Kapila wrote:\n> > On Thu, Aug 12, 2021 at 1:52 PM Andres Freund <andres@anarazel.de> wrote:\n> > > I'm not so sure. Why does sharedfileset have its own proc exit hook in the\n> > > first place? ISTM that this should be dealt with using resowners, rathers than\n> > > a sharedfileset specific mechanism?\n> > >\n>\n> > The underlying temporary files need to be closed at xact end but need\n> > to survive across transactions.\n>\n> Why do they need to be closed at xact end? To avoid wasting memory due to too\n> many buffered files?\n>\n\nYes.\n\n>\n> > These are registered with the resource owner via\n> > PathNameOpenTemporaryFile/PathNameCreateTemporaryFile and then closed\n> > at xact end. So, we need a way to remove the files used by the process\n> > (apply worker in this particular case) before process exit and used\n> > this proc_exit hook (possibly on the lines of AtProcExit_Files).\n>\n> What I'm wondering is why it is a good idea to have a SharedFileSet specific\n> cleanup mechanism. One that only operates on process lifetime level, rather\n> than something more granular. I get that the of the files here needs to be\n> longer than a transaction, but that can easily be addressed by having a longer\n> lived resource owner.\n>\n> Process lifetime may work well for the current worker.c, but even there it\n> doesn't seem optimal. One e.g. could easily imagine that we'd want to handle\n> connection errors or configuration changes without restarting the worker, in\n> which case process lifetime obviously isn't a good idea anymore.\n>\n\nI don't deny that we can't make this at a more granular level. IIRC,\nat that time, we tried to follow AtProcExit_Files which cleans up temp\nfiles at proc exit and we needed something similar for temporary files\nused via SharedFileSet. I think we can extend this API but I guess it\nis better to then do it for dsm-based as well so that these get\ntracked via resowner.\n\n>\n> I think SharedFileSetInit() needs a comment explaining that it needs to be\n> called in a process-lifetime memory context if used without dsm\n> segments.\n>\n\nWe already have a comment about proc_exit clean up of files but will\nextend that a bit about memory context.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Fri, 13 Aug 2021 14:38:37 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Thu, Aug 12, 2021 at 6:24 PM Andres Freund <andres@anarazel.de> wrote:\n>\n> On 2021-08-12 05:48:19 -0700, Andres Freund wrote:\n> > I think SharedFileSetInit() needs a comment explaining that it needs to be\n> > called in a process-lifetime memory context if used without dsm\n> > segments. Because otherwise SharedFileSetDeleteOnProcExit() will access\n> > already freed memory (both for filesetlist and the SharedFileSet itself).\n>\n> Oh. And I think it's not ok that SharedFileSetDeleteAll() unconditionally does\n> SharedFileSetUnregister(). SharedFileSetUnregister() asserts out if there's no\n> match, but DSM based sets are never entered into filesetlist. So one cannot\n> have a non-DSM and DSM set coexisting. Which seems surprising.\n>\n\nOops, it should be allowed to have both non-DSM and DSM set\ncoexisting. I think we can remove Assert from\nSharedFileSetUnregister(). The other way could be to pass a parameter\nto SharedFileSetDeleteAll() to tell whether to unregister or not.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Fri, 13 Aug 2021 14:39:35 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "Hi,\n\n(dropping -committers to avoid moderation stalls due xposting to multiple lists -\nI find that more annoying than helpful)\n\nOn 2021-08-13 14:38:37 +0530, Amit Kapila wrote:\n> > What I'm wondering is why it is a good idea to have a SharedFileSet specific\n> > cleanup mechanism. One that only operates on process lifetime level, rather\n> > than something more granular. I get that the of the files here needs to be\n> > longer than a transaction, but that can easily be addressed by having a longer\n> > lived resource owner.\n> >\n> > Process lifetime may work well for the current worker.c, but even there it\n> > doesn't seem optimal. One e.g. could easily imagine that we'd want to handle\n> > connection errors or configuration changes without restarting the worker, in\n> > which case process lifetime obviously isn't a good idea anymore.\n> >\n> \n> I don't deny that we can't make this at a more granular level. IIRC,\n> at that time, we tried to follow AtProcExit_Files which cleans up temp\n> files at proc exit and we needed something similar for temporary files\n> used via SharedFileSet.\n\nThe comparison to AtProcExit_Files isn't convincing to me - normally temp\nfiles are cleaned up long before that via resowner cleanup.\n\nTo me the reuse of SharedFileSet for worker.c as executed seems like a bad\ndesign. As things stand there's little code shared between dsm/non-dsm shared\nfile sets. The cleanup semantics are entirely different. Several functions\ndon't work if used on the \"wrong kind\" of set (e.g. SharedFileSetAttach()).\n\n\n> I think we can extend this API but I guess it is better to then do it\n> for dsm-based as well so that these get tracked via resowner.\n\nDSM segments are resowner managed already, so it's not obvious that that'd buy\nus much? Although I guess there could be a few edge cases that'd look cleaner,\nbecause we could reliably trigger cleanup in the leader instead of relying on\ndsm detach hooks + refcounts to manage when a set is physically deleted?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 13 Aug 2021 08:59:40 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "On Fri, Aug 13, 2021 at 9:29 PM Andres Freund <andres@anarazel.de> wrote:\n\n> > I think we can extend this API but I guess it is better to then do it\n> > for dsm-based as well so that these get tracked via resowner.\n>\n> DSM segments are resowner managed already, so it's not obvious that that'd buy\n> us much? Although I guess there could be a few edge cases that'd look cleaner,\n> because we could reliably trigger cleanup in the leader instead of relying on\n> dsm detach hooks + refcounts to manage when a set is physically deleted?\n>\n\nIn an off-list discussion with Thomas and Amit, we tried to discuss\nhow to clean up the shared files set in the current use case. Thomas\nsuggested that instead of using individual shared fileset for storing\nthe data for each XID why don't we just create a single shared fileset\nfor complete worker lifetime and when the worker is exiting we can\njust remove that shared fileset. And for storing XID data, we can\njust create the files under the same shared fileset and delete those\nfiles when we longer need them. I like this idea and it looks much\ncleaner, after this, we can get rid of the special cleanup mechanism\nusing 'filesetlist'. I have attached a patch for the same.\n\n--\nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Mon, 16 Aug 2021 20:17:47 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Mon, Aug 16, 2021 at 8:18 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Fri, Aug 13, 2021 at 9:29 PM Andres Freund <andres@anarazel.de> wrote:\n>\n> > > I think we can extend this API but I guess it is better to then do it\n> > > for dsm-based as well so that these get tracked via resowner.\n> >\n> > DSM segments are resowner managed already, so it's not obvious that that'd buy\n> > us much? Although I guess there could be a few edge cases that'd look cleaner,\n> > because we could reliably trigger cleanup in the leader instead of relying on\n> > dsm detach hooks + refcounts to manage when a set is physically deleted?\n> >\n>\n> In an off-list discussion with Thomas and Amit, we tried to discuss\n> how to clean up the shared files set in the current use case. Thomas\n> suggested that instead of using individual shared fileset for storing\n> the data for each XID why don't we just create a single shared fileset\n> for complete worker lifetime and when the worker is exiting we can\n> just remove that shared fileset. And for storing XID data, we can\n> just create the files under the same shared fileset and delete those\n> files when we longer need them. I like this idea and it looks much\n> cleaner, after this, we can get rid of the special cleanup mechanism\n> using 'filesetlist'. I have attached a patch for the same.\n>\n\nIt seems to me that this idea would obviate any need for resource\nowners as we will have only one fileset now. I have a few initial\ncomments on the patch:\n\n1.\n+ /* do cleanup on worker exit (e.g. after DROP SUBSCRIPTION) */\n+ on_shmem_exit(worker_cleanup, (Datum) 0);\n\nIt should be registered with before_shmem_exit() hook to allow sending\nstats for file removal.\n\n2. After these changes, the comments atop stream_open_file and\nSharedFileSetInit need to be changed.\n\n3. In function subxact_info_write(), we are computing subxact file\npath twice which doesn't seem to be required.\n\n4.\n+ if (missing_ok)\n+ return NULL;\n ereport(ERROR,\n (errcode_for_file_access(),\n- errmsg(\"could not open temporary file \\\"%s\\\" from BufFile \\\"%s\\\": %m\",\n+ errmsg(\"could not open temporary file \\\"%s\\\" from BufFile \\\"%s\\\": %m\",\n segment_name, name)));\n\nThere seems to be a formatting issue with errmsg. Also, it is better\nto keep an empty line before ereport.\n\n5. How can we provide a strict mechanism to not allow to use dsm APIs\nfor non-dsm FileSet? One idea could be that we can have a variable\n(probably bool) in SharedFileSet structure which will be initialized\nin SharedFileSetInit based on whether the caller has provided dsm\nsegment. Then in other DSM-based APIs, we can check if it is used for\nthe wrong type.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 17 Aug 2021 10:54:30 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Tue, Aug 17, 2021 at 10:54 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Mon, Aug 16, 2021 at 8:18 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n> > On Fri, Aug 13, 2021 at 9:29 PM Andres Freund <andres@anarazel.de> wrote:\n> >\n> > > > I think we can extend this API but I guess it is better to then do it\n> > > > for dsm-based as well so that these get tracked via resowner.\n> > >\n> > > DSM segments are resowner managed already, so it's not obvious that that'd buy\n> > > us much? Although I guess there could be a few edge cases that'd look cleaner,\n> > > because we could reliably trigger cleanup in the leader instead of relying on\n> > > dsm detach hooks + refcounts to manage when a set is physically deleted?\n> > >\n> >\n> > In an off-list discussion with Thomas and Amit, we tried to discuss\n> > how to clean up the shared files set in the current use case. Thomas\n> > suggested that instead of using individual shared fileset for storing\n> > the data for each XID why don't we just create a single shared fileset\n> > for complete worker lifetime and when the worker is exiting we can\n> > just remove that shared fileset. And for storing XID data, we can\n> > just create the files under the same shared fileset and delete those\n> > files when we longer need them. I like this idea and it looks much\n> > cleaner, after this, we can get rid of the special cleanup mechanism\n> > using 'filesetlist'. I have attached a patch for the same.\n> >\n>\n> It seems to me that this idea would obviate any need for resource\n> owners as we will have only one fileset now. I have a few initial\n> comments on the patch:\n>\n\nOne more comment:\n@@ -2976,39 +2952,17 @@ subxact_info_write(Oid subid, TransactionId xid)\n..\n+ /* Try to open the subxact file, if it doesn't exist then create it */\n+ fd = BufFileOpenShared(xidfileset, path, O_RDWR, true);\n+ if (fd == NULL)\n+ fd = BufFileCreateShared(xidfileset, path);\n..\n\nInstead of trying to create the file here based on whether it exists\nor not, can't we create it in subxact_info_add where we are first time\nallocating memory for subxacts? If that works then in the above code,\nthe file should always exist.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 17 Aug 2021 12:06:37 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Tue, Aug 17, 2021 at 12:06 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> One more comment:\n> @@ -2976,39 +2952,17 @@ subxact_info_write(Oid subid, TransactionId xid)\n> ..\n> + /* Try to open the subxact file, if it doesn't exist then create it */\n> + fd = BufFileOpenShared(xidfileset, path, O_RDWR, true);\n> + if (fd == NULL)\n> + fd = BufFileCreateShared(xidfileset, path);\n> ..\n>\n> Instead of trying to create the file here based on whether it exists\n> or not, can't we create it in subxact_info_add where we are first time\n> allocating memory for subxacts? If that works then in the above code,\n> the file should always exist.\n\nOne problem with this approach is that for now we delay creating the\nsubxact file till the end of the stream and if by end of the stream\nall the subtransactions got aborted within the same stream then we\ndon't even create that file. But with this suggestion, we will always\ncreate the file as soon as we get the first subtransaction.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 17 Aug 2021 13:07:45 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Tue, Aug 17, 2021 at 10:54 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Mon, Aug 16, 2021 at 8:18 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n> > On Fri, Aug 13, 2021 at 9:29 PM Andres Freund <andres@anarazel.de> wrote:\n> >\n> > > > I think we can extend this API but I guess it is better to then do it\n> > > > for dsm-based as well so that these get tracked via resowner.\n> > >\n> > > DSM segments are resowner managed already, so it's not obvious that that'd buy\n> > > us much? Although I guess there could be a few edge cases that'd look cleaner,\n> > > because we could reliably trigger cleanup in the leader instead of relying on\n> > > dsm detach hooks + refcounts to manage when a set is physically deleted?\n> > >\n> >\n> > In an off-list discussion with Thomas and Amit, we tried to discuss\n> > how to clean up the shared files set in the current use case. Thomas\n> > suggested that instead of using individual shared fileset for storing\n> > the data for each XID why don't we just create a single shared fileset\n> > for complete worker lifetime and when the worker is exiting we can\n> > just remove that shared fileset. And for storing XID data, we can\n> > just create the files under the same shared fileset and delete those\n> > files when we longer need them. I like this idea and it looks much\n> > cleaner, after this, we can get rid of the special cleanup mechanism\n> > using 'filesetlist'. I have attached a patch for the same.\n> >\n>\n> It seems to me that this idea would obviate any need for resource\n> owners as we will have only one fileset now. I have a few initial\n> comments on the patch:\n>\n> 1.\n> + /* do cleanup on worker exit (e.g. after DROP SUBSCRIPTION) */\n> + on_shmem_exit(worker_cleanup, (Datum) 0);\n>\n> It should be registered with before_shmem_exit() hook to allow sending\n> stats for file removal.\n\nDone\n\n> 2. After these changes, the comments atop stream_open_file and\n> SharedFileSetInit need to be changed.\n\nDone\n\n> 3. In function subxact_info_write(), we are computing subxact file\n> path twice which doesn't seem to be required.\n\nFixed\n\n> 4.\n> + if (missing_ok)\n> + return NULL;\n> ereport(ERROR,\n> (errcode_for_file_access(),\n> - errmsg(\"could not open temporary file \\\"%s\\\" from BufFile \\\"%s\\\": %m\",\n> + errmsg(\"could not open temporary file \\\"%s\\\" from BufFile \\\"%s\\\": %m\",\n> segment_name, name)));\n>\n> There seems to be a formatting issue with errmsg. Also, it is better\n> to keep an empty line before ereport.\n\nDone\n\n> 5. How can we provide a strict mechanism to not allow to use dsm APIs\n> for non-dsm FileSet? One idea could be that we can have a variable\n> (probably bool) in SharedFileSet structure which will be initialized\n> in SharedFileSetInit based on whether the caller has provided dsm\n> segment. Then in other DSM-based APIs, we can check if it is used for\n> the wrong type.\n\nYeah, we can do something like that, can't we just use an existing\nvariable instead of adding new, e.g. refcnt is required only when\nmultiple processes are attached, so maybe if dsm segment is not passed\nthen we can keep refcnt as 0 and based on we can give an error. For\nexample, if we try to call SharedFileSetAttach for the SharedFileSet\nwhich has refcnt as 0 then we error out?\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Tue, 17 Aug 2021 13:30:06 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Tue, Aug 17, 2021 at 1:30 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Tue, Aug 17, 2021 at 10:54 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n>\n> > 5. How can we provide a strict mechanism to not allow to use dsm APIs\n> > for non-dsm FileSet? One idea could be that we can have a variable\n> > (probably bool) in SharedFileSet structure which will be initialized\n> > in SharedFileSetInit based on whether the caller has provided dsm\n> > segment. Then in other DSM-based APIs, we can check if it is used for\n> > the wrong type.\n>\n> Yeah, we can do something like that, can't we just use an existing\n> variable instead of adding new, e.g. refcnt is required only when\n> multiple processes are attached, so maybe if dsm segment is not passed\n> then we can keep refcnt as 0 and based on we can give an error. For\n> example, if we try to call SharedFileSetAttach for the SharedFileSet\n> which has refcnt as 0 then we error out?\n>\n\nBut as of now, we treat refcnt as 0 for SharedFileSet that is already\ndestroyed. See SharedFileSetAttach.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 17 Aug 2021 14:26:37 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "Hi,\n\nOn 2021-08-17 10:54:30 +0530, Amit Kapila wrote:\n> 5. How can we provide a strict mechanism to not allow to use dsm APIs\n> for non-dsm FileSet? One idea could be that we can have a variable\n> (probably bool) in SharedFileSet structure which will be initialized\n> in SharedFileSetInit based on whether the caller has provided dsm\n> segment. Then in other DSM-based APIs, we can check if it is used for\n> the wrong type.\n\nWell, isn't the issue here that it's not a shared file set in case you\nexplicitly don't want to share it? ISTM that the proper way to address\nthis would be to split out a FileSet from SharedFileSet that's then used\nfor worker.c and sharedfileset.c. Rather than making sharedfileset.c\nsupport a non-shared mode.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 17 Aug 2021 04:04:27 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix\n uninitialized use o" }, { "msg_contents": "Hi,\r\n\r\nI took a quick look at the v2 patch and noticed a typo.\r\n\r\n+ * backends and render it read-only. If missing_ok is true then it will return\r\n+ * NULL if file doesn not exist otherwise error.\r\n */\r\ndoesn not=> doesn't\r\n\r\nBest regards,\r\nHouzj\r\n\r\n\r\n", "msg_date": "Wed, 18 Aug 2021 01:16:50 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Wed, Aug 18, 2021 9:17 AM houzj.fnst@fujitsu.com wrote:\r\n> Hi,\r\n> \r\n> I took a quick look at the v2 patch and noticed a typo.\r\n> \r\n> + * backends and render it read-only. If missing_ok is true then it will return\r\n> + * NULL if file doesn not exist otherwise error.\r\n> */\r\n> doesn not=> doesn't\r\n>\r\n\r\nHere are some other comments:\r\n\r\n1).\r\n+BufFileOpenShared(SharedFileSet *fileset, const char *name, int mode,\r\n+\t\t\t\t bool missing_ok)\r\n {\r\n \tBufFile *file;\r\n \tchar\t\tsegment_name[MAXPGPATH];\r\n\t...\r\n\tfiles = palloc(sizeof(File) * capacity);\r\n\t...\r\n@@ -318,10 +320,15 @@ BufFileOpenShared(SharedFileSet *fileset, const char *name, int mode)\r\n \t * name.\r\n \t */\r\n \tif (nfiles == 0)\r\n+\t{\r\n+\t\tif (missing_ok)\r\n+\t\t\treturn NULL;\r\n+\r\n\r\nI think it might be better to pfree(files) when return NULL.\r\n\r\n\r\n2).\r\n \t/* Delete the subxact file and release the memory, if it exist */\r\n-\tif (ent->subxact_fileset)\r\n-\t{\r\n-\t\tsubxact_filename(path, subid, xid);\r\n-\t\tSharedFileSetDeleteAll(ent->subxact_fileset);\r\n-\t\tpfree(ent->subxact_fileset);\r\n-\t\tent->subxact_fileset = NULL;\r\n-\t}\r\n-\r\n-\t/* Remove the xid entry from the stream xid hash */\r\n-\thash_search(xidhash, (void *) &xid, HASH_REMOVE, NULL);\r\n+\tsubxact_filename(path, subid, xid);\r\n+\tSharedFileSetDelete(xidfileset, path, true);\r\n\r\nWithout the patch it doesn't throw an error if not exist,\r\nBut with the patch, it pass error_on_failure=true to SharedFileSetDelete().\r\nWas it intentional ?\r\n\r\nBest regards,\r\nHouzj\r\n\r\n\r\n", "msg_date": "Wed, 18 Aug 2021 02:52:57 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Wed, Aug 18, 2021 at 8:23 AM houzj.fnst@fujitsu.com\n<houzj.fnst@fujitsu.com> wrote:\n>\n> On Wed, Aug 18, 2021 9:17 AM houzj.fnst@fujitsu.com wrote:\n> > Hi,\n> >\n> > I took a quick look at the v2 patch and noticed a typo.\n> >\n> > + * backends and render it read-only. If missing_ok is true then it will return\n> > + * NULL if file doesn not exist otherwise error.\n> > */\n> > doesn not=> doesn't\n> >\n>\n> Here are some other comments:\n>\n> 1).\n> +BufFileOpenShared(SharedFileSet *fileset, const char *name, int mode,\n> + bool missing_ok)\n> {\n> BufFile *file;\n> char segment_name[MAXPGPATH];\n> ...\n> files = palloc(sizeof(File) * capacity);\n> ...\n> @@ -318,10 +320,15 @@ BufFileOpenShared(SharedFileSet *fileset, const char *name, int mode)\n> * name.\n> */\n> if (nfiles == 0)\n> + {\n> + if (missing_ok)\n> + return NULL;\n> +\n>\n> I think it might be better to pfree(files) when return NULL.\n>\n>\n> 2).\n> /* Delete the subxact file and release the memory, if it exist */\n> - if (ent->subxact_fileset)\n> - {\n> - subxact_filename(path, subid, xid);\n> - SharedFileSetDeleteAll(ent->subxact_fileset);\n> - pfree(ent->subxact_fileset);\n> - ent->subxact_fileset = NULL;\n> - }\n> -\n> - /* Remove the xid entry from the stream xid hash */\n> - hash_search(xidhash, (void *) &xid, HASH_REMOVE, NULL);\n> + subxact_filename(path, subid, xid);\n> + SharedFileSetDelete(xidfileset, path, true);\n>\n> Without the patch it doesn't throw an error if not exist,\n> But with the patch, it pass error_on_failure=true to SharedFileSetDelete().\n>\n\nDon't we need to use BufFileDeleteShared instead of\nSharedFileSetDelete as you have used to remove the changes file?\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Wed, 18 Aug 2021 09:30:09 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Wed, Aug 18, 2021 at 9:30 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Wed, Aug 18, 2021 at 8:23 AM houzj.fnst@fujitsu.com\n> <houzj.fnst@fujitsu.com> wrote:\n> >\n> > On Wed, Aug 18, 2021 9:17 AM houzj.fnst@fujitsu.com wrote:\n> > > Hi,\n> > >\n> > > I took a quick look at the v2 patch and noticed a typo.\n> > >\n> > > + * backends and render it read-only. If missing_ok is true then it will return\n> > > + * NULL if file doesn not exist otherwise error.\n> > > */\n> > > doesn not=> doesn't\n> > >\n> >\n> > Here are some other comments:\n> >\n> > 1).\n> > +BufFileOpenShared(SharedFileSet *fileset, const char *name, int mode,\n> > + bool missing_ok)\n> > {\n> > BufFile *file;\n> > char segment_name[MAXPGPATH];\n> > ...\n> > files = palloc(sizeof(File) * capacity);\n> > ...\n> > @@ -318,10 +320,15 @@ BufFileOpenShared(SharedFileSet *fileset, const char *name, int mode)\n> > * name.\n> > */\n> > if (nfiles == 0)\n> > + {\n> > + if (missing_ok)\n> > + return NULL;\n> > +\n> >\n> > I think it might be better to pfree(files) when return NULL.\n> >\n> >\n> > 2).\n> > /* Delete the subxact file and release the memory, if it exist */\n> > - if (ent->subxact_fileset)\n> > - {\n> > - subxact_filename(path, subid, xid);\n> > - SharedFileSetDeleteAll(ent->subxact_fileset);\n> > - pfree(ent->subxact_fileset);\n> > - ent->subxact_fileset = NULL;\n> > - }\n> > -\n> > - /* Remove the xid entry from the stream xid hash */\n> > - hash_search(xidhash, (void *) &xid, HASH_REMOVE, NULL);\n> > + subxact_filename(path, subid, xid);\n> > + SharedFileSetDelete(xidfileset, path, true);\n> >\n> > Without the patch it doesn't throw an error if not exist,\n> > But with the patch, it pass error_on_failure=true to SharedFileSetDelete().\n> >\n>\n> Don't we need to use BufFileDeleteShared instead of\n> SharedFileSetDelete as you have used to remove the changes file?\n\nYeah, it should be BufFileDeleteShared.\n\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 18 Aug 2021 09:47:40 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Tue, Aug 17, 2021 at 4:34 PM Andres Freund <andres@anarazel.de> wrote:\n>\n> On 2021-08-17 10:54:30 +0530, Amit Kapila wrote:\n> > 5. How can we provide a strict mechanism to not allow to use dsm APIs\n> > for non-dsm FileSet? One idea could be that we can have a variable\n> > (probably bool) in SharedFileSet structure which will be initialized\n> > in SharedFileSetInit based on whether the caller has provided dsm\n> > segment. Then in other DSM-based APIs, we can check if it is used for\n> > the wrong type.\n>\n> Well, isn't the issue here that it's not a shared file set in case you\n> explicitly don't want to share it? ISTM that the proper way to address\n> this would be to split out a FileSet from SharedFileSet that's then used\n> for worker.c and sharedfileset.c.\n>\n\nOkay, but note that to accomplish the same, we need to tweak the\nBufFile (buffile.c) APIs as well so that they can work with FileSet.\nAs per the initial analysis, there doesn't seem to be any problem with\nthat though.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Wed, 18 Aug 2021 11:24:01 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Wed, Aug 18, 2021 at 11:24 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Tue, Aug 17, 2021 at 4:34 PM Andres Freund <andres@anarazel.de> wrote:\n> >\n> > On 2021-08-17 10:54:30 +0530, Amit Kapila wrote:\n> > > 5. How can we provide a strict mechanism to not allow to use dsm APIs\n> > > for non-dsm FileSet? One idea could be that we can have a variable\n> > > (probably bool) in SharedFileSet structure which will be initialized\n> > > in SharedFileSetInit based on whether the caller has provided dsm\n> > > segment. Then in other DSM-based APIs, we can check if it is used for\n> > > the wrong type.\n> >\n> > Well, isn't the issue here that it's not a shared file set in case you\n> > explicitly don't want to share it? ISTM that the proper way to address\n> > this would be to split out a FileSet from SharedFileSet that's then used\n> > for worker.c and sharedfileset.c.\n> >\n>\n> Okay, but note that to accomplish the same, we need to tweak the\n> BufFile (buffile.c) APIs as well so that they can work with FileSet.\n> As per the initial analysis, there doesn't seem to be any problem with\n> that though.\n\nI was looking into this, so if we want to do that I think the outline\nwill look like this\n\n- There will be a fileset.c and fileset.h files, and we will expose a\nnew structure FileSet, which will be the same as SharedFileSet, except\nmutext and refcount. The fileset.c will expose FileSetInit(),\nFileSetCreate(), FileSetOpen(), FileSetDelete() and FileSetDeleteAll()\ninterfaces.\n\n- sharefileset.c will internally call the fileset.c's interfaces. The\nSharedFileSet structure will also contain FileSet and other members\ni.e. mutex and refcount.\n\n- the buffile.c's interfaces which are ending with Shared e.g.\nBufFileCreateShared, BufFileOpenShared, should be converted to\nBufFileCreate and\nBufFileOpen respectively. And the input to these interfaces can be\nconverted to FileSet instead of SharedFileSet.\n\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 18 Aug 2021 15:45:14 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Wed, Aug 18, 2021 at 3:45 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Wed, Aug 18, 2021 at 11:24 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > On Tue, Aug 17, 2021 at 4:34 PM Andres Freund <andres@anarazel.de> wrote:\n> > >\n> > > On 2021-08-17 10:54:30 +0530, Amit Kapila wrote:\n> > > > 5. How can we provide a strict mechanism to not allow to use dsm APIs\n> > > > for non-dsm FileSet? One idea could be that we can have a variable\n> > > > (probably bool) in SharedFileSet structure which will be initialized\n> > > > in SharedFileSetInit based on whether the caller has provided dsm\n> > > > segment. Then in other DSM-based APIs, we can check if it is used for\n> > > > the wrong type.\n> > >\n> > > Well, isn't the issue here that it's not a shared file set in case you\n> > > explicitly don't want to share it? ISTM that the proper way to address\n> > > this would be to split out a FileSet from SharedFileSet that's then used\n> > > for worker.c and sharedfileset.c.\n> > >\n> >\n> > Okay, but note that to accomplish the same, we need to tweak the\n> > BufFile (buffile.c) APIs as well so that they can work with FileSet.\n> > As per the initial analysis, there doesn't seem to be any problem with\n> > that though.\n>\n> I was looking into this, so if we want to do that I think the outline\n> will look like this\n>\n> - There will be a fileset.c and fileset.h files, and we will expose a\n> new structure FileSet, which will be the same as SharedFileSet, except\n> mutext and refcount. The fileset.c will expose FileSetInit(),\n> FileSetCreate(), FileSetOpen(), FileSetDelete() and FileSetDeleteAll()\n> interfaces.\n>\n> - sharefileset.c will internally call the fileset.c's interfaces. The\n> SharedFileSet structure will also contain FileSet and other members\n> i.e. mutex and refcount.\n>\n> - the buffile.c's interfaces which are ending with Shared e.g.\n> BufFileCreateShared, BufFileOpenShared, should be converted to\n> BufFileCreate and\n> BufFileOpen respectively.\n>\n\nThe other alternative to name buffile APIs could be\nBufFileCreateFileSet, BufFileOpenFileSet, etc.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Thu, 19 Aug 2021 09:53:43 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Wed, Aug 18, 2021 at 3:45 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Wed, Aug 18, 2021 at 11:24 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > On Tue, Aug 17, 2021 at 4:34 PM Andres Freund <andres@anarazel.de> wrote:\n> > >\n> > > On 2021-08-17 10:54:30 +0530, Amit Kapila wrote:\n> > > > 5. How can we provide a strict mechanism to not allow to use dsm APIs\n> > > > for non-dsm FileSet? One idea could be that we can have a variable\n> > > > (probably bool) in SharedFileSet structure which will be initialized\n> > > > in SharedFileSetInit based on whether the caller has provided dsm\n> > > > segment. Then in other DSM-based APIs, we can check if it is used for\n> > > > the wrong type.\n> > >\n> > > Well, isn't the issue here that it's not a shared file set in case you\n> > > explicitly don't want to share it? ISTM that the proper way to address\n> > > this would be to split out a FileSet from SharedFileSet that's then used\n> > > for worker.c and sharedfileset.c.\n> > >\n> >\n> > Okay, but note that to accomplish the same, we need to tweak the\n> > BufFile (buffile.c) APIs as well so that they can work with FileSet.\n> > As per the initial analysis, there doesn't seem to be any problem with\n> > that though.\n>\n> I was looking into this, so if we want to do that I think the outline\n> will look like this\n>\n> - There will be a fileset.c and fileset.h files, and we will expose a\n> new structure FileSet, which will be the same as SharedFileSet, except\n> mutext and refcount. The fileset.c will expose FileSetInit(),\n> FileSetCreate(), FileSetOpen(), FileSetDelete() and FileSetDeleteAll()\n> interfaces.\n>\n> - sharefileset.c will internally call the fileset.c's interfaces. The\n> SharedFileSet structure will also contain FileSet and other members\n> i.e. mutex and refcount.\n>\n> - the buffile.c's interfaces which are ending with Shared e.g.\n> BufFileCreateShared, BufFileOpenShared, should be converted to\n> BufFileCreate and\n> BufFileOpen respectively. And the input to these interfaces can be\n> converted to FileSet instead of SharedFileSet.\n\nHere is the first draft based on the idea we discussed, 0001, splits\nsharedfileset.c in sharedfileset.c and fileset.c and 0002 is same\npatch I submitted earlier(use single fileset throughout the worker),\njust it is rebased on top of 0001. Please let me know your thoughts.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Sat, 21 Aug 2021 18:08:17 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Sat, Aug 21, 2021 8:38 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\r\n> On Wed, Aug 18, 2021 at 3:45 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\r\n> > I was looking into this, so if we want to do that I think the outline\r\n> > will look like this\r\n> >\r\n> > - There will be a fileset.c and fileset.h files, and we will expose a\r\n> > new structure FileSet, which will be the same as SharedFileSet, except\r\n> > mutext and refcount. The fileset.c will expose FileSetInit(),\r\n> > FileSetCreate(), FileSetOpen(), FileSetDelete() and FileSetDeleteAll()\r\n> > interfaces.\r\n> >\r\n> > - sharefileset.c will internally call the fileset.c's interfaces. The\r\n> > SharedFileSet structure will also contain FileSet and other members\r\n> > i.e. mutex and refcount.\r\n> >\r\n> > - the buffile.c's interfaces which are ending with Shared e.g.\r\n> > BufFileCreateShared, BufFileOpenShared, should be converted to\r\n> > BufFileCreate and BufFileOpen respectively. And the input to these\r\n> > interfaces can be converted to FileSet instead of SharedFileSet.\r\n> \r\n> Here is the first draft based on the idea we discussed, 0001, splits\r\n> sharedfileset.c in sharedfileset.c and fileset.c and 0002 is same patch I\r\n> submitted earlier(use single fileset throughout the worker), just it is rebased on\r\n> top of 0001. Please let me know your thoughts.\r\n\r\nHi,\r\n\r\nHere are some comments for the new version patches.\r\n\r\n1)\r\n+\tTempTablespacePath(tempdirpath, tablespace);\r\n+\tsnprintf(path, MAXPGPATH, \"%s/%s%lu.%u.sharedfileset\",\r\n+\t\t\t tempdirpath, PG_TEMP_FILE_PREFIX,\r\n+\t\t\t (unsigned long) fileset->creator_pid, fileset->number);\r\n\r\ndo we need to use different filename for shared and un-shared fileset ?\r\n\r\n2)\r\nI think we can remove or adjust the following comments in sharedfileset.c.\r\n\r\n----\r\n * SharedFileSets can be used by backends when the temporary files need to be\r\n * opened/closed multiple times and the underlying files need to survive across\r\n * transactions.\r\n----\r\n * We can also use this interface if the temporary files are used only by\r\n * single backend but the files need to be opened and closed multiple times\r\n * and also the underlying files need to survive across transactions. For\r\n----\r\n\r\n3)\r\nThe 0002 patch still used the word \"shared fileset\" in some places, I think we\r\nshould change it to \"fileset\".\r\n\r\n4)\r\n-extern File SharedFileSetCreate(SharedFileSet *fileset, const char *name);\r\n-extern File SharedFileSetOpen(SharedFileSet *fileset, const char *name,\r\n-\t\t\t\t\t\t\t int mode);\r\n-extern bool SharedFileSetDelete(SharedFileSet *fileset, const char *name,\r\n-\t\t\t\t\t\t\t\tbool error_on_failure);\r\n extern void SharedFileSetDeleteAll(SharedFileSet *fileset);\r\n-extern void SharedFileSetUnregister(SharedFileSet *input_fileset);\r\n\r\nI noticed the patch delete part of public api, is it better to keep the old api and\r\nlet them invoke new api internally ? Having said that, I didn’t find any open source\r\nextension use these old api, so it might be fine to delete them.\r\n\r\nBest regards,\r\nHou zj\r\n", "msg_date": "Mon, 23 Aug 2021 03:41:22 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Mon, Aug 23, 2021 at 9:11 AM houzj.fnst@fujitsu.com\n<houzj.fnst@fujitsu.com> wrote:\n\n> 4)\n> -extern File SharedFileSetCreate(SharedFileSet *fileset, const char *name);\n> -extern File SharedFileSetOpen(SharedFileSet *fileset, const char *name,\n> - int mode);\n> -extern bool SharedFileSetDelete(SharedFileSet *fileset, const char *name,\n> - bool error_on_failure);\n> extern void SharedFileSetDeleteAll(SharedFileSet *fileset);\n> -extern void SharedFileSetUnregister(SharedFileSet *input_fileset);\n>\n> I noticed the patch delete part of public api, is it better to keep the old api and\n> let them invoke new api internally ? Having said that, I didn’t find any open source\n> extension use these old api, so it might be fine to delete them.\n\nRight, those were internally used by buffile.c but now we have changed\nbuffile.c to directly use the fileset interfaces, so we better remove\nthem.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 23 Aug 2021 09:52:50 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Mon, Aug 23, 2021 at 9:53 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Mon, Aug 23, 2021 at 9:11 AM houzj.fnst@fujitsu.com\n> <houzj.fnst@fujitsu.com> wrote:\n>\n> > 4)\n> > -extern File SharedFileSetCreate(SharedFileSet *fileset, const char *name);\n> > -extern File SharedFileSetOpen(SharedFileSet *fileset, const char *name,\n> > - int mode);\n> > -extern bool SharedFileSetDelete(SharedFileSet *fileset, const char *name,\n> > - bool error_on_failure);\n> > extern void SharedFileSetDeleteAll(SharedFileSet *fileset);\n> > -extern void SharedFileSetUnregister(SharedFileSet *input_fileset);\n> >\n> > I noticed the patch delete part of public api, is it better to keep the old api and\n> > let them invoke new api internally ? Having said that, I didn’t find any open source\n> > extension use these old api, so it might be fine to delete them.\n>\n> Right, those were internally used by buffile.c but now we have changed\n> buffile.c to directly use the fileset interfaces, so we better remove\n> them.\n>\n\nI also don't see any reason to keep those exposed from\nsharedfileset.h. I see that even in the original commit dc6c4c9dc2,\nthese APIs seem to be introduced to be used by buffile. Andres/Thomas,\ndo let us know if you think otherwise?\n\nOne more comment:\nI think v1-0001-Sharedfileset-refactoring doesn't have a way for\ncleaning up worker.c temporary files on error/exit. It is better to\nhave that to make it an independent patch.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Mon, 23 Aug 2021 11:43:10 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat: Bring\n up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Mon, Aug 23, 2021 at 11:43 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Mon, Aug 23, 2021 at 9:53 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n> > On Mon, Aug 23, 2021 at 9:11 AM houzj.fnst@fujitsu.com\n> > <houzj.fnst@fujitsu.com> wrote:\n> >\n> > > 4)\n> > > -extern File SharedFileSetCreate(SharedFileSet *fileset, const char *name);\n> > > -extern File SharedFileSetOpen(SharedFileSet *fileset, const char *name,\n> > > - int mode);\n> > > -extern bool SharedFileSetDelete(SharedFileSet *fileset, const char *name,\n> > > - bool error_on_failure);\n> > > extern void SharedFileSetDeleteAll(SharedFileSet *fileset);\n> > > -extern void SharedFileSetUnregister(SharedFileSet *input_fileset);\n> > >\n> > > I noticed the patch delete part of public api, is it better to keep the old api and\n> > > let them invoke new api internally ? Having said that, I didn’t find any open source\n> > > extension use these old api, so it might be fine to delete them.\n> >\n> > Right, those were internally used by buffile.c but now we have changed\n> > buffile.c to directly use the fileset interfaces, so we better remove\n> > them.\n> >\n>\n> I also don't see any reason to keep those exposed from\n> sharedfileset.h. I see that even in the original commit dc6c4c9dc2,\n> these APIs seem to be introduced to be used by buffile. Andres/Thomas,\n> do let us know if you think otherwise?\n>\n> One more comment:\n> I think v1-0001-Sharedfileset-refactoring doesn't have a way for\n> cleaning up worker.c temporary files on error/exit. It is better to\n> have that to make it an independent patch.\n\nI think we should handle that in worker.c itself, by adding a\nbefore_dsm_detach function before_shmem_exit right? Or you are\nthinking that in FileSetInit, we keep the mechanism of filesetlist\nlike we were doing in SharedFileSetInit? I think that will just add\nunnecessary complexity in the first patch which will eventually go\naway in the second patch. And if we do that then SharedFileSetInit\ncan not directly use the FileSetInit, otherwise, the dsm based fileset\nwill also get registered for cleanup in filesetlist so for that we\nmight need to pass one parameter to the FileSetInit() that whether to\nregister for cleanup or not and that will again not look clean because\nnow we are again adding the conditional cleanup, IMHO that is the same\nproblem what we are trying to cleanup in SharedFileSetInit by\nintroducing a new FileSetInit.\n\nI think what we can do is, introduce a new function\nFileSetInitInternal(), that will do what FileSetInit() is doing today\nand now both SharedFileSetInit() and the FileSetInit() will call this\nfunction, and along with that SharedFileSetInit(), will register the\ndsm based cleanup and FileSetInit() will do the filesetlist based\ncleanup. But IMHO, we should try to go in this direction only if we\nare sure that we want to commit the first patch and not the second.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 23 Aug 2021 12:52:04 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Sat, Aug 21, 2021 at 9:38 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Wed, Aug 18, 2021 at 3:45 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n> > On Wed, Aug 18, 2021 at 11:24 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > >\n> > > On Tue, Aug 17, 2021 at 4:34 PM Andres Freund <andres@anarazel.de> wrote:\n> > > >\n> > > > On 2021-08-17 10:54:30 +0530, Amit Kapila wrote:\n> > > > > 5. How can we provide a strict mechanism to not allow to use dsm APIs\n> > > > > for non-dsm FileSet? One idea could be that we can have a variable\n> > > > > (probably bool) in SharedFileSet structure which will be initialized\n> > > > > in SharedFileSetInit based on whether the caller has provided dsm\n> > > > > segment. Then in other DSM-based APIs, we can check if it is used for\n> > > > > the wrong type.\n> > > >\n> > > > Well, isn't the issue here that it's not a shared file set in case you\n> > > > explicitly don't want to share it? ISTM that the proper way to address\n> > > > this would be to split out a FileSet from SharedFileSet that's then used\n> > > > for worker.c and sharedfileset.c.\n> > > >\n> > >\n> > > Okay, but note that to accomplish the same, we need to tweak the\n> > > BufFile (buffile.c) APIs as well so that they can work with FileSet.\n> > > As per the initial analysis, there doesn't seem to be any problem with\n> > > that though.\n> >\n> > I was looking into this, so if we want to do that I think the outline\n> > will look like this\n> >\n> > - There will be a fileset.c and fileset.h files, and we will expose a\n> > new structure FileSet, which will be the same as SharedFileSet, except\n> > mutext and refcount. The fileset.c will expose FileSetInit(),\n> > FileSetCreate(), FileSetOpen(), FileSetDelete() and FileSetDeleteAll()\n> > interfaces.\n> >\n> > - sharefileset.c will internally call the fileset.c's interfaces. The\n> > SharedFileSet structure will also contain FileSet and other members\n> > i.e. mutex and refcount.\n> >\n> > - the buffile.c's interfaces which are ending with Shared e.g.\n> > BufFileCreateShared, BufFileOpenShared, should be converted to\n> > BufFileCreate and\n> > BufFileOpen respectively. And the input to these interfaces can be\n> > converted to FileSet instead of SharedFileSet.\n>\n> Here is the first draft based on the idea we discussed, 0001, splits\n> sharedfileset.c in sharedfileset.c and fileset.c and 0002 is same\n> patch I submitted earlier(use single fileset throughout the worker),\n> just it is rebased on top of 0001. Please let me know your thoughts.\n\nHere are some comments on 0001 patch:\n\n+/*\n+ * Initialize a space for temporary files. This API can be used by shared\n+ * fileset as well as if the temporary files are used only by single backend\n+ * but the files need to be opened and closed multiple times and also the\n+ * underlying files need to survive across transactions.\n+ *\n+ * Files will be distributed over the tablespaces configured in\n+ * temp_tablespaces.\n+ *\n+ * Under the covers the set is one or more directories which will eventually\n+ * be deleted.\n+ */\n\nI think it's better to mention cleaning up here like we do in the\ncomment of SharedFileSetInit().\n\n---\nI think we need to clean up both stream_fileset and subxact_fileset on\nproc exit. In 0002 patch cleans up the fileset but I think we need to\ndo that also in 0001 patch.\n\n---\nThere still are some comments using \"shared fileset\" in both buffile.c\nand worker.c.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Mon, 23 Aug 2021 16:37:27 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized\n use o" }, { "msg_contents": "On Mon, Aug 23, 2021 at 12:52 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Mon, Aug 23, 2021 at 11:43 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > On Mon, Aug 23, 2021 at 9:53 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> > >\n> > > On Mon, Aug 23, 2021 at 9:11 AM houzj.fnst@fujitsu.com\n> > > <houzj.fnst@fujitsu.com> wrote:\n> > >\n> > > > 4)\n> > > > -extern File SharedFileSetCreate(SharedFileSet *fileset, const char *name);\n> > > > -extern File SharedFileSetOpen(SharedFileSet *fileset, const char *name,\n> > > > - int mode);\n> > > > -extern bool SharedFileSetDelete(SharedFileSet *fileset, const char *name,\n> > > > - bool error_on_failure);\n> > > > extern void SharedFileSetDeleteAll(SharedFileSet *fileset);\n> > > > -extern void SharedFileSetUnregister(SharedFileSet *input_fileset);\n> > > >\n> > > > I noticed the patch delete part of public api, is it better to keep the old api and\n> > > > let them invoke new api internally ? Having said that, I didn’t find any open source\n> > > > extension use these old api, so it might be fine to delete them.\n> > >\n> > > Right, those were internally used by buffile.c but now we have changed\n> > > buffile.c to directly use the fileset interfaces, so we better remove\n> > > them.\n> > >\n> >\n> > I also don't see any reason to keep those exposed from\n> > sharedfileset.h. I see that even in the original commit dc6c4c9dc2,\n> > these APIs seem to be introduced to be used by buffile. Andres/Thomas,\n> > do let us know if you think otherwise?\n> >\n> > One more comment:\n> > I think v1-0001-Sharedfileset-refactoring doesn't have a way for\n> > cleaning up worker.c temporary files on error/exit. It is better to\n> > have that to make it an independent patch.\n>\n> I think we should handle that in worker.c itself, by adding a\n> before_dsm_detach function before_shmem_exit right?\n>\n\nYeah, I thought of handling it in worker.c similar to what you've in 0002 patch.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Mon, 23 Aug 2021 13:43:01 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Mon, Aug 23, 2021 at 1:43 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\nNote: merge comments from multiple mails\n\n> > I think we should handle that in worker.c itself, by adding a\n> > before_dsm_detach function before_shmem_exit right?\n> >\n>\n> Yeah, I thought of handling it in worker.c similar to what you've in 0002 patch.\n>\n\nI have done handling in worker.c\n\nOn Mon, Aug 23, 2021 at 9:11 AM houzj.fnst@fujitsu.com\n<houzj.fnst@fujitsu.com> wrote:\n>\n> On Sat, Aug 21, 2021 8:38 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> 1)\n> + TempTablespacePath(tempdirpath, tablespace);\n> + snprintf(path, MAXPGPATH, \"%s/%s%lu.%u.sharedfileset\",\n> + tempdirpath, PG_TEMP_FILE_PREFIX,\n> + (unsigned long) fileset->creator_pid, fileset->number);\n>\n> do we need to use different filename for shared and un-shared fileset ?\n\nI was also thinking about the same, does it make sense to name it just\n\"\"%s/%s%lu.%u.fileset\"?\n\nOn Mon, Aug 23, 2021 at 1:08 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n\n> Here are some comments on 0001 patch:\n>\n> +/*\n> + * Initialize a space for temporary files. This API can be used by shared\n> + * fileset as well as if the temporary files are used only by single backend\n> + * but the files need to be opened and closed multiple times and also the\n> + * underlying files need to survive across transactions.\n> + *\n> + * Files will be distributed over the tablespaces configured in\n> + * temp_tablespaces.\n> + *\n> + * Under the covers the set is one or more directories which will eventually\n> + * be deleted.\n> + */\n>\n> I think it's better to mention cleaning up here like we do in the\n> comment of SharedFileSetInit().\n\nRight, done\n\n>\n> ---\n> I think we need to clean up both stream_fileset and subxact_fileset on\n> proc exit. In 0002 patch cleans up the fileset but I think we need to\n> do that also in 0001 patch.\n\nDone\n\n> ---\n> There still are some comments using \"shared fileset\" in both buffile.c\n> and worker.c.\n\nDone\n\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Mon, 23 Aug 2021 15:13:19 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Mon, Aug 23, 2021 at 3:13 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Mon, Aug 23, 2021 at 1:43 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> Note: merge comments from multiple mails\n>\n> > > I think we should handle that in worker.c itself, by adding a\n> > > before_dsm_detach function before_shmem_exit right?\n> > >\n> >\n> > Yeah, I thought of handling it in worker.c similar to what you've in 0002 patch.\n> >\n>\n> I have done handling in worker.c\n>\n> On Mon, Aug 23, 2021 at 9:11 AM houzj.fnst@fujitsu.com\n> <houzj.fnst@fujitsu.com> wrote:\n> >\n> > On Sat, Aug 21, 2021 8:38 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n> > 1)\n> > + TempTablespacePath(tempdirpath, tablespace);\n> > + snprintf(path, MAXPGPATH, \"%s/%s%lu.%u.sharedfileset\",\n> > + tempdirpath, PG_TEMP_FILE_PREFIX,\n> > + (unsigned long) fileset->creator_pid, fileset->number);\n> >\n> > do we need to use different filename for shared and un-shared fileset ?\n>\n> I was also thinking about the same, does it make sense to name it just\n> \"\"%s/%s%lu.%u.fileset\"?\n>\n\nI think it is reasonable to use .fileset as proposed by you.\n\nFew other comments:\n=================\n1.\n+ /*\n+ * Register before-shmem-exit hook to ensure filesets are dropped while we\n+ * can still report stats for underlying temporary files.\n+ */\n+ before_shmem_exit(worker_cleanup, (Datum) 0);\n+\n\nDo we really need to register a new callback here? Won't the existing\nlogical replication worker exit routine (logicalrep_worker_onexit) be\nsufficient for this patch's purpose?\n\n2.\n- SharedFileSet *fileset; /* space for segment files if shared */\n- const char *name; /* name of this BufFile if shared */\n+ FileSet *fileset; /* space for fileset for fileset based file */\n+ const char *name; /* name of this BufFile */\n\nThe comments for the above two variables can be written as (a) space\nfor fileset based segment files, (b) name of fileset based BufFile.\n\n3.\n /*\n- * Create a new segment file backing a shared BufFile.\n+ * Create a new segment file backing a fileset BufFile.\n */\n static File\n-MakeNewSharedSegment(BufFile *buffile, int segment)\n+MakeNewSegment(BufFile *buffile, int segment)\n\nI think it is better to name this function as MakeNewFileSetSegment.\nYou can slightly change the comment as: \"Create a new segment file\nbacking a fileset based BufFile.\"\n\n4.\n/*\n * It is possible that there are files left over from before a crash\n- * restart with the same name. In order for BufFileOpenShared() not to\n+ * restart with the same name. In order for BufFileOpen() not to\n * get confused about how many segments there are, we'll unlink the next\n\nTypo. /BufFileOpen/BufFileOpenFileSet\n\n5.\n static void\n-SharedSegmentName(char *name, const char *buffile_name, int segment)\n+SegmentName(char *name, const char *buffile_name, int segment)\n\nCan we name this as FileSetSegmentName?\n\n6.\n *\n- * The naming scheme for shared BufFiles is left up to the calling code. The\n+ * The naming scheme for fileset BufFiles is left up to the calling code.\n\nIsn't it better to say \"... fileset based BufFiles ..\"?\n\n7.\n+ * FileSets provide a temporary namespace (think directory) so that files can\n+ * be discovered by name\n\nA full stop is missing at the end of the statement.\n\n8.\n+ *\n+ * The callers are expected to explicitly remove such files by using\n+ * SharedFileSetDelete/ SharedFileSetDeleteAll.\n+ *\n+ * Files will be distributed over the tablespaces configured in\n+ * temp_tablespaces.\n+ *\n+ * Under the covers the set is one or more directories which will eventually\n+ * be deleted.\n+ */\n+void\n+FileSetInit(FileSet *fileset)\n\nIs there a need to mention 'Shared' in API names (SharedFileSetDelete/\nSharedFileSetDeleteAll) in the comments? Also, there doesn't seem to\nbe a need for extra space before *DeleteAll API in comments.\n\n9.\n * Files will be distributed over the tablespaces configured in\n * temp_tablespaces.\n *\n * Under the covers the set is one or more directories which will eventually\n * be deleted.\n */\nvoid\nSharedFileSetInit(SharedFileSet *fileset, dsm_segment *seg)\n\nI think we can remove the part of the above comment where it says\n\"Files will be distributed over ...\" as that is already mentioned atop\nFileSetInit.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 24 Aug 2021 12:26:02 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Tue, Aug 24, 2021 at 12:26 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> > I was also thinking about the same, does it make sense to name it just\n> > \"\"%s/%s%lu.%u.fileset\"?\n\nDone\n\n> I think it is reasonable to use .fileset as proposed by you.\n>\n> Few other comments:\n> =================\n> 1.\n> + /*\n> + * Register before-shmem-exit hook to ensure filesets are dropped while we\n> + * can still report stats for underlying temporary files.\n> + */\n> + before_shmem_exit(worker_cleanup, (Datum) 0);\n> +\n>\n> Do we really need to register a new callback here? Won't the existing\n> logical replication worker exit routine (logicalrep_worker_onexit) be\n> sufficient for this patch's purpose?\n\nRight, we don't need an extra function for this.\n\n> 2.\n> - SharedFileSet *fileset; /* space for segment files if shared */\n> - const char *name; /* name of this BufFile if shared */\n> + FileSet *fileset; /* space for fileset for fileset based file */\n> + const char *name; /* name of this BufFile */\n>\n> The comments for the above two variables can be written as (a) space\n> for fileset based segment files, (b) name of fileset based BufFile.\n\nDone\n\n> 3.\n> /*\n> - * Create a new segment file backing a shared BufFile.\n> + * Create a new segment file backing a fileset BufFile.\n> */\n> static File\n> -MakeNewSharedSegment(BufFile *buffile, int segment)\n> +MakeNewSegment(BufFile *buffile, int segment)\n>\n> I think it is better to name this function as MakeNewFileSetSegment.\n> You can slightly change the comment as: \"Create a new segment file\n> backing a fileset based BufFile.\"\n\n Make sense\n\n> 4.\n> /*\n> * It is possible that there are files left over from before a crash\n> - * restart with the same name. In order for BufFileOpenShared() not to\n> + * restart with the same name. In order for BufFileOpen() not to\n> * get confused about how many segments there are, we'll unlink the next\n>\n> Typo. /BufFileOpen/BufFileOpenFileSet\n\nFixed\n\n> 5.\n> static void\n> -SharedSegmentName(char *name, const char *buffile_name, int segment)\n> +SegmentName(char *name, const char *buffile_name, int segment)\n>\n> Can we name this as FileSetSegmentName?\n\nDone\n\n> 6.\n> *\n> - * The naming scheme for shared BufFiles is left up to the calling code. The\n> + * The naming scheme for fileset BufFiles is left up to the calling code.\n>\n> Isn't it better to say \"... fileset based BufFiles ..\"?\n\nDone\n\n> 7.\n> + * FileSets provide a temporary namespace (think directory) so that files can\n> + * be discovered by name\n>\n> A full stop is missing at the end of the statement.\n\nFixed\n\n> 8.\n> + *\n> + * The callers are expected to explicitly remove such files by using\n> + * SharedFileSetDelete/ SharedFileSetDeleteAll.\n> + *\n> + * Files will be distributed over the tablespaces configured in\n> + * temp_tablespaces.\n> + *\n> + * Under the covers the set is one or more directories which will eventually\n> + * be deleted.\n> + */\n> +void\n> +FileSetInit(FileSet *fileset)\n>\n> Is there a need to mention 'Shared' in API names (SharedFileSetDelete/\n> SharedFileSetDeleteAll) in the comments? Also, there doesn't seem to\n> be a need for extra space before *DeleteAll API in comments.\n\nFixed\n\n> 9.\n> * Files will be distributed over the tablespaces configured in\n> * temp_tablespaces.\n> *\n> * Under the covers the set is one or more directories which will eventually\n> * be deleted.\n> */\n> void\n> SharedFileSetInit(SharedFileSet *fileset, dsm_segment *seg)\n>\n> I think we can remove the part of the above comment where it says\n> \"Files will be distributed over ...\" as that is already mentioned atop\n> FileSetInit.\n\nDone\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Tue, 24 Aug 2021 15:55:26 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Tuesday, August 24, 2021 6:25 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\r\n> On Tue, Aug 24, 2021 at 12:26 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\r\n> \r\n> > > I was also thinking about the same, does it make sense to name it\r\n> > > just \"\"%s/%s%lu.%u.fileset\"?\r\n> \r\n> Done\r\n> \r\n> > I think it is reasonable to use .fileset as proposed by you.\r\n> >\r\n> > Few other comments:\r\n> Done\r\n\r\nAfter applying the patch, I tested the impacted features\r\n(parallel hashjoin/btree build) with different settings\r\n(log_temp_files/maintenance_work_mem/parallel_leader_participation/workers)\r\n, and the patch works well.\r\n\r\nOne thing I noticed is that when enable log_temp_files, the pathname in log\r\nchanged from \"xxx.sharedfileset\" to \"xxx.fileset\", and I also noticed some\r\nblogs[1] reference the old path name. Although, I think it doesn't matter, just\r\nshare the information here in case someone has different opinions.\r\n\r\n\r\nSome minor thing I noticed in the patch:\r\n\r\n1)\r\nit seems we can add \"FileSet\" to typedefs.list\r\n\r\n2)\r\nThe commit message in 0002 used \"shared fileset\" which should be \"fileset\",\r\n---\r\nInstead of using a separate shared fileset for each xid, use one shared\r\nfileset for whole lifetime of the worker...\r\n---\r\n\r\n[1] https://blog.dbi-services.com/about-temp_tablespaces-in-postgresql/\r\n\r\nBest regards,\r\nHou zj\r\n\r\n", "msg_date": "Wed, 25 Aug 2021 01:50:42 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Tue, Aug 24, 2021 at 3:55 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Tue, Aug 24, 2021 at 12:26 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n\nThe first patch looks good to me. I have made minor changes to the\nattached patch. The changes include: fixing compilation warning, made\nsome comment changes, ran pgindent, and few other cosmetic changes. If\nyou are fine with the attached, then kindly rebase the second patch\natop it.\n\n-- \nWith Regards,\nAmit Kapila.", "msg_date": "Wed, 25 Aug 2021 17:49:20 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Wed, Aug 25, 2021 at 9:19 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Tue, Aug 24, 2021 at 3:55 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n> > On Tue, Aug 24, 2021 at 12:26 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n>\n> The first patch looks good to me. I have made minor changes to the\n> attached patch. The changes include: fixing compilation warning, made\n> some comment changes, ran pgindent, and few other cosmetic changes. If\n> you are fine with the attached, then kindly rebase the second patch\n> atop it.\n\nThe patch looks good to me.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Thu, 26 Aug 2021 10:46:49 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Wed, Aug 25, 2021 at 5:49 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> On Tue, Aug 24, 2021 at 3:55 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n> > On Tue, Aug 24, 2021 at 12:26 PM Amit Kapila <amit.kapila16@gmail.com>\n> wrote:\n> >\n>\n> The first patch looks good to me. I have made minor changes to the\n> attached patch. The changes include: fixing compilation warning, made\n> some comment changes, ran pgindent, and few other cosmetic changes. If\n> you are fine with the attached, then kindly rebase the second patch\n> atop it.\n>\n>\nThe patch looks good to me, I have rebased 0002 atop this patch and also\ndone some cosmetic fixes in 0002.\n\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Thu, 26 Aug 2021 11:47:34 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Thu, Aug 26, 2021 at 11:47 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Wed, Aug 25, 2021 at 5:49 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>\n>> On Tue, Aug 24, 2021 at 3:55 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>> >\n>> > On Tue, Aug 24, 2021 at 12:26 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>> >\n>>\n>> The first patch looks good to me. I have made minor changes to the\n>> attached patch. The changes include: fixing compilation warning, made\n>> some comment changes, ran pgindent, and few other cosmetic changes. If\n>> you are fine with the attached, then kindly rebase the second patch\n>> atop it.\n>>\n>\n> The patch looks good to me,\n>\n\nThanks, Sawada-San and Dilip for confirmation. I would like to commit\nthis and the second patch (the second one still needs some more\ntesting and review) for PG-15 as there is no bug per-se related to\nthis work in PG-14 but I see an argument to commit this for PG-14 to\nkeep the code (APIs) consistent. What do you think? Does anybody else\nhave any opinion on this?\n\nBelow is a summary of each of the patches for those who are not\nfollowing this closely:\nPatch-1: The purpose of this patch is to refactor sharedfileset.c to\nseparate out fileset implementation. Basically, this moves the fileset\nrelated implementation out of sharedfileset.c to allow its usage by\nbackends that don't want to share filesets among different processes.\nAfter this split, fileset infrastructure is used by both\nsharedfileset.c and worker.c for the named temporary files that\nsurvive across transactions. This is suggested by Andres to have a\ncleaner API and its usage.\n\nPatch-2: Allow to use single fileset in worker.c (for the lifetime of\nworker) instead of using a separate fileset for each remote\ntransaction. After this, the files to record changes for each remote\ntransaction will be created under the same fileset and the files will\nbe deleted after the transaction is completed. This is suggested by\nThomas to allow better resource usage.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Thu, 26 Aug 2021 14:10:00 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Thu, Aug 26, 2021 at 2:10 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n>\n> Thanks, Sawada-San and Dilip for confirmation. I would like to commit\n> this and the second patch (the second one still needs some more\n> testing and review) for PG-15 as there is no bug per-se related to\n> this work in PG-14 but I see an argument to commit this for PG-14 to\n> keep the code (APIs) consistent. What do you think? Does anybody else\n> have any opinion on this?\n>\n>\nIMHO, this is a fair amount of refactoring and this is actually an\nimprovement patch so we should push it to v15.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Thu, Aug 26, 2021 at 2:10 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\nThanks, Sawada-San and Dilip for confirmation. I would like to commit\nthis and the second patch (the second one still needs some more\ntesting and review) for PG-15 as there is no bug per-se related to\nthis work in PG-14 but I see an argument to commit this for PG-14 to\nkeep the code (APIs) consistent. What do you think? Does anybody else\nhave any opinion on this?IMHO, this is a fair amount of refactoring and this is actually an improvement patch so we should push it to v15.-- Regards,Dilip KumarEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Fri, 27 Aug 2021 10:54:46 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Thu, Aug 26, 2021 2:18 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\r\n\r\n> The patch looks good to me, I have rebased 0002 atop\r\n> this patch and also done some cosmetic fixes in 0002. \r\n\r\nHere are some comments for the 0002 patch.\r\n\r\n1)\r\n\r\n- * toplevel transaction. Each subscription has a separate set of files.\r\n+ * toplevel transaction. Each subscription has a separate files.\r\n\r\na separate files => a separate file\r\n\r\n2)\r\n+\t * Otherwise, just open it file for writing, in append mode.\r\n \t */\r\n\r\nopen it file => open the file\r\n\r\n\r\n3)\r\n \tif (subxact_data.nsubxacts == 0)\r\n \t{\r\n-\t\tif (ent->subxact_fileset)\r\n-\t\t{\r\n-\t\t\tcleanup_subxact_info();\r\n-\t\t\tFileSetDeleteAll(ent->subxact_fileset);\r\n-\t\t\tpfree(ent->subxact_fileset);\r\n-\t\t\tent->subxact_fileset = NULL;\r\n-\t\t}\r\n+\t\tcleanup_subxact_info();\r\n+\t\tBufFileDeleteFileSet(stream_fileset, path, true);\r\n+\r\n\r\n\r\nBefore applying the patch, the code only invoke cleanup_subxact_info() when the\r\nfile exists. After applying the patch, it will invoke cleanup_subxact_info()\r\neither the file exists or not. Is it correct ?\r\n\r\n\r\n4)\r\n \t/*\r\n-\t * If this is the first streamed segment, the file must not exist, so make\r\n-\t * sure we're the ones creating it. Otherwise just open the file for\r\n-\t * writing, in append mode.\r\n+\t * If this is the first streamed segment, create the changes file.\r\n+\t * Otherwise, just open it file for writing, in append mode.\r\n \t */\r\n \tif (first_segment)\r\n-\t{\r\n\t...\r\n-\t\tif (found)\r\n-\t\t\tereport(ERROR,\r\n-\t\t\t\t\t(errcode(ERRCODE_PROTOCOL_VIOLATION),\r\n-\t\t\t\t\t errmsg_internal(\"incorrect first-segment flag for streamed replication transaction\")));\r\n\t...\r\n-\t}\r\n+\t\tstream_fd = BufFileCreateFileSet(stream_fileset, path);\r\n\r\n\r\nSince the function BufFileCreateFileSet() doesn't check the file's existence,\r\nthe change here seems remove the file existence check which the old code did.\r\n\r\n\r\nBest regards,\r\nHou zj\r\n", "msg_date": "Fri, 27 Aug 2021 05:26:17 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Fri, Aug 27, 2021 1:25 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\r\n> On Thu, Aug 26, 2021 at 2:10 PM Amit Kapila <mailto:amit.kapila16@gmail.com> wrote:\r\n> \r\n>> Thanks, Sawada-San and Dilip for confirmation. I would like to commit\r\n>> this and the second patch (the second one still needs some more\r\n>> testing and review) for PG-15 as there is no bug per-se related to\r\n>> this work in PG-14 but I see an argument to commit this for PG-14 to\r\n>> keep the code (APIs) consistent. What do you think? Does anybody else\r\n>> have any opinion on this?\r\n\r\n> IMHO, this is a fair amount of refactoring and this is actually an\r\n> improvement patch so we should push it to v15.\r\n\r\n+1\r\n\r\nBest regards,\r\nHou zj\r\n", "msg_date": "Fri, 27 Aug 2021 05:28:48 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Fri, Aug 27, 2021 at 10:56 AM houzj.fnst@fujitsu.com\n<houzj.fnst@fujitsu.com> wrote:\n>\n> On Thu, Aug 26, 2021 2:18 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> > The patch looks good to me, I have rebased 0002 atop\n> > this patch and also done some cosmetic fixes in 0002.\n>\n> Here are some comments for the 0002 patch.\n>\n> 1)\n>\n> - * toplevel transaction. Each subscription has a separate set of files.\n> + * toplevel transaction. Each subscription has a separate files.\n>\n> a separate files => a separate file\n\nDone\n\n> 2)\n> + * Otherwise, just open it file for writing, in append mode.\n> */\n>\n> open it file => open the file\n\nDone\n\n>\n> 3)\n> if (subxact_data.nsubxacts == 0)\n> {\n> - if (ent->subxact_fileset)\n> - {\n> - cleanup_subxact_info();\n> - FileSetDeleteAll(ent->subxact_fileset);\n> - pfree(ent->subxact_fileset);\n> - ent->subxact_fileset = NULL;\n> - }\n> + cleanup_subxact_info();\n> + BufFileDeleteFileSet(stream_fileset, path, true);\n> +\n>\n> Before applying the patch, the code only invoke cleanup_subxact_info() when the\n> file exists. After applying the patch, it will invoke cleanup_subxact_info()\n> either the file exists or not. Is it correct ?\n\nI think this is just structure resetting at the end of the stream.\nEarlier the hash was telling us whether we have ever dirtied that\nstructure or not but now we are not maintaining that hash so we just\nreset it at the end of the stream. I don't think its any bad, in fact\nI think this is much cheaper compared to maining the hash.\n\n>\n> 4)\n> /*\n> - * If this is the first streamed segment, the file must not exist, so make\n> - * sure we're the ones creating it. Otherwise just open the file for\n> - * writing, in append mode.\n> + * If this is the first streamed segment, create the changes file.\n> + * Otherwise, just open it file for writing, in append mode.\n> */\n> if (first_segment)\n> - {\n> ...\n> - if (found)\n> - ereport(ERROR,\n> - (errcode(ERRCODE_PROTOCOL_VIOLATION),\n> - errmsg_internal(\"incorrect first-segment flag for streamed replication transaction\")));\n> ...\n> - }\n> + stream_fd = BufFileCreateFileSet(stream_fileset, path);\n>\n>\n> Since the function BufFileCreateFileSet() doesn't check the file's existence,\n> the change here seems remove the file existence check which the old code did.\n\nNot really, we were just doing a sanity check of the in memory hash\nentry, now we don't maintain that so we don't need to do that.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Fri, 27 Aug 2021 12:04:31 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Fri, Aug 27, 2021 at 2:25 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Thu, Aug 26, 2021 at 2:10 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>\n>>\n>> Thanks, Sawada-San and Dilip for confirmation. I would like to commit\n>> this and the second patch (the second one still needs some more\n>> testing and review) for PG-15 as there is no bug per-se related to\n>> this work in PG-14 but I see an argument to commit this for PG-14 to\n>> keep the code (APIs) consistent. What do you think? Does anybody else\n>> have any opinion on this?\n>>\n>\n> IMHO, this is a fair amount of refactoring and this is actually an improvement patch so we should push it to v15.\n\nI think so too.\n\nRegards,\n\n--\nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Mon, 30 Aug 2021 10:12:07 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Fri, Aug 27, 2021 at 3:34 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Fri, Aug 27, 2021 at 10:56 AM houzj.fnst@fujitsu.com\n> <houzj.fnst@fujitsu.com> wrote:\n> >\n> > On Thu, Aug 26, 2021 2:18 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n> > > The patch looks good to me, I have rebased 0002 atop\n> > > this patch and also done some cosmetic fixes in 0002.\n> >\n> > Here are some comments for the 0002 patch.\n> >\n> > 1)\n> >\n> > - * toplevel transaction. Each subscription has a separate set of files.\n> > + * toplevel transaction. Each subscription has a separate files.\n> >\n> > a separate files => a separate file\n>\n> Done\n>\n> > 2)\n> > + * Otherwise, just open it file for writing, in append mode.\n> > */\n> >\n> > open it file => open the file\n>\n> Done\n>\n> >\n> > 3)\n> > if (subxact_data.nsubxacts == 0)\n> > {\n> > - if (ent->subxact_fileset)\n> > - {\n> > - cleanup_subxact_info();\n> > - FileSetDeleteAll(ent->subxact_fileset);\n> > - pfree(ent->subxact_fileset);\n> > - ent->subxact_fileset = NULL;\n> > - }\n> > + cleanup_subxact_info();\n> > + BufFileDeleteFileSet(stream_fileset, path, true);\n> > +\n> >\n> > Before applying the patch, the code only invoke cleanup_subxact_info() when the\n> > file exists. After applying the patch, it will invoke cleanup_subxact_info()\n> > either the file exists or not. Is it correct ?\n>\n> I think this is just structure resetting at the end of the stream.\n> Earlier the hash was telling us whether we have ever dirtied that\n> structure or not but now we are not maintaining that hash so we just\n> reset it at the end of the stream. I don't think its any bad, in fact\n> I think this is much cheaper compared to maining the hash.\n>\n> >\n> > 4)\n> > /*\n> > - * If this is the first streamed segment, the file must not exist, so make\n> > - * sure we're the ones creating it. Otherwise just open the file for\n> > - * writing, in append mode.\n> > + * If this is the first streamed segment, create the changes file.\n> > + * Otherwise, just open it file for writing, in append mode.\n> > */\n> > if (first_segment)\n> > - {\n> > ...\n> > - if (found)\n> > - ereport(ERROR,\n> > - (errcode(ERRCODE_PROTOCOL_VIOLATION),\n> > - errmsg_internal(\"incorrect first-segment flag for streamed replication transaction\")));\n> > ...\n> > - }\n> > + stream_fd = BufFileCreateFileSet(stream_fileset, path);\n> >\n> >\n> > Since the function BufFileCreateFileSet() doesn't check the file's existence,\n> > the change here seems remove the file existence check which the old code did.\n>\n> Not really, we were just doing a sanity check of the in memory hash\n> entry, now we don't maintain that so we don't need to do that.\n\nThank you for updating the patch!\n\nThe patch looks good to me except for the below comment:\n\n+ /* Delete the subxact file, if it exist. */\n+ subxact_filename(path, subid, xid);\n+ BufFileDeleteFileSet(stream_fileset, path, true);\n\ns/it exist/it exists/\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Mon, 30 Aug 2021 15:15:27 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Mon, Aug 30, 2021 at 6:42 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Fri, Aug 27, 2021 at 2:25 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n> > On Thu, Aug 26, 2021 at 2:10 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >>\n> >>\n> >> Thanks, Sawada-San and Dilip for confirmation. I would like to commit\n> >> this and the second patch (the second one still needs some more\n> >> testing and review) for PG-15 as there is no bug per-se related to\n> >> this work in PG-14 but I see an argument to commit this for PG-14 to\n> >> keep the code (APIs) consistent. What do you think? Does anybody else\n> >> have any opinion on this?\n> >>\n> >\n> > IMHO, this is a fair amount of refactoring and this is actually an improvement patch so we should push it to v15.\n>\n> I think so too.\n>\n\nI have pushed the first patch in this series.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Mon, 30 Aug 2021 12:14:09 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "From Mon, Aug 30, 2021 2:15 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\r\n> On Fri, Aug 27, 2021 at 3:34 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\r\n> >\r\n> > On Fri, Aug 27, 2021 at 10:56 AM houzj.fnst@fujitsu.com <houzj.fnst@fujitsu.com> wrote:\r\n> > >\r\n> > > On Thu, Aug 26, 2021 2:18 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\r\n> > >\r\n> > > > The patch looks good to me, I have rebased 0002 atop this patch\r\n> > > > and also done some cosmetic fixes in 0002.\r\n> \r\n> Thank you for updating the patch!\r\n> \r\n> The patch looks good to me except for the below comment:\r\n> \r\n> + /* Delete the subxact file, if it exist. */\r\n> + subxact_filename(path, subid, xid);\r\n> + BufFileDeleteFileSet(stream_fileset, path, true);\r\n> \r\n> s/it exist/it exists/\r\n\r\nExcept for Sawada-san's comment, the v6-0002 patch looks good to me.\r\n\r\nBest regards,\r\nHou zj\r\n", "msg_date": "Tue, 31 Aug 2021 02:08:59 +0000", "msg_from": "\"houzj.fnst@fujitsu.com\" <houzj.fnst@fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Tue, Aug 31, 2021 at 7:39 AM houzj.fnst@fujitsu.com <\nhouzj.fnst@fujitsu.com> wrote:\n\n> From Mon, Aug 30, 2021 2:15 PM Masahiko Sawada <sawada.mshk@gmail.com>\n> wrote:\n> > On Fri, Aug 27, 2021 at 3:34 PM Dilip Kumar <dilipbalaut@gmail.com>\n> wrote:\n> > >\n> > > On Fri, Aug 27, 2021 at 10:56 AM houzj.fnst@fujitsu.com <\n> houzj.fnst@fujitsu.com> wrote:\n> > > >\n> > > > On Thu, Aug 26, 2021 2:18 PM Dilip Kumar <dilipbalaut@gmail.com>\n> wrote:\n> > > >\n> > > > > The patch looks good to me, I have rebased 0002 atop this patch\n> > > > > and also done some cosmetic fixes in 0002.\n> >\n> > Thank you for updating the patch!\n> >\n> > The patch looks good to me except for the below comment:\n> >\n> > + /* Delete the subxact file, if it exist. */\n> > + subxact_filename(path, subid, xid);\n> > + BufFileDeleteFileSet(stream_fileset, path, true);\n> >\n> > s/it exist/it exists/\n>\n> Except for Sawada-san's comment, the v6-0002 patch looks good to me.\n>\n\nThanks, I will wait for a day to see if there are any other comments on\nthis, after that I will fix this one issue and post the updated patch.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Tue, Aug 31, 2021 at 7:39 AM houzj.fnst@fujitsu.com <houzj.fnst@fujitsu.com> wrote:From Mon, Aug 30, 2021 2:15 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> On Fri, Aug 27, 2021 at 3:34 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n> > On Fri, Aug 27, 2021 at 10:56 AM houzj.fnst@fujitsu.com <houzj.fnst@fujitsu.com> wrote:\n> > >\n> > > On Thu, Aug 26, 2021 2:18 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> > >\n> > > > The patch looks good to me, I have rebased 0002 atop this patch\n> > > > and also done some cosmetic fixes in 0002.\n> \n> Thank you for updating the patch!\n> \n> The patch looks good to me except for the below comment:\n> \n> +        /* Delete the subxact file, if it exist. */\n> +        subxact_filename(path, subid, xid);\n> +        BufFileDeleteFileSet(stream_fileset, path, true);\n> \n> s/it exist/it exists/\n\nExcept for Sawada-san's comment, the v6-0002 patch looks good to me.\nThanks, I will wait for a day to see if there are any other comments on this, after that I will fix this one issue and post the updated patch.-- Regards,Dilip KumarEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Tue, 31 Aug 2021 11:23:16 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Fri, Aug 27, 2021 at 12:04 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n\nFew comments on v6-0002*\n=========================\n1.\n-BufFileDeleteFileSet(FileSet *fileset, const char *name)\n+BufFileDeleteFileSet(FileSet *fileset, const char *name, bool missing_ok)\n {\n char segment_name[MAXPGPATH];\n int segment = 0;\n@@ -358,7 +369,7 @@ BufFileDeleteFileSet(FileSet *fileset, const char *name)\n for (;;)\n {\n FileSetSegmentName(segment_name, name, segment);\n- if (!FileSetDelete(fileset, segment_name, true))\n+ if (!FileSetDelete(fileset, segment_name, !missing_ok))\n\nI don't think the usage of missing_ok is correct here. If you see\nFileSetDelete->PathNameDeleteTemporaryFile, it already tolerates that\nthe file doesn't exist but gives an error only when it is unable to\nlink. So, with this missing_ok users (say like worker.c) won't even\nget errors when they are not able to remove files whereas I think the\nneed for the patch is to not get an error when the file doesn't exist.\nI think you don't need to change anything in the way we invoke\nFileSetDelete.\n\n2.\n-static HTAB *xidhash = NULL;\n+static FileSet *stream_fileset = NULL;\n\nCan we keep this in LogicalRepWorker and initialize it accordingly?\n\n3.\n+ /* Open the subxact file, if it does not exist, create it. */\n+ fd = BufFileOpenFileSet(stream_fileset, path, O_RDWR, true);\n+ if (fd == NULL)\n+ fd = BufFileCreateFileSet(stream_fileset, path);\n\nI think retaining the existing comment: \"Create the subxact file if it\nnot already created, otherwise open the existing file.\" seems better\nhere.\n\n4.\n /*\n- * If there is no subtransaction then nothing to do, but if already have\n- * subxact file then delete that.\n+ * If there are no subtransactions, there is nothing to be done, but if\n+ * subxacts already exist, delete it.\n */\n\nHow about changing the above comment to something like: \"Delete the\nsubxacts file, if exists\"?\n\n5. Can we slightly change the commit message as:\nOptimize fileset usage in apply worker.\n\nUse one fileset for the entire worker lifetime instead of using\nseparate filesets for each streaming transaction. Now, the\nchanges/subxacts files for every streaming transaction will be created\nunder the same fileset and the files will be deleted after the\ntransaction is completed.\n\nThis patch extends the BufFileOpenFileSet and BufFileDeleteFileSet\nAPIs to allow users to specify whether to give an error on missing\nfiles.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 31 Aug 2021 15:20:04 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Tue, Aug 31, 2021 at 3:20 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Fri, Aug 27, 2021 at 12:04 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n>\n> Few comments on v6-0002*\n> =========================\n> 1.\n> -BufFileDeleteFileSet(FileSet *fileset, const char *name)\n> +BufFileDeleteFileSet(FileSet *fileset, const char *name, bool missing_ok)\n> {\n> char segment_name[MAXPGPATH];\n> int segment = 0;\n> @@ -358,7 +369,7 @@ BufFileDeleteFileSet(FileSet *fileset, const char *name)\n> for (;;)\n> {\n> FileSetSegmentName(segment_name, name, segment);\n> - if (!FileSetDelete(fileset, segment_name, true))\n> + if (!FileSetDelete(fileset, segment_name, !missing_ok))\n>\n> I don't think the usage of missing_ok is correct here. If you see\n> FileSetDelete->PathNameDeleteTemporaryFile, it already tolerates that\n> the file doesn't exist but gives an error only when it is unable to\n> link. So, with this missing_ok users (say like worker.c) won't even\n> get errors when they are not able to remove files whereas I think the\n> need for the patch is to not get an error when the file doesn't exist.\n> I think you don't need to change anything in the way we invoke\n> FileSetDelete.\n\nRight, fixed.\n\n> 2.\n> -static HTAB *xidhash = NULL;\n> +static FileSet *stream_fileset = NULL;\n>\n> Can we keep this in LogicalRepWorker and initialize it accordingly?\n\nDone\n\n> 3.\n> + /* Open the subxact file, if it does not exist, create it. */\n> + fd = BufFileOpenFileSet(stream_fileset, path, O_RDWR, true);\n> + if (fd == NULL)\n> + fd = BufFileCreateFileSet(stream_fileset, path);\n>\n> I think retaining the existing comment: \"Create the subxact file if it\n> not already created, otherwise open the existing file.\" seems better\n> here.\n\nDone\n\n> 4.\n> /*\n> - * If there is no subtransaction then nothing to do, but if already have\n> - * subxact file then delete that.\n> + * If there are no subtransactions, there is nothing to be done, but if\n> + * subxacts already exist, delete it.\n> */\n>\n> How about changing the above comment to something like: \"Delete the\n> subxacts file, if exists\"?\n\nDone\n\n> 5. Can we slightly change the commit message as:\n> Optimize fileset usage in apply worker.\n>\n> Use one fileset for the entire worker lifetime instead of using\n> separate filesets for each streaming transaction. Now, the\n> changes/subxacts files for every streaming transaction will be created\n> under the same fileset and the files will be deleted after the\n> transaction is completed.\n>\n> This patch extends the BufFileOpenFileSet and BufFileDeleteFileSet\n> APIs to allow users to specify whether to give an error on missing\n> files.\n\nDone\n\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Wed, 1 Sep 2021 13:53:05 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Wed, Sep 1, 2021 at 1:53 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n\nThe latest patch looks good to me. I have made some changes in the\ncomments, see attached. I am planning to push this tomorrow unless you\nor others have any comments on it.\n\n-- \nWith Regards,\nAmit Kapila.", "msg_date": "Wed, 1 Sep 2021 17:23:13 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Wed, Sep 1, 2021 at 5:23 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> On Wed, Sep 1, 2021 at 1:53 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n>\n> The latest patch looks good to me. I have made some changes in the\n> comments, see attached. I am planning to push this tomorrow unless you\n> or others have any comments on it.\n>\n\nThese comments changes look good to me.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Wed, Sep 1, 2021 at 5:23 PM Amit Kapila <amit.kapila16@gmail.com> wrote:On Wed, Sep 1, 2021 at 1:53 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n\nThe latest patch looks good to me. I have made some changes in the\ncomments, see attached. I am planning to push this tomorrow unless you\nor others have any comments on it. These comments changes look good to me. -- Regards,Dilip KumarEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Wed, 1 Sep 2021 17:32:51 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "On Wed, Sep 1, 2021 at 5:33 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Wed, Sep 1, 2021 at 5:23 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>\n>> On Wed, Sep 1, 2021 at 1:53 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>> >\n>>\n>> The latest patch looks good to me. I have made some changes in the\n>> comments, see attached. I am planning to push this tomorrow unless you\n>> or others have any comments on it.\n>\n>\n> These comments changes look good to me.\n>\n\nPushed.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Thu, 2 Sep 2021 11:06:28 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" }, { "msg_contents": "Hi,\n\nThank for all the work on this topic - I'd somehow accidentally marked this\nthread as read when coming back from vacation...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 29 Nov 2021 10:10:51 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: Separate out FileSet from SharedFileSet (was Re: pgsql: pgstat:\n Bring up pgstat in BaseInit() to fix uninitialized use o)" } ]
[ { "msg_contents": "Hi hackers,\n\nHere's a patch adding EXECUTE to the list of of commands tab completed\nafter the various EXPLAIN variants.\n\n- ilmari", "msg_date": "Sat, 07 Aug 2021 22:29:01 +0100", "msg_from": "ilmari@ilmari.org (Dagfinn Ilmari =?utf-8?Q?Manns=C3=A5ker?=)", "msg_from_op": true, "msg_subject": "[PATCH] Add tab completion for EXECUTE after EXPLAIN" }, { "msg_contents": "ilmari@ilmari.org (Dagfinn Ilmari Mannsåker) writes:\n\n> Hi hackers,\n>\n> Here's a patch adding EXECUTE to the list of of commands tab completed\n> after the various EXPLAIN variants.\n\nAdded to the 2021-09 commitfest: https://commitfest.postgresql.org/34/3279/\n\n- ilmari\n\n\n", "msg_date": "Sat, 07 Aug 2021 23:23:28 +0100", "msg_from": "ilmari@ilmari.org (Dagfinn Ilmari =?utf-8?Q?Manns=C3=A5ker?=)", "msg_from_op": true, "msg_subject": "Re: [PATCH] Add tab completion for EXECUTE after EXPLAIN" }, { "msg_contents": "On Sat, Aug 07, 2021 at 11:23:28PM +0100, Dagfinn Ilmari Mannsåker wrote:\n>> Here's a patch adding EXECUTE to the list of of commands tab completed\n>> after the various EXPLAIN variants.\n\nI see no problems with that, so applied. Thanks.\n--\nMichael", "msg_date": "Wed, 25 Aug 2021 12:03:09 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Add tab completion for EXECUTE after EXPLAIN" } ]
[ { "msg_contents": "Hi,\n\nIn the course of [1] I again looked at all pgstat_* callsites and noticed the\nnew calls to pgstat_get_my_query_id() in elog.c.\n\nAs currently implemented those pgstat_get_my_query_id() calls are not\nsafe. It's fine during backend startup because MyBEEntry is not set, but\nduring shutdown that's not ok, because we never unset MyBEEntry.\n\nandres@awork3:~/src/postgresql$ /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --single postgres -D /srv/dev/pgdev-dev/ -c 'log_line_prefix=%Q' -c log_min_messages=debug1\n0NOTICE: database system was shut down at 2021-08-07 16:42:26 PDT\n0DEBUG: checkpoint record is at 1/1C000508\n0DEBUG: redo record is at 1/1C000508; shutdown true\n0DEBUG: next transaction ID: 213067; next OID: 16434\n0DEBUG: next MultiXactId: 1; next MultiXactOffset: 0\n0DEBUG: oldest unfrozen transaction ID: 701, in database 1\n0DEBUG: oldest MultiXactId: 1, in database 1\n0DEBUG: commit timestamp Xid oldest/newest: 0/0\n0DEBUG: transaction ID wrap limit is 2147484348, limited by database with OID 1\n0DEBUG: MultiXactId wrap limit is 2147483648, limited by database with OID 1\n0DEBUG: starting up replication slots\n0DEBUG: MultiXactId wrap limit is 2147483648, limited by database with OID 1\n0DEBUG: MultiXact member stop limit is now 4294914944 based on MultiXact 1\n\nPostgreSQL stand-alone backend 15devel\nbackend> 0NOTICE: shutting down\n0DEBUG: performing replication slot checkpoint\nSegmentation fault\n\n#0 0x000055cb9b871632 in pgstat_get_my_query_id () at /home/andres/src/postgresql/src/backend/utils/activity/backend_status.c:1042\n#1 0x000055cb9ba00398 in log_line_prefix (buf=0x7ffc751092e0, edata=0x55cb9bd6a900 <errordata>)\n at /home/andres/src/postgresql/src/backend/utils/error/elog.c:2723\n#2 0x000055cb9ba00ee6 in send_message_to_server_log (edata=0x55cb9bd6a900 <errordata>) at /home/andres/src/postgresql/src/backend/utils/error/elog.c:3017\n#3 0x000055cb9b9fe1b3 in EmitErrorReport () at /home/andres/src/postgresql/src/backend/utils/error/elog.c:1542\n#4 0x000055cb9b9fb600 in errfinish (filename=0x55cb9bc1a0eb \"miscinit.c\", lineno=974, funcname=0x55cb9bc1aea0 <__func__.5> \"UnlinkLockFiles\")\n at /home/andres/src/postgresql/src/backend/utils/error/elog.c:597\n#5 0x000055cb9ba0f2b4 in UnlinkLockFiles (status=0, arg=0) at /home/andres/src/postgresql/src/backend/utils/init/miscinit.c:974\n#6 0x000055cb9b8148da in proc_exit_prepare (code=0) at /home/andres/src/postgresql/src/backend/storage/ipc/ipc.c:209\n#7 0x000055cb9b814792 in proc_exit (code=0) at /home/andres/src/postgresql/src/backend/storage/ipc/ipc.c:107\n#8 0x000055cb9b851568 in PostgresMain (argc=9, argv=0x55cb9daddec0, dbname=0x55cb9dac4f70 \"postgres\", username=0x55cb9dac3580 \"andres\")\n at /home/andres/src/postgresql/src/backend/tcop/postgres.c:4702\n#9 0x000055cb9b672c5b in main (argc=9, argv=0x55cb9daddec0) at /home/andres/src/postgresql/src/backend/main/main.c:195\n\n\nI suspect that to make the elog.c usage safe, we'll have to clear MyBEEntry in\npgstat_beshutdown_hook().\n\nGreetings,\n\nAndres Freund\n\n[1] https://www.postgresql.org/message-id/20210807210349.bby5ta2xrbnte6ht%40alap3.anarazel.de\n\n\n", "msg_date": "Sat, 7 Aug 2021 16:44:07 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "elog.c query_id support vs shutdown" }, { "msg_contents": "On Sat, Aug 07, 2021 at 04:44:07PM -0700, Andres Freund wrote:\n> \n> As currently implemented those pgstat_get_my_query_id() calls are not\n> safe. It's fine during backend startup because MyBEEntry is not set, but\n> during shutdown that's not ok, because we never unset MyBEEntry.\n> \n> andres@awork3:~/src/postgresql$ /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --single postgres -D /srv/dev/pgdev-dev/ -c 'log_line_prefix=%Q' -c log_min_messages=debug1\n> [...]\n> PostgreSQL stand-alone backend 15devel\n> backend> 0NOTICE: shutting down\n> 0DEBUG: performing replication slot checkpoint\n> Segmentation fault\n\nOuch\n\n> I suspect that to make the elog.c usage safe, we'll have to clear MyBEEntry in\n> pgstat_beshutdown_hook().\n\nI agree, and a quick test indeed fix your scenario. It also seems like a good\nthing to do overall.\n\nI didn't find any other problematic corner cases, but I'm not that familiar with\npgstat, especially after the recent activity.\n\n\n", "msg_date": "Sun, 8 Aug 2021 13:46:39 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: elog.c query_id support vs shutdown" }, { "msg_contents": "On Sun, Aug 08, 2021 at 01:46:39PM +0800, Julien Rouhaud wrote:\n> On Sat, Aug 07, 2021 at 04:44:07PM -0700, Andres Freund wrote:\n> > \n> > As currently implemented those pgstat_get_my_query_id() calls are not\n> > safe. It's fine during backend startup because MyBEEntry is not set, but\n> > during shutdown that's not ok, because we never unset MyBEEntry.\n> > \n> > andres@awork3:~/src/postgresql$ /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --single postgres -D /srv/dev/pgdev-dev/ -c 'log_line_prefix=%Q' -c log_min_messages=debug1\n> > [...]\n> > PostgreSQL stand-alone backend 15devel\n> > backend> 0NOTICE: shutting down\n> > 0DEBUG: performing replication slot checkpoint\n> > Segmentation fault\n> \nFTR I just added an open item for that.\n\n\n", "msg_date": "Sun, 8 Aug 2021 14:02:58 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: elog.c query_id support vs shutdown" }, { "msg_contents": "Hi,\n\nOn 2021-08-08 13:46:39 +0800, Julien Rouhaud wrote:\n> On Sat, Aug 07, 2021 at 04:44:07PM -0700, Andres Freund wrote:\n> > \n> > As currently implemented those pgstat_get_my_query_id() calls are not\n> > safe. It's fine during backend startup because MyBEEntry is not set, but\n> > during shutdown that's not ok, because we never unset MyBEEntry.\n> > \n> > andres@awork3:~/src/postgresql$ /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --single postgres -D /srv/dev/pgdev-dev/ -c 'log_line_prefix=%Q' -c log_min_messages=debug1\n> > [...]\n> > PostgreSQL stand-alone backend 15devel\n> > backend> 0NOTICE: shutting down\n> > 0DEBUG: performing replication slot checkpoint\n> > Segmentation fault\n> \n> Ouch\n> \n> > I suspect that to make the elog.c usage safe, we'll have to clear MyBEEntry in\n> > pgstat_beshutdown_hook().\n> \n> I agree, and a quick test indeed fix your scenario. It also seems like a good\n> thing to do overall.\n\nYea, it does seem like a good thing. But we should do a search for the\nproblems it could cause...\n\n\n> I didn't find any other problematic corner cases, but I'm not that familiar\n> with pgstat, especially after the recent activity.\n\nI don't think anything relevant to this issue has changed so far... And there\nshouldn't be a meaningful amount of change to backend_status.c anyway - the\n\"what is currently happening\" stuff that backend_status.c implements is mostly\nindependent from the \"what has happened so far\" that pgstats.c implements.\n\nIt probably would be a good idea to separate out the two namespaces more\nclearly. Even with things like pgstat_report_activity() not being entirely\nclear cut (because of the pgstat_count_conn_* calls) it still seems like it\nwould be an improvement. But I don't want to do that before the shared memory\nstuff is in.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sun, 8 Aug 2021 11:53:39 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: elog.c query_id support vs shutdown" }, { "msg_contents": "Hi,\n\nOn 2021-08-08 11:53:39 -0700, Andres Freund wrote:\n> On 2021-08-08 13:46:39 +0800, Julien Rouhaud wrote:\n> > > I suspect that to make the elog.c usage safe, we'll have to clear MyBEEntry in\n> > > pgstat_beshutdown_hook().\n> > \n> > I agree, and a quick test indeed fix your scenario. It also seems like a good\n> > thing to do overall.\n> \n> Yea, it does seem like a good thing. But we should do a search for the\n> problems it could cause...\n\nNot a problem with unsetting MyBEEntry. But the search for problems made me\nreread the following comment:\n\n\t/*\n\t * There's no need for a lock around pgstat_begin_read_activity /\n\t * pgstat_end_read_activity here as it's only called from\n\t * pg_stat_get_activity which is already protected, or from the same\n\t * backend which means that there won't be concurrent writes.\n\t */\n\nI don't understand the pg_stat_get_activity() part of this comment?\npgstat_get_my_query_id() hardcodes MyBEEntry->st_query_id, so it can't be\nuseful to pg_stat_get_activity(), nor is it used there?\n\nI assume it's just a remnant from an earlier iteration of the code?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sun, 8 Aug 2021 12:06:16 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: elog.c query_id support vs shutdown" }, { "msg_contents": "On Mon, Aug 9, 2021 at 3:06 AM Andres Freund <andres@anarazel.de> wrote:\n>\n> Hi,\n>\n> On 2021-08-08 11:53:39 -0700, Andres Freund wrote:\n> > On 2021-08-08 13:46:39 +0800, Julien Rouhaud wrote:\n> > > > I suspect that to make the elog.c usage safe, we'll have to clear MyBEEntry in\n> > > > pgstat_beshutdown_hook().\n> > >\n> > > I agree, and a quick test indeed fix your scenario. It also seems like a good\n> > > thing to do overall.\n> >\n> > Yea, it does seem like a good thing. But we should do a search for the\n> > problems it could cause...\n\nAgreed, and I'm also looking into it.\n\n> Not a problem with unsetting MyBEEntry. But the search for problems made me\n> reread the following comment:\n>\n> /*\n> * There's no need for a lock around pgstat_begin_read_activity /\n> * pgstat_end_read_activity here as it's only called from\n> * pg_stat_get_activity which is already protected, or from the same\n> * backend which means that there won't be concurrent writes.\n> */\n>\n> I don't understand the pg_stat_get_activity() part of this comment?\n> pgstat_get_my_query_id() hardcodes MyBEEntry->st_query_id, so it can't be\n> useful to pg_stat_get_activity(), nor is it used there?\n>\n> I assume it's just a remnant from an earlier iteration of the code?\n\nAh indeed! This was quite a long thread so I didn't try to see when\nthat changed. I also now realize that I made a typo in the patch\nwhere I s/loop/look/ which was then changed to s/look/lock/. The\ncomment should be something like:\n\n/*\n* There's no need for a loop around pgstat_begin_read_activity /\n* pgstat_end_read_activity here as it's only called from the same backend\n* which means that there won't be concurrent writes.\n*/\n\n\n", "msg_date": "Mon, 9 Aug 2021 11:29:24 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: elog.c query_id support vs shutdown" }, { "msg_contents": "On Mon, Aug 09, 2021 at 11:29:24AM +0800, Julien Rouhaud wrote:\n> Ah indeed! This was quite a long thread so I didn't try to see when\n> that changed. I also now realize that I made a typo in the patch\n> where I s/loop/look/ which was then changed to s/look/lock/. The\n> comment should be something like:\n\nThe thread of this open item is now idle for 10 days and there does\nnot seem to be a lot of progress. Bruce, this is assigned to you.\nAre you planning to look at it?\n--\nMichael", "msg_date": "Thu, 19 Aug 2021 16:05:26 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: elog.c query_id support vs shutdown" }, { "msg_contents": "On Thu, Aug 19, 2021 at 3:05 PM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> The thread of this open item is now idle for 10 days and there does\n> not seem to be a lot of progress. Bruce, this is assigned to you.\n> Are you planning to look at it?\n\nI'm really sorry for the lack of answer on my side, I had too many\nduties at work to thoroughly look at the implication of clearing\nMyBEEntry in the pgstat_beshutdown_hook :(\n\nWith what I've seen so far I didn't find any evidence that it could\nlead to any new problem (it should actually make things slightly\nsafer) and couldn't hit any issue with some testing. Opinion from\nsomeone more familiar with pgstats is of course welcome.\n\nWhile reading the various code, I also found this incorrect comment in\nbackend_status.c:\n\n/* exposed so that progress.c can access it */\nPgBackendStatus *MyBEEntry = NULL;\n\nprogress.c was apparently renamed to backend_progress.c sometime\nduring e1025044 development (Split backend status and progress related\nfunctionality out of pgstat.c.).\n\nSo I'm +1 for the fix originally suggested by Andres.\n\n\n", "msg_date": "Thu, 19 Aug 2021 15:29:40 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: elog.c query_id support vs shutdown" }, { "msg_contents": "On Thu, Aug 19, 2021 at 03:29:40PM +0800, Julien Rouhaud wrote:\n> On Thu, Aug 19, 2021 at 3:05 PM Michael Paquier <michael@paquier.xyz> wrote:\n> >\n> > The thread of this open item is now idle for 10 days and there does\n> > not seem to be a lot of progress. Bruce, this is assigned to you.\n> > Are you planning to look at it?\n> \n> I'm really sorry for the lack of answer on my side, I had too many\n> duties at work to thoroughly look at the implication of clearing\n> MyBEEntry in the pgstat_beshutdown_hook :(\n> \n> With what I've seen so far I didn't find any evidence that it could\n> lead to any new problem (it should actually make things slightly\n> safer) and couldn't hit any issue with some testing. Opinion from\n> someone more familiar with pgstats is of course welcome.\n\nOkay. Would you like to write a patch then?\n--\nMichael", "msg_date": "Thu, 19 Aug 2021 17:05:01 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: elog.c query_id support vs shutdown" }, { "msg_contents": "On 2021-08-19 17:05:01 +0900, Michael Paquier wrote:\n> Okay. Would you like to write a patch then?\n\nI'll push something in a bit...\n\n- Andres\n\n\n", "msg_date": "Thu, 19 Aug 2021 01:10:55 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: elog.c query_id support vs shutdown" }, { "msg_contents": "On 2021-08-19 01:10:55 -0700, Andres Freund wrote:\n> On 2021-08-19 17:05:01 +0900, Michael Paquier wrote:\n> > Okay. Would you like to write a patch then?\n> \n> I'll push something in a bit...\n\nDone.\n\n\n", "msg_date": "Thu, 19 Aug 2021 05:20:52 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: elog.c query_id support vs shutdown" }, { "msg_contents": "On Thu, Aug 19, 2021 at 8:20 PM Andres Freund <andres@anarazel.de> wrote:\n>\n> On 2021-08-19 01:10:55 -0700, Andres Freund wrote:\n> > On 2021-08-19 17:05:01 +0900, Michael Paquier wrote:\n> > > Okay. Would you like to write a patch then?\n> >\n> > I'll push something in a bit...\n>\n> Done.\n\nThanks!\n\n\n", "msg_date": "Thu, 19 Aug 2021 21:07:27 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: elog.c query_id support vs shutdown" }, { "msg_contents": "On Thu, Aug 19, 2021 at 05:20:52AM -0700, Andres Freund wrote:\n> On 2021-08-19 01:10:55 -0700, Andres Freund wrote:\n> > On 2021-08-19 17:05:01 +0900, Michael Paquier wrote:\n> > > Okay. Would you like to write a patch then?\n> > \n> > I'll push something in a bit...\n> \n> Done.\n\nThanks. I was kind of wondering since there had not been a patch posted\nyet.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Thu, 19 Aug 2021 14:28:04 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: elog.c query_id support vs shutdown" }, { "msg_contents": "On Thu, Aug 19, 2021 at 05:20:52AM -0700, Andres Freund wrote:\n> Done.\n\nThanks. There does not seem to be anything left here, so I have\nmarked this open item as fixed.\n--\nMichael", "msg_date": "Fri, 20 Aug 2021 08:46:27 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: elog.c query_id support vs shutdown" } ]
[ { "msg_contents": "PSA a patch to fix trivial comment typo in newly committed TAP test.\n\n\"amd\" -> \"and\"\n\n------\nKind Regards,\nPeter Smith.\nFujitsu Australia", "msg_date": "Sun, 8 Aug 2021 16:14:36 +1000", "msg_from": "Peter Smith <smithpb2250@gmail.com>", "msg_from_op": true, "msg_subject": "Typo in subscription TAP test comment" }, { "msg_contents": "On Sun, Aug 8, 2021 at 11:44 AM Peter Smith <smithpb2250@gmail.com> wrote:\n>\n> PSA a patch to fix trivial comment typo in newly committed TAP test.\n>\n> \"amd\" -> \"and\"\n>\n\nI'll push this in some time.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Mon, 9 Aug 2021 08:41:29 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Typo in subscription TAP test comment" } ]
[ { "msg_contents": "I was wondering about the following code in explain.c\n\nchar buf[MAXINT8LEN + 1];\n\npg_lltoa(plannedstmt->queryId, buf);\nExplainPropertyText(\"Query Identifier\", buf, es);\n\nI thought it was a bit strange that we don't just use\nExplainPropertyInteger() instead of going to the trouble of building\nthe string with pg_lltoa().\n\nOn looking a little closer I also saw that plannedstmt->queryId is a\nuint64. I guess that we're showing this as an int64 so that it\nmatches the queryid column in the pg_stat_statements view? If so, I\nthink it's worth a comment to mention why we're not using\nExplainPropertyUInteger.\n\nAny objection to applying the attached to pg14 and master?\n\nDavid", "msg_date": "Sun, 8 Aug 2021 23:56:41 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Strange code in EXPLAIN for queryid" }, { "msg_contents": "On Sun, Aug 08, 2021 at 11:56:41PM +1200, David Rowley wrote:\n> \n> On looking a little closer I also saw that plannedstmt->queryId is a\n> uint64. I guess that we're showing this as an int64 so that it\n> matches the queryid column in the pg_stat_statements view?\n\nThe only reason we display it as an int64 rather than a uint64 is because\nthe SQL standard doesn't define such a type, and using numeric would add\nuseless overhead.\n\n> Any objection to applying the attached to pg14 and master?\n\nNo objection.\n\n\n", "msg_date": "Sun, 8 Aug 2021 22:06:32 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Strange code in EXPLAIN for queryid" }, { "msg_contents": "On Mon, 9 Aug 2021 at 02:06, Julien Rouhaud <rjuju123@gmail.com> wrote:\n> > Any objection to applying the attached to pg14 and master?\n>\n> No objection.\n\nThanks for looking. I've now pushed this to master and pg14.\n\nDavid\n\n\n", "msg_date": "Mon, 9 Aug 2021 15:49:25 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Strange code in EXPLAIN for queryid" } ]
[ { "msg_contents": "1) Are there free scripts for CREATE TYPE (native type), more advanced, <date> or <datetime> sorts of types out there, online, free for commercial use? With function support, too? Can someone reply with a link or a suggestion?\n\n2) How may I get PostgreSQL to output the create table statement(s) for one or more tables inside one database, without issuing instructions via the command line, but only inside a database login, as a query or pl/sql?\n\n3) I know that I can use COPY to import or export one database table between it and a *.csv file. Can I use it to do this with multiple TABLES and *.csv files specified in one COPY COMMAND, or not?\n\n4) In the absence of OS command line instructions, is there an internal postgresql way, via COPY or another function for example, to backup an entire database, with all its create table statements and all insert statements, and any other associated objects as well, in one hit? Or is this ill- advised?\n\n5) When setting up communication to remote databases on remote machines, I need to use the OPTIONS() function. It seems to require as its first function parameter, the schema of the table (the second parameter) that it wants to access. Can I supply a null schema, and still be able to reference the remote table, or must I also make use of IMPORT FOREIGN SCHEMA?\n\n6) How may I access, query, the log for the details of a normal table, or similar?\n\n7) I have found that the native trigonometry functions, namely the radians versions, do produce error results around key trigonometry input values. I have discovered that these errors persist, even if I cast the input parameter away from DOUBLE PRECISION and into DECIMAL. I would like to know if there are any freely available scripts out there that include Arbitrary Precision mathematical functions support that work on DECIMAL and not on DOUBLE PRECISION, that do not produce any error values around key inputs? Could someone refer me to a website that has a script that is such?\n\n\n\n\n\n\n\n\n1) Are there free scripts for CREATE TYPE (native type), more advanced, <date> or <datetime> sorts of types out there, online, free for commercial use? With function support, too? Can someone reply with a link or a suggestion?\n\n\n2) How may I get PostgreSQL to output the create table statement(s) for one or more tables inside one database, without issuing instructions via the command line, but only inside a database login, as a query or pl/sql?\n\n\n3) I know that I can use COPY to import or export one database table between it and a *.csv file. Can I use it to do this with multiple TABLES and *.csv files specified in one COPY COMMAND, or not?\n\n\n4) In the absence of OS command line instructions, is there an internal postgresql way, via COPY or another function for example, to backup an entire database, with all its create table statements and all insert statements, and any other associated objects\n as well, in one hit? Or is this ill- advised?\n\n\n5) When setting up communication to remote databases on remote machines, I need to use the OPTIONS() function. It seems to require as its first function parameter, the schema of the table (the second parameter) that it wants to access. Can I supply a null\n schema, and still be able to reference the remote table, or must I also make use of IMPORT FOREIGN SCHEMA?\n\n\n6) How may I access, query, the log for the details of a normal table, or similar?\n\n\n7) I have found that the native trigonometry functions, namely the radians versions, do produce error results around key trigonometry input values. I have discovered that these errors persist, even if I cast the input parameter away from DOUBLE PRECISION\n and into DECIMAL. I would like to know if there are any freely available scripts out there that include Arbitrary Precision mathematical functions support that work on DECIMAL and not on DOUBLE PRECISION, that do not produce any error values around key inputs?\n Could someone refer me to a website that has a script that is such?", "msg_date": "Mon, 9 Aug 2021 05:14:07 +0000", "msg_from": "A Z <poweruserm@live.com.au>", "msg_from_op": true, "msg_subject": "Advanced Questions about PostgreSQL" }, { "msg_contents": "On Mon, 9 Aug 2021 at 17:14, A Z <poweruserm@live.com.au> wrote:\n>\n> 1) Are there free scripts for CREATE TYPE (native type), more advanced, <date> or <datetime> sorts of types out there, online, free for commercial use? With function support, too? Can someone reply with a link or a suggestion?\n>\n> 2) How may I get PostgreSQL to output the create table statement(s) for one or more tables inside one database, without issuing instructions via the command line, but only inside a database login, as a query or pl/sql?\n>\n> 3) I know that I can use COPY to import or export one database table between it and a *.csv file. Can I use it to do this with multiple TABLES and *.csv files specified in one COPY COMMAND, or not?\n>\n> 4) In the absence of OS command line instructions, is there an internal postgresql way, via COPY or another function for example, to backup an entire database, with all its create table statements and all insert statements, and any other associated objects as well, in one hit? Or is this ill- advised?\n>\n> 5) When setting up communication to remote databases on remote machines, I need to use the OPTIONS() function. It seems to require as its first function parameter, the schema of the table (the second parameter) that it wants to access. Can I supply a null schema, and still be able to reference the remote table, or must I also make use of IMPORT FOREIGN SCHEMA?\n>\n> 6) How may I access, query, the log for the details of a normal table, or similar?\n>\n> 7) I have found that the native trigonometry functions, namely the radians versions, do produce error results around key trigonometry input values. I have discovered that these errors persist, even if I cast the input parameter away from DOUBLE PRECISION and into DECIMAL. I would like to know if there are any freely available scripts out there that include Arbitrary Precision mathematical functions support that work on DECIMAL and not on DOUBLE PRECISION, that do not produce any error values around key inputs? Could someone refer me to a website that has a script that is such?\n\nThis is the wrong mailing list for this type of thing.\n\nI suggest you review the answers that you've already received to these\nquestions in the general mailing list. They all look like general\nquestions to me.\n\nIf you're not happy with the answers you get there, then see if you\ncan get someone to expand on the existing answer or provide further\ndetails that might help them help you.\n\nIgnoring everyone that's tried to help you is likely not a good way\nfor you to obtain the help you need.\n\nDavid\n\n\n", "msg_date": "Mon, 9 Aug 2021 17:33:16 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Advanced Questions about PostgreSQL" }, { "msg_contents": "\nOn 8/9/21 1:33 AM, David Rowley wrote:\n> On Mon, 9 Aug 2021 at 17:14, A Z <poweruserm@live.com.au> wrote:\n>>\n>> 2) How may I get PostgreSQL to output the create table statement(s) for one or more tables inside one database, without issuing instructions via the command line, but only inside a database login, as a query or pl/sql?\n\n\n\nWatch this space.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Mon, 9 Aug 2021 08:09:13 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: Advanced Questions about PostgreSQL" } ]
[ { "msg_contents": "Hi,\nI am able to hit \"ERROR: cache lookup failed for function %d\" while I am\ndropping function from another session.\n\n*Reproducible steps are as(I tried on current head d8a75b1308b133502ae3):*\n\n*Step 1) Fire below query from session-1 to create a function:*\ncreate function fun1(int) returns record as ' DECLARE retval RECORD;\nBEGIN SELECT\nINTO retval 5, 10, 15; RETURN retval;\nEND;' language plpgsql;\n\n*Step 2)* Attach PID of session-1 into gdb and set a breakpoint into\ninternal_get_result_type and then press c.\n(gdb) b internal_get_result_type Breakpoint 1 at 0x5565dd4f3ce4: file\nfuncapi.c, line 325. (gdb) c\nContinuing.\n\n*Step 3)* Fire below select command from session-1:\nSELECT * FROM fun1(1500) AS (a int, b int, c int);\n\n*Step 3) Open session-2 and drop the function:*\npsql (15devel) Type \"help\" for help. postgres=# drop function fun1; DROP\nFUNCTION\npostgres=#\n\n*Step 4)* Press 'c' in gdb for 2 times and we will get an error in the 1st\nsession.\n(gdb) c Continuing. Breakpoint 1, internal_get_result_type (funcid=16384,\ncall_expr=0x5565de885af0, rsinfo=0x0, resultTypeId=0x7ffc94572608,\nresultTupleDesc=0x7ffc94572628) at funcapi.c:325 (gdb) c\nContinuing.\n\npostgres=# SELECT * FROM fun1(1500) AS (a int, b int, c int);\nERROR: cache lookup failed for function 16384\n*Call stack of error:*\n\n> Breakpoint 2, errfinish (filename=0x55e0b8907c6f \"funcapi.c\", lineno=336,\n> funcname=0x55e0b89083a0 <__func__.23015> \"internal_get_result_type\") at\n> elog.c:515\n> 515 ErrorData *edata = &errordata[errordata_stack_depth];\n> (gdb) bt\n> #0 errfinish (filename=0x55e0b8907c6f \"funcapi.c\", lineno=336,\n> funcname=0x55e0b89083a0 <__func__.23015> \"internal_get_result_type\") at\n> elog.c:515\n> #1 0x000055e0b86abdaf in internal_get_result_type (funcid=16384,\n> call_expr=0x55e0ba9e2ad0, rsinfo=0x0, resultTypeId=0x7ffcb7ca4918,\n> resultTupleDesc=0x7ffcb7ca4938)\n> at funcapi.c:336\n> #2 0x000055e0b86ab6d0 in get_expr_result_type (expr=0x55e0ba9e2ad0,\n> resultTypeId=0x7ffcb7ca4918, resultTupleDesc=0x7ffcb7ca4938) at\n> funcapi.c:230\n> #3 0x000055e0b7fef027 in ExecInitFunctionScan (node=0x55e0ba9e3cd0,\n> estate=0x55e0ba9d2fe0, eflags=16) at nodeFunctionscan.c:370\n> #4 0x000055e0b7fbb408 in ExecInitNode (node=0x55e0ba9e3cd0,\n> estate=0x55e0ba9d2fe0, eflags=16) at execProcnode.c:254\n> #5 0x000055e0b7faa1d5 in InitPlan (queryDesc=0x55e0ba926f50, eflags=16)\n> at execMain.c:936\n> #6 0x000055e0b7fa84b6 in standard_ExecutorStart\n> (queryDesc=0x55e0ba926f50, eflags=16) at execMain.c:263\n> #7 0x000055e0b7fa7fc7 in ExecutorStart (queryDesc=0x55e0ba926f50,\n> eflags=0) at execMain.c:143\n> #8 0x000055e0b83ba8de in PortalStart (portal=0x55e0ba968870, params=0x0,\n> eflags=0, snapshot=0x0) at pquery.c:512\n> #9 0x000055e0b83ae112 in exec_simple_query (query_string=0x55e0ba906760\n> \"SELECT * FROM fun1(1500) AS (a int, b int, c int);\") at postgres.c:1175\n> #10 0x000055e0b83b7a86 in PostgresMain (argc=1, argv=0x7ffcb7ca4f70,\n> dbname=0x55e0ba932770 \"postgres\", username=0x55e0ba932748 \"mahendrathalor\")\n> at postgres.c:4488\n> #11 0x000055e0b825161b in BackendRun (port=0x55e0ba929730) at\n> postmaster.c:4519\n> #12 0x000055e0b8250971 in BackendStartup (port=0x55e0ba929730) at\n> postmaster.c:4241\n> #13 0x000055e0b8248a1b in ServerLoop () at postmaster.c:1758\n> #14 0x000055e0b8247c18 in PostmasterMain (argc=3, argv=0x55e0ba8fee70) at\n> postmaster.c:1430\n> #15 0x000055e0b808dbe9 in main (argc=3, argv=0x55e0ba8fee70) at main.c:199\n>\n\n cache lookup failed errors are never an expected behavior(Thanks Robert\nHass for your opinion) so I think we should fix this error.\n\nI haven't debugged it so I will debug it and will post my findings in the\ncoming days.\n\n-- \nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n\nHi,I am able to hit \"ERROR:  cache lookup failed for function %d\" while I am dropping function from another session.Reproducible steps are as(I tried on current head d8a75b1308b133502ae3):Step 1) Fire below query from session-1 to create a function:create function fun1(int) returns record as ' \nDECLARE \nretval RECORD; \nBEGIN \nSELECT INTO retval 5, 10, 15; \nRETURN retval; \nEND;' language plpgsql; \nStep 2) Attach PID of session-1 into gdb and set a breakpoint into internal_get_result_type and then press c.(gdb) b internal_get_result_type\nBreakpoint 1 at 0x5565dd4f3ce4: file funcapi.c, line 325.\n(gdb) c\nContinuing.\nStep 3) Fire below select command from session-1: SELECT * FROM fun1(1500) AS (a int, b int, c int);Step 3) Open session-2 and drop the function:psql (15devel)\nType \"help\" for help.\n\npostgres=# drop function fun1;\nDROP FUNCTION\npostgres=#\nStep 4) Press 'c' in gdb for 2 times and we will get an error in the 1st session.(gdb) c\nContinuing.\n\nBreakpoint 1, internal_get_result_type (funcid=16384, call_expr=0x5565de885af0, rsinfo=0x0, resultTypeId=0x7ffc94572608, resultTupleDesc=0x7ffc94572628) at funcapi.c:325\n(gdb) c\nContinuing.\npostgres=# SELECT * FROM fun1(1500) AS (a int, b int, c int);ERROR: cache lookup failed for function 16384Call stack of error:Breakpoint 2, errfinish (filename=0x55e0b8907c6f \"funcapi.c\", lineno=336, funcname=0x55e0b89083a0 <__func__.23015> \"internal_get_result_type\") at elog.c:515515\t\tErrorData  *edata = &errordata[errordata_stack_depth];(gdb) bt#0  errfinish (filename=0x55e0b8907c6f \"funcapi.c\", lineno=336, funcname=0x55e0b89083a0 <__func__.23015> \"internal_get_result_type\") at elog.c:515#1  0x000055e0b86abdaf in internal_get_result_type (funcid=16384, call_expr=0x55e0ba9e2ad0, rsinfo=0x0, resultTypeId=0x7ffcb7ca4918, resultTupleDesc=0x7ffcb7ca4938)    at funcapi.c:336#2  0x000055e0b86ab6d0 in get_expr_result_type (expr=0x55e0ba9e2ad0, resultTypeId=0x7ffcb7ca4918, resultTupleDesc=0x7ffcb7ca4938) at funcapi.c:230#3  0x000055e0b7fef027 in ExecInitFunctionScan (node=0x55e0ba9e3cd0, estate=0x55e0ba9d2fe0, eflags=16) at nodeFunctionscan.c:370#4  0x000055e0b7fbb408 in ExecInitNode (node=0x55e0ba9e3cd0, estate=0x55e0ba9d2fe0, eflags=16) at execProcnode.c:254#5  0x000055e0b7faa1d5 in InitPlan (queryDesc=0x55e0ba926f50, eflags=16) at execMain.c:936#6  0x000055e0b7fa84b6 in standard_ExecutorStart (queryDesc=0x55e0ba926f50, eflags=16) at execMain.c:263#7  0x000055e0b7fa7fc7 in ExecutorStart (queryDesc=0x55e0ba926f50, eflags=0) at execMain.c:143#8  0x000055e0b83ba8de in PortalStart (portal=0x55e0ba968870, params=0x0, eflags=0, snapshot=0x0) at pquery.c:512#9  0x000055e0b83ae112 in exec_simple_query (query_string=0x55e0ba906760 \"SELECT * FROM fun1(1500) AS (a int, b int, c int);\") at postgres.c:1175#10 0x000055e0b83b7a86 in PostgresMain (argc=1, argv=0x7ffcb7ca4f70, dbname=0x55e0ba932770 \"postgres\", username=0x55e0ba932748 \"mahendrathalor\") at postgres.c:4488#11 0x000055e0b825161b in BackendRun (port=0x55e0ba929730) at postmaster.c:4519#12 0x000055e0b8250971 in BackendStartup (port=0x55e0ba929730) at postmaster.c:4241#13 0x000055e0b8248a1b in ServerLoop () at postmaster.c:1758#14 0x000055e0b8247c18 in PostmasterMain (argc=3, argv=0x55e0ba8fee70) at postmaster.c:1430#15 0x000055e0b808dbe9 in main (argc=3, argv=0x55e0ba8fee70) at main.c:199 cache lookup failed errors are never an expected behavior(Thanks Robert Hass for your opinion) so I think we should fix this error.I haven't debugged it so I will debug it and will post my findings in the coming days. -- Thanks and RegardsMahendra Singh ThalorEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Mon, 9 Aug 2021 11:07:13 +0530", "msg_from": "Mahendra Singh Thalor <mahi6run@gmail.com>", "msg_from_op": true, "msg_subject": "\"ERROR: cache lookup failed for function %d\" while dropping function\n from another session" }, { "msg_contents": "On Mon, 9 Aug 2021 at 11:07, Mahendra Singh Thalor <mahi6run@gmail.com>\nwrote:\n>\n> Hi,\n> I am able to hit \"ERROR: cache lookup failed for function %d\" while I am\ndropping function from another session.\n>\n> Reproducible steps are as(I tried on current head d8a75b1308b133502ae3):\n>\n> Step 1) Fire below query from session-1 to create a function:\n>\n> create function fun1(int) returns record as ' DECLARE retval RECORD;\nBEGIN SELECT INTO retval 5, 10, 15; RETURN retval;\n> END;' language plpgsql;\n>\n> Step 2) Attach PID of session-1 into gdb and set a breakpoint into\ninternal_get_result_type and then press c.\n>\n> (gdb) b internal_get_result_type Breakpoint 1 at 0x5565dd4f3ce4: file\nfuncapi.c, line 325. (gdb) c\n> Continuing.\n>\n> Step 3) Fire below select command from session-1:\n>\n> SELECT * FROM fun1(1500) AS (a int, b int, c int);\n>\n> Step 3) Open session-2 and drop the function:\n>\n> psql (15devel) Type \"help\" for help. postgres=# drop function fun1; DROP\nFUNCTION\n> postgres=#\n>\n> Step 4) Press 'c' in gdb for 2 times and we will get an error in the 1st\nsession.\n>\n> (gdb) c Continuing. Breakpoint 1, internal_get_result_type (funcid=16384,\ncall_expr=0x5565de885af0, rsinfo=0x0, resultTypeId=0x7ffc94572608,\nresultTupleDesc=0x7ffc94572628) at funcapi.c:325 (gdb) c\n> Continuing.\n>\n> postgres=# SELECT * FROM fun1(1500) AS (a int, b int, c int);\n> ERROR: cache lookup failed for function 16384\n>\n> Call stack of error:\n>>\n>> Breakpoint 2, errfinish (filename=0x55e0b8907c6f \"funcapi.c\",\nlineno=336, funcname=0x55e0b89083a0 <__func__.23015>\n\"internal_get_result_type\") at elog.c:515\n>> 515 ErrorData *edata = &errordata[errordata_stack_depth];\n>> (gdb) bt\n>> #0 errfinish (filename=0x55e0b8907c6f \"funcapi.c\", lineno=336,\nfuncname=0x55e0b89083a0 <__func__.23015> \"internal_get_result_type\") at\nelog.c:515\n>> #1 0x000055e0b86abdaf in internal_get_result_type (funcid=16384,\ncall_expr=0x55e0ba9e2ad0, rsinfo=0x0, resultTypeId=0x7ffcb7ca4918,\nresultTupleDesc=0x7ffcb7ca4938)\n>> at funcapi.c:336\n>> #2 0x000055e0b86ab6d0 in get_expr_result_type (expr=0x55e0ba9e2ad0,\nresultTypeId=0x7ffcb7ca4918, resultTupleDesc=0x7ffcb7ca4938) at\nfuncapi.c:230\n>> #3 0x000055e0b7fef027 in ExecInitFunctionScan (node=0x55e0ba9e3cd0,\nestate=0x55e0ba9d2fe0, eflags=16) at nodeFunctionscan.c:370\n>> #4 0x000055e0b7fbb408 in ExecInitNode (node=0x55e0ba9e3cd0,\nestate=0x55e0ba9d2fe0, eflags=16) at execProcnode.c:254\n>> #5 0x000055e0b7faa1d5 in InitPlan (queryDesc=0x55e0ba926f50, eflags=16)\nat execMain.c:936\n>> #6 0x000055e0b7fa84b6 in standard_ExecutorStart\n(queryDesc=0x55e0ba926f50, eflags=16) at execMain.c:263\n>> #7 0x000055e0b7fa7fc7 in ExecutorStart (queryDesc=0x55e0ba926f50,\neflags=0) at execMain.c:143\n>> #8 0x000055e0b83ba8de in PortalStart (portal=0x55e0ba968870,\nparams=0x0, eflags=0, snapshot=0x0) at pquery.c:512\n>> #9 0x000055e0b83ae112 in exec_simple_query (query_string=0x55e0ba906760\n\"SELECT * FROM fun1(1500) AS (a int, b int, c int);\") at postgres.c:1175\n>> #10 0x000055e0b83b7a86 in PostgresMain (argc=1, argv=0x7ffcb7ca4f70,\ndbname=0x55e0ba932770 \"postgres\", username=0x55e0ba932748 \"mahendrathalor\")\nat postgres.c:4488\n>> #11 0x000055e0b825161b in BackendRun (port=0x55e0ba929730) at\npostmaster.c:4519\n>> #12 0x000055e0b8250971 in BackendStartup (port=0x55e0ba929730) at\npostmaster.c:4241\n>> #13 0x000055e0b8248a1b in ServerLoop () at postmaster.c:1758\n>> #14 0x000055e0b8247c18 in PostmasterMain (argc=3, argv=0x55e0ba8fee70)\nat postmaster.c:1430\n>> #15 0x000055e0b808dbe9 in main (argc=3, argv=0x55e0ba8fee70) at\nmain.c:199\n>\n>\n> cache lookup failed errors are never an expected behavior(Thanks Robert\nHass for your opinion) so I think we should fix this error.\n>\n> I haven't debugged it so I will debug it and will post my findings in the\ncoming days.\n>\n\nI googled it and found that we already discussed this issue in another\nthread.\n\nLink:\nhttps://www.postgresql.org/message-id/flat/NX26BD7O.SQ6NCQDL.Z4KK4FBY%40HXCHZXMY.EBBFSJQH.OUMOBSJN\n\nI reproduced this issue locally (to avoid race conditions, I just had the\n> function drop itself ;-)) and traced the site of the failure to this\n> bit in plpgsql function exit:\n>\n> /*\n> * Need to look up the expected result type. XXX would be\n> * better to cache the tupdesc instead of repeating\n> * get_call_result_type(), but the only easy place to save it\n> * is in the PLpgSQL_function struct, and that's too\n> * long-lived: composite types could change during the\n> * existence of a PLpgSQL_function.\n> */\n> switch (get_call_result_type(fcinfo, &resultTypeId, &tupdesc))\n>\n> The catalog access inside get_call_result_type is fairly essential,\n> because this function has OUT parameters, so its pg_proc row is the\n> ultimate source of truth about what it returns. We could imagine\n> caching the info earlier during function execution, but as the comment\n> says, that has its own failure modes ... and they're more important\n> ones in practice. So I'm afraid there's not much to be done to\n> improve this.\n>\n> regards, tom lane\n>\n\n-- \nThanks and Regards\nMahendra Singh Thalor\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Mon, 9 Aug 2021 at 11:07, Mahendra Singh Thalor <mahi6run@gmail.com> wrote:>> Hi,> I am able to hit \"ERROR:  cache lookup failed for function %d\" while I am dropping function from another session.>> Reproducible steps are as(I tried on current head d8a75b1308b133502ae3):>> Step 1) Fire below query from session-1 to create a function:>> create function fun1(int) returns record as ' DECLARE retval RECORD; BEGIN SELECT INTO retval 5, 10, 15; RETURN retval;> END;' language plpgsql;>> Step 2) Attach PID of session-1 into gdb and set a breakpoint into internal_get_result_type and then press c.>> (gdb) b internal_get_result_type Breakpoint 1 at 0x5565dd4f3ce4: file funcapi.c, line 325. (gdb) c> Continuing.>> Step 3) Fire below select command from session-1:>> SELECT * FROM fun1(1500) AS (a int, b int, c int);>> Step 3) Open session-2 and drop the function:>> psql (15devel) Type \"help\" for help. postgres=# drop function fun1; DROP FUNCTION> postgres=#>> Step 4) Press 'c' in gdb for 2 times and we will get an error in the 1st session.>> (gdb) c Continuing. Breakpoint 1, internal_get_result_type (funcid=16384, call_expr=0x5565de885af0, rsinfo=0x0, resultTypeId=0x7ffc94572608, resultTupleDesc=0x7ffc94572628) at funcapi.c:325 (gdb) c> Continuing.>> postgres=# SELECT * FROM fun1(1500) AS (a int, b int, c int);> ERROR: cache lookup failed for function 16384>> Call stack of error:>>>> Breakpoint 2, errfinish (filename=0x55e0b8907c6f \"funcapi.c\", lineno=336, funcname=0x55e0b89083a0 <__func__.23015> \"internal_get_result_type\") at elog.c:515>> 515 ErrorData  *edata = &errordata[errordata_stack_depth];>> (gdb) bt>> #0  errfinish (filename=0x55e0b8907c6f \"funcapi.c\", lineno=336, funcname=0x55e0b89083a0 <__func__.23015> \"internal_get_result_type\") at elog.c:515>> #1  0x000055e0b86abdaf in internal_get_result_type (funcid=16384, call_expr=0x55e0ba9e2ad0, rsinfo=0x0, resultTypeId=0x7ffcb7ca4918, resultTupleDesc=0x7ffcb7ca4938)>>     at funcapi.c:336>> #2  0x000055e0b86ab6d0 in get_expr_result_type (expr=0x55e0ba9e2ad0, resultTypeId=0x7ffcb7ca4918, resultTupleDesc=0x7ffcb7ca4938) at funcapi.c:230>> #3  0x000055e0b7fef027 in ExecInitFunctionScan (node=0x55e0ba9e3cd0, estate=0x55e0ba9d2fe0, eflags=16) at nodeFunctionscan.c:370>> #4  0x000055e0b7fbb408 in ExecInitNode (node=0x55e0ba9e3cd0, estate=0x55e0ba9d2fe0, eflags=16) at execProcnode.c:254>> #5  0x000055e0b7faa1d5 in InitPlan (queryDesc=0x55e0ba926f50, eflags=16) at execMain.c:936>> #6  0x000055e0b7fa84b6 in standard_ExecutorStart (queryDesc=0x55e0ba926f50, eflags=16) at execMain.c:263>> #7  0x000055e0b7fa7fc7 in ExecutorStart (queryDesc=0x55e0ba926f50, eflags=0) at execMain.c:143>> #8  0x000055e0b83ba8de in PortalStart (portal=0x55e0ba968870, params=0x0, eflags=0, snapshot=0x0) at pquery.c:512>> #9  0x000055e0b83ae112 in exec_simple_query (query_string=0x55e0ba906760 \"SELECT * FROM fun1(1500) AS (a int, b int, c int);\") at postgres.c:1175>> #10 0x000055e0b83b7a86 in PostgresMain (argc=1, argv=0x7ffcb7ca4f70, dbname=0x55e0ba932770 \"postgres\", username=0x55e0ba932748 \"mahendrathalor\") at postgres.c:4488>> #11 0x000055e0b825161b in BackendRun (port=0x55e0ba929730) at postmaster.c:4519>> #12 0x000055e0b8250971 in BackendStartup (port=0x55e0ba929730) at postmaster.c:4241>> #13 0x000055e0b8248a1b in ServerLoop () at postmaster.c:1758>> #14 0x000055e0b8247c18 in PostmasterMain (argc=3, argv=0x55e0ba8fee70) at postmaster.c:1430>> #15 0x000055e0b808dbe9 in main (argc=3, argv=0x55e0ba8fee70) at main.c:199>>>  cache lookup failed errors are never an expected behavior(Thanks Robert Hass for your opinion) so I think we should fix this error.>> I haven't debugged it so I will debug it and will post my findings in the coming days.>I googled it and found that we already discussed this issue in another thread.Link: https://www.postgresql.org/message-id/flat/NX26BD7O.SQ6NCQDL.Z4KK4FBY%40HXCHZXMY.EBBFSJQH.OUMOBSJNI reproduced this issue locally (to avoid race conditions, I just had thefunction drop itself ;-)) and traced the site of the failure to thisbit in plpgsql function exit:\n /* * Need to look up the expected result type. XXX would be * better to cache the tupdesc instead of repeating * get_call_result_type(), but the only easy place to save it * is in the PLpgSQL_function struct, and that's too * long-lived: composite types could change during the * existence of a PLpgSQL_function. */ switch (get_call_result_type(fcinfo, &resultTypeId, &tupdesc))\nThe catalog access inside get_call_result_type is fairly essential,because this function has OUT parameters, so its pg_proc row is theultimate source of truth about what it returns. We could imaginecaching the info earlier during function execution, but as the commentsays, that has its own failure modes ... and they're more importantones in practice. So I'm afraid there's not much to be done toimprove this.\n\t\t\tregards, tom lane -- Thanks and RegardsMahendra Singh ThalorEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Mon, 9 Aug 2021 11:16:01 +0530", "msg_from": "Mahendra Singh Thalor <mahi6run@gmail.com>", "msg_from_op": true, "msg_subject": "Re: \"ERROR: cache lookup failed for function %d\" while dropping\n function from another session" } ]
[ { "msg_contents": "Our minor releases coming out this week will create a script when\npg_upgrade finishes that contains ALTER EXTENSION ... UPDATE commands\nfor extension that show updates in pg_available_extensions. However, I\nam unclear if all extensions that have updates are reported in\npg_available_extensions or support ALTER EXTENSION ... UPDATE, e.g.,\nPostGIS. Do the new pg_upgrade docs need to be more vague about this?\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Mon, 9 Aug 2021 09:10:26 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": true, "msg_subject": "Extension updates and pg_upgrade" } ]
[ { "msg_contents": "To reproduce, initialize a cluster with wal_level=minimal and\nmax_wal_senders=0. Then from psql:\n\n\\! mkdir /tmp/goose\n\nCHECKPOINT;\nCREATE TABLESPACE goose LOCATION '/tmp/goose';\nSET wal_skip_threshold=0;\nBEGIN;\nCREATE TABLE wild (a int, b text) TABLESPACE goose;\nINSERT INTO wild VALUES (1, 'chase');\nCOMMIT;\nSELECT * FROM wild;\n\nAs expected, you will see one row in table 'wild'. Now perform an\nimmediate shutdown. Restart the server. Table 'wild' is now empty. The\nproblem appears to be that tblspc_redo() calls\ncreate_tablespace_directories(), which says:\n\n /*\n * Our theory for replaying a CREATE is to forcibly drop the target\n * subdirectory if present, and then recreate it. This may be more\n * work than needed, but it is simple to implement.\n */\n\nUnfortunately, this theory (which dates to\nc86f467d18aa58e18fd85b560b46d8de014e6017, vintage 2010, by Bruce) is\ncorrect only with wal_level>minimal. At wal_level='minimal', we can\nreplay the record to recreate the relfilenode, but not the records\nthat would have created the contents. However, note that if the table\nis smaller than wal_skip_threshold, then we'll log full-page images of\nthe contents at commit time even at wal_level='minimal' after which we\nhave no problem. As far as I can see, this bug has \"always\" existed,\nbut before c6b92041d38512a4176ed76ad06f713d2e6c01a8 (2020, Noah) you\nwould have needed a different test case. Specifically, you would have\nneeded to use COPY to put the row in the table, and you would have\nneeded to omit setting wal_skip_threshold since it didn't exist yet.\n\nI don't presently have a specific idea about how to fix this.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 9 Aug 2021 13:08:42 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": true, "msg_subject": "replay of CREATE TABLESPACE eats data at wal_level=minimal" }, { "msg_contents": "On Mon, Aug 09, 2021 at 01:08:42PM -0400, Robert Haas wrote:\n> To reproduce, initialize a cluster with wal_level=minimal and\n> max_wal_senders=0. Then from psql:\n> \n> \\! mkdir /tmp/goose\n> \n> CHECKPOINT;\n> CREATE TABLESPACE goose LOCATION '/tmp/goose';\n> SET wal_skip_threshold=0;\n> BEGIN;\n> CREATE TABLE wild (a int, b text) TABLESPACE goose;\n> INSERT INTO wild VALUES (1, 'chase');\n> COMMIT;\n> SELECT * FROM wild;\n> \n> As expected, you will see one row in table 'wild'. Now perform an\n> immediate shutdown. Restart the server. Table 'wild' is now empty.\n\nThanks for finding the problem. It's a bad problem.\n\n> The problem appears to be that tblspc_redo() calls\n> create_tablespace_directories(), which says:\n> \n> /*\n> * Our theory for replaying a CREATE is to forcibly drop the target\n> * subdirectory if present, and then recreate it. This may be more\n> * work than needed, but it is simple to implement.\n> */\n> \n> Unfortunately, this theory (which dates to\n> c86f467d18aa58e18fd85b560b46d8de014e6017, vintage 2010, by Bruce) is\n> correct only with wal_level>minimal. At wal_level='minimal', we can\n> replay the record to recreate the relfilenode, but not the records\n> that would have created the contents. However, note that if the table\n> is smaller than wal_skip_threshold, then we'll log full-page images of\n> the contents at commit time even at wal_level='minimal' after which we\n> have no problem. As far as I can see, this bug has \"always\" existed,\n> but before c6b92041d38512a4176ed76ad06f713d2e6c01a8 (2020, Noah) you\n> would have needed a different test case. Specifically, you would have\n> needed to use COPY to put the row in the table, and you would have\n> needed to omit setting wal_skip_threshold since it didn't exist yet.\n\nAgreed.\n\n> I don't presently have a specific idea about how to fix this.\n\nCan't recovery just not delete the directory, create it if doesn't exist, and\nbe happy if it does exist? Like the attached WIP. If we think it's possible\nfor a crash during mkdir to leave a directory having the wrong permissions,\nadding a chmod would be in order.", "msg_date": "Mon, 9 Aug 2021 18:23:07 -0700", "msg_from": "Noah Misch <noah@leadboat.com>", "msg_from_op": false, "msg_subject": "Re: replay of CREATE TABLESPACE eats data at wal_level=minimal" }, { "msg_contents": "On Mon, Aug 9, 2021 at 9:23 PM Noah Misch <noah@leadboat.com> wrote:\n> > I don't presently have a specific idea about how to fix this.\n>\n> Can't recovery just not delete the directory, create it if doesn't exist, and\n> be happy if it does exist? Like the attached WIP. If we think it's possible\n> for a crash during mkdir to leave a directory having the wrong permissions,\n> adding a chmod would be in order.\n\nOh, yeah, I think that works, actually. I was imagining a few problems\nhere, but I don't think they really exist. The redo routines for files\nwithin the directory can't possibly care about having the old files\nerased for them, since that wouldn't be something that would normally\nhappen, if there were no recent CREATE TABLESPACE involved. And\nthere's code further down to remove and recreate the symlink, just in\ncase. So I think your proposed patch might be all we need.\n\n--\nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 10 Aug 2021 09:35:00 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": true, "msg_subject": "Re: replay of CREATE TABLESPACE eats data at wal_level=minimal" }, { "msg_contents": "On Tue, Aug 10, 2021 at 9:35 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> Oh, yeah, I think that works, actually. I was imagining a few problems\n> here, but I don't think they really exist. The redo routines for files\n> within the directory can't possibly care about having the old files\n> erased for them, since that wouldn't be something that would normally\n> happen, if there were no recent CREATE TABLESPACE involved. And\n> there's code further down to remove and recreate the symlink, just in\n> case. So I think your proposed patch might be all we need.\n\nNoah, do you plan to commit this?\n\nDoes anyone else want to review?\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 18 Aug 2021 10:47:24 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": true, "msg_subject": "Re: replay of CREATE TABLESPACE eats data at wal_level=minimal" }, { "msg_contents": "On Wed, Aug 18, 2021 at 10:47:24AM -0400, Robert Haas wrote:\n> On Tue, Aug 10, 2021 at 9:35 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > Oh, yeah, I think that works, actually. I was imagining a few problems\n> > here, but I don't think they really exist. The redo routines for files\n> > within the directory can't possibly care about having the old files\n> > erased for them, since that wouldn't be something that would normally\n> > happen, if there were no recent CREATE TABLESPACE involved. And\n> > there's code further down to remove and recreate the symlink, just in\n> > case. So I think your proposed patch might be all we need.\n> \n> Noah, do you plan to commit this?\n\nYes. I feel it needs a test case, which is the main reason I've queued the\ntask rather than just pushed what I posted last.\n\nOn Mon, Aug 09, 2021 at 06:23:07PM -0700, Noah Misch wrote:\n> If we think it's possible for a crash during mkdir to leave a directory\n> having the wrong permissions, adding a chmod would be in order.\n\nI wouldn't be surprised if it's possible under some NFS versions, considering\nbehavior like https://www.spinics.net/lists/linux-nfs/msg59044.html exists.\nHowever, nowhere else do we try to cope with this. Hence, the fix for\n$SUBJECT shouldn't change that pattern.\n\n\n", "msg_date": "Wed, 18 Aug 2021 22:32:10 -0700", "msg_from": "Noah Misch <noah@leadboat.com>", "msg_from_op": false, "msg_subject": "Re: replay of CREATE TABLESPACE eats data at wal_level=minimal" }, { "msg_contents": "On Wed, Aug 18, 2021 at 10:32:10PM -0700, Noah Misch wrote:\n> On Wed, Aug 18, 2021 at 10:47:24AM -0400, Robert Haas wrote:\n> > On Tue, Aug 10, 2021 at 9:35 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > > Oh, yeah, I think that works, actually. I was imagining a few problems\n> > > here, but I don't think they really exist. The redo routines for files\n> > > within the directory can't possibly care about having the old files\n> > > erased for them, since that wouldn't be something that would normally\n> > > happen, if there were no recent CREATE TABLESPACE involved. And\n> > > there's code further down to remove and recreate the symlink, just in\n> > > case. So I think your proposed patch might be all we need.\n> > \n> > Noah, do you plan to commit this?\n> \n> Yes. I feel it needs a test case, which is the main reason I've queued the\n> task rather than just pushed what I posted last.\n\nHere's what I plan to push. Besides adding a test, I modified things so\nCREATE TABLESPACE redo continues to report an error if a non-directory exists\nunder the name we seek to create. One could argue against covering that\ncorner case, but TablespaceCreateDbspace() does cover it.", "msg_date": "Sun, 22 Aug 2021 15:59:44 -0700", "msg_from": "Noah Misch <noah@leadboat.com>", "msg_from_op": false, "msg_subject": "Re: replay of CREATE TABLESPACE eats data at wal_level=minimal" }, { "msg_contents": "On Mon, Aug 23, 2021 at 4:29 AM Noah Misch <noah@leadboat.com> wrote:\n\n> On Wed, Aug 18, 2021 at 10:32:10PM -0700, Noah Misch wrote:\n> > On Wed, Aug 18, 2021 at 10:47:24AM -0400, Robert Haas wrote:\n> > > On Tue, Aug 10, 2021 at 9:35 AM Robert Haas <robertmhaas@gmail.com>\n> wrote:\n> > > > Oh, yeah, I think that works, actually. I was imagining a few\n> problems\n> > > > here, but I don't think they really exist. The redo routines for\n> files\n> > > > within the directory can't possibly care about having the old files\n> > > > erased for them, since that wouldn't be something that would normally\n> > > > happen, if there were no recent CREATE TABLESPACE involved. And\n> > > > there's code further down to remove and recreate the symlink, just in\n> > > > case. So I think your proposed patch might be all we need.\n> > >\n> > > Noah, do you plan to commit this?\n> >\n> > Yes. I feel it needs a test case, which is the main reason I've queued\n> the\n> > task rather than just pushed what I posted last.\n>\n> Here's what I plan to push. Besides adding a test,\n\n\nI have reproduced the issue of data inconsistency with CREATE TABLESPACE at\nwal_level=minimal,\nalso I have tested the fix with v0 and v1 patch, and come up with a similar\ntap-testcase(as in v1). The test case looks good.\n\n-- \n\nWith Regards,\nPrabhat Kumar Sahu\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Mon, Aug 23, 2021 at 4:29 AM Noah Misch <noah@leadboat.com> wrote:On Wed, Aug 18, 2021 at 10:32:10PM -0700, Noah Misch wrote:\n> On Wed, Aug 18, 2021 at 10:47:24AM -0400, Robert Haas wrote:\n> > On Tue, Aug 10, 2021 at 9:35 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > > Oh, yeah, I think that works, actually. I was imagining a few problems\n> > > here, but I don't think they really exist. The redo routines for files\n> > > within the directory can't possibly care about having the old files\n> > > erased for them, since that wouldn't be something that would normally\n> > > happen, if there were no recent CREATE TABLESPACE involved. And\n> > > there's code further down to remove and recreate the symlink, just in\n> > > case. So I think your proposed patch might be all we need.\n> > \n> > Noah, do you plan to commit this?\n> \n> Yes.  I feel it needs a test case, which is the main reason I've queued the\n> task rather than just pushed what I posted last.\n\nHere's what I plan to push.  Besides adding a test, I have reproduced the issue of data inconsistency with CREATE TABLESPACE at wal_level=minimal, also I have tested the fix with v0 and v1 patch, and come up with a similar tap-testcase(as in v1). The test case looks good.-- \nWith Regards,Prabhat Kumar SahuEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Mon, 23 Aug 2021 16:14:18 +0530", "msg_from": "Prabhat Sahu <prabhat.sahu@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: replay of CREATE TABLESPACE eats data at wal_level=minimal" }, { "msg_contents": "On Sun, Aug 22, 2021 at 6:59 PM Noah Misch <noah@leadboat.com> wrote:\n> Here's what I plan to push. Besides adding a test, I modified things so\n> CREATE TABLESPACE redo continues to report an error if a non-directory exists\n> under the name we seek to create. One could argue against covering that\n> corner case, but TablespaceCreateDbspace() does cover it.\n\nBy and large, LGTM, though perhaps it would be appropriate to also\ncredit me as the reporter of the issue.\n\nI feel it might be slightly better to highlight somewhere, either in\nthe commit message or in the comments, that removing the old directory\nis unsafe, because if wal_level=minimal, we may have no other copy of\nthe data. For me that's the key point here. I feel that the commit\nmessage and comments inside the patch explain rather thoroughly the\npossible consequences of the bug and why this particular fix was\nchosen, but they're not real explicit about why there was a bug at\nall.\n\nThanks very much for working on this.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 23 Aug 2021 09:08:44 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": true, "msg_subject": "Re: replay of CREATE TABLESPACE eats data at wal_level=minimal" }, { "msg_contents": "On Mon, Aug 23, 2021 at 09:08:44AM -0400, Robert Haas wrote:\n> On Sun, Aug 22, 2021 at 6:59 PM Noah Misch <noah@leadboat.com> wrote:\n> > Here's what I plan to push. Besides adding a test, I modified things so\n> > CREATE TABLESPACE redo continues to report an error if a non-directory exists\n> > under the name we seek to create. One could argue against covering that\n> > corner case, but TablespaceCreateDbspace() does cover it.\n> \n> By and large, LGTM, though perhaps it would be appropriate to also\n> credit me as the reporter of the issue.\n> \n> I feel it might be slightly better to highlight somewhere, either in\n> the commit message or in the comments, that removing the old directory\n> is unsafe, because if wal_level=minimal, we may have no other copy of\n> the data. For me that's the key point here. I feel that the commit\n> message and comments inside the patch explain rather thoroughly the\n> possible consequences of the bug and why this particular fix was\n> chosen, but they're not real explicit about why there was a bug at\n> all.\n\nSounds good. I think the log message is the optimal place:\n\n===\nFix data loss in wal_level=minimal crash recovery of CREATE TABLESPACE.\n\nIf the system crashed between CREATE TABLESPACE and the next checkpoint,\nthe result could be some files in the tablespace unexpectedly containing\nno rows. Affected files would be those for which the system did not\nwrite WAL; see the wal_skip_threshold documentation. Before v13, a\ndifferent set of conditions governed the writing of WAL; see v12's\n<sect2 id=\"populate-pitr\">. (The v12 conditions were broader in some\nways and narrower in others.) Users may want to audit non-default\ntablespaces for unexpected short files. The bug could have truncated an\nindex without affecting the associated table, and reindexing the index\nwould fix that particular problem.\n\nThis fixes the bug by making create_tablespace_directories() more like\nTablespaceCreateDbspace(). create_tablespace_directories() was\nrecursively removing tablespace contents, reasoning that WAL redo would\nrecreate everything removed that way. That assumption holds for other\nwal_level values. Under wal_level=minimal, the old approach could\ndelete files for which no other copy existed. Back-patch to 9.6 (all\nsupported versions).\n\nReviewed by Robert Haas and Prabhat Sahu. Reported by Robert Haas.\n\nDiscussion: https://postgr.es/m/CA+TgmoaLO9ncuwvr2nN-J4VEP5XyAcy=zKiHxQzBbFRxxGxm0w@mail.gmail.com\n===\n\n\n", "msg_date": "Tue, 24 Aug 2021 22:21:40 -0700", "msg_from": "Noah Misch <noah@leadboat.com>", "msg_from_op": false, "msg_subject": "Re: replay of CREATE TABLESPACE eats data at wal_level=minimal" }, { "msg_contents": "On Wed, Aug 25, 2021 at 1:21 AM Noah Misch <noah@leadboat.com> wrote:\n> Sounds good. I think the log message is the optimal place:\n\nLooks awesome.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 25 Aug 2021 08:03:24 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": true, "msg_subject": "Re: replay of CREATE TABLESPACE eats data at wal_level=minimal" }, { "msg_contents": "On Wed, Aug 25, 2021 at 8:03 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> On Wed, Aug 25, 2021 at 1:21 AM Noah Misch <noah@leadboat.com> wrote:\n> > Sounds good. I think the log message is the optimal place:\n>\n> Looks awesome.\n\nIs there anything still standing in the way of committing this?\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 2 Sep 2021 11:28:27 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": true, "msg_subject": "Re: replay of CREATE TABLESPACE eats data at wal_level=minimal" }, { "msg_contents": "On Thu, Sep 02, 2021 at 11:28:27AM -0400, Robert Haas wrote:\n> On Wed, Aug 25, 2021 at 8:03 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > On Wed, Aug 25, 2021 at 1:21 AM Noah Misch <noah@leadboat.com> wrote:\n> > > Sounds good. I think the log message is the optimal place:\n> >\n> > Looks awesome.\n> \n> Is there anything still standing in the way of committing this?\n\nI pushed it as commit 97ddda8.\n\n\n", "msg_date": "Thu, 2 Sep 2021 19:56:08 -0700", "msg_from": "Noah Misch <noah@leadboat.com>", "msg_from_op": false, "msg_subject": "Re: replay of CREATE TABLESPACE eats data at wal_level=minimal" }, { "msg_contents": "On Thu, Sep 2, 2021 at 10:56 PM Noah Misch <noah@leadboat.com> wrote:\n> > Is there anything still standing in the way of committing this?\n>\n> I pushed it as commit 97ddda8.\n\nOh, thanks. Sorry, I had missed that.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 3 Sep 2021 10:12:49 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": true, "msg_subject": "Re: replay of CREATE TABLESPACE eats data at wal_level=minimal" } ]
[ { "msg_contents": "Hi everyone,\nI am doding some jobs in postgres. I want to add \"^=\" like \"!=\" and \"<>\".\n\nSo i modify the code in scan.l.\nPlan 1:\nequals_greater \"=>\"\nless_equals \"<=\"\ngreater_equals \">=\"\nless_greater \"<>\"\nnot_equals (!=|\\^=)\n\nMaybe i can delete some code to make the code more simple.\nPlan 2:\nequals_greater \"=>\"\nless_equals \"<=\"\ngreater_equals \">=\"\nless_greater \"<>\" (delete this definition)\nnot_equals (!=|\\^=|<>)\n\nBefore send patch review, I want to konw whether the postgres maintainer will approve my changes.\n\nSo, please give me some advice.\n\nThank you!\nHi everyone,I am doding some jobs in postgres. I want to add \"^=\" like \"!=\" and \"<>\".So i modify the code in scan.l.Plan 1:equals_greater \"=>\"less_equals  \"<=\"greater_equals \">=\"less_greater \"<>\"not_equals  (!=|\\^=) Maybe i can delete some code to make the code more simple.Plan 2: equals_greater \"=>\"less_equals  \"<=\"greater_equals \">=\"less_greater \"<>\" (delete this definition)not_equals  (!=|\\^=|<>)Before send patch review, I want to konw whether the postgres maintainer will approve my changes.So, please give me some advice.Thank you!", "msg_date": "Tue, 10 Aug 2021 16:27:20 +0800", "msg_from": "\"=?UTF-8?B?5a2Z6K+X5rWpKOaAneaJjSk=?=\" <sunshihao.ssh@alibaba-inc.com>", "msg_from_op": true, "msg_subject": "\n =?UTF-8?B?YWRkIG9wZXJhdG9yIF49IHRvIG1lYW4gbm90IGVxdWFsIChsaWtlICE9IGFuZCA8Pik=?=" }, { "msg_contents": "On 8/10/21 10:27 AM, 孙诗浩(思才) wrote:\n> Before send patch review, I want to konw whether the postgres maintainer \n> will approve my changes.\n> \n> So, please give me some advice.\n\nWelcome!\n\nI do not think that is a feature which will get much interest from the \ndevelopers since it is unclear to me what the advantage of yet another \nalias for not equal would be. It just takes up yet another operator and \nmeans that there is yet another thing to remember for the users. \nPersonally I feel it is bad enough that we have two ways of writing it.\n\nWhat is he reason you want to add ^= is there any other databases which \nuses ^= for inequality?\n\nAndreas\n\n\n", "msg_date": "Tue, 10 Aug 2021 11:10:00 +0200", "msg_from": "Andreas Karlsson <andreas@proxel.se>", "msg_from_op": false, "msg_subject": "Re: add operator ^= to mean not equal (like != and <>)" }, { "msg_contents": "> On 10 Aug 2021, at 11:10, Andreas Karlsson <andreas@proxel.se> wrote:\n\n> What is he reason you want to add ^= is there any other databases which uses ^= for inequality?\n\nI assume it's because of Oracle compatibility which AFAIK is the only database\nsupporting ^=.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Tue, 10 Aug 2021 11:13:03 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: add operator ^= to mean not equal (like != and <>)" }, { "msg_contents": "On Tue, 10 Aug 2021 at 21:13, Daniel Gustafsson <daniel@yesql.se> wrote:\n>\n> > On 10 Aug 2021, at 11:10, Andreas Karlsson <andreas@proxel.se> wrote:\n>\n> > What is he reason you want to add ^= is there any other databases which uses ^= for inequality?\n>\n> I assume it's because of Oracle compatibility which AFAIK is the only database\n> supporting ^=.\n\nSeems likely.\n\nI'm strongly against inheriting warts from Oracle for apparently good\nreason. At the very least, anyone who's using ^= for some other\npurpose is very likely to be upset with us. Anyone else who really\nneeds this for compatibility reasons can just create a set of\noperators for themselves.\n\nDavid\n\n\n", "msg_date": "Tue, 10 Aug 2021 22:21:04 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: add operator ^= to mean not equal (like != and <>)" }, { "msg_contents": "> On 10 Aug 2021, at 12:21, David Rowley <dgrowleyml@gmail.com> wrote:\n> \n> On Tue, 10 Aug 2021 at 21:13, Daniel Gustafsson <daniel@yesql.se> wrote:\n>> \n>>> On 10 Aug 2021, at 11:10, Andreas Karlsson <andreas@proxel.se> wrote:\n>> \n>>> What is he reason you want to add ^= is there any other databases which uses ^= for inequality?\n>> \n>> I assume it's because of Oracle compatibility which AFAIK is the only database\n>> supporting ^=.\n> \n> Seems likely.\n> \n> I'm strongly against inheriting warts from Oracle for apparently good\n> reason. At the very least, anyone who's using ^= for some other\n> purpose is very likely to be upset with us. Anyone else who really\n> needs this for compatibility reasons can just create a set of\n> operators for themselves.\n\nAgreed, if it’s because of Oracle compatibility then this seems like something\nwhich has a better fit in orafce or a similar extension like that.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Tue, 10 Aug 2021 12:41:15 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: add operator ^= to mean not equal (like != and <>)" }, { "msg_contents": "Le mar. 10 août 2021 à 18:41, Daniel Gustafsson <daniel@yesql.se> a écrit :\n\n> > On 10 Aug 2021, at 12:21, David Rowley <dgrowleyml@gmail.com> wrote:\n> >\n> > I'm strongly against inheriting warts from Oracle for apparently good\n> > reason. At the very least, anyone who's using ^= for some other\n> > purpose is very likely to be upset with us. Anyone else who really\n> > needs this for compatibility reasons can just create a set of\n> > operators for themselves.\n>\n> Agreed, if it’s because of Oracle compatibility then this seems like\n> something\n> which has a better fit in orafce or a similar extension like that.\n>\n\n+1\n\n>\n\nLe mar. 10 août 2021 à 18:41, Daniel Gustafsson <daniel@yesql.se> a écrit :> On 10 Aug 2021, at 12:21, David Rowley <dgrowleyml@gmail.com> wrote:\n> \n> I'm strongly against inheriting warts from Oracle for apparently good\n> reason. At the very least, anyone who's using ^= for some other\n> purpose is very likely to be upset with us. Anyone else who really\n> needs this for compatibility reasons can just create a set of\n> operators for themselves.\n\nAgreed, if it’s because of Oracle compatibility then this seems like something\nwhich has a better fit in orafce or a similar extension like that.+1", "msg_date": "Tue, 10 Aug 2021 18:42:29 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: add operator ^= to mean not equal (like != and <>)" }, { "msg_contents": "On 10/08/21 8:27 pm, 孙诗浩(思才) wrote:\n> Hi everyone,\n> I am doding some jobs in postgres. I want to add \"^=\" like \"!=\" and \"<>\".\n\nOne problem is that '^' & '^=' is already used as the exclusive OR \noperator in programming languages such as: C, Java, JavaScript, and \nPython.  See:\n\n https://www.tutorialspoint.com/java/java_basic_operators.htm\n\n https://www.tutorialspoint.com/cprogramming/c_operators.htm\n\n https://docs.python.org/3/library/operator.html\n\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators\n\nPlease don't confuse people unnecessarily!\n\n\nCheers,\nGavin\n\n\n\n", "msg_date": "Wed, 11 Aug 2021 08:57:33 +1200", "msg_from": "Gavin Flower <GavinFlower@archidevsys.co.nz>", "msg_from_op": false, "msg_subject": "Re: add operator ^= to mean not equal (like != and <>)" }, { "msg_contents": "Hi,\n\nOn Tue, Aug 10, 2021 at 11:13:03AM +0200, Daniel Gustafsson wrote:\n> > On 10 Aug 2021, at 11:10, Andreas Karlsson <andreas@proxel.se> wrote:\n> > What is he reason you want to add ^= is there any other databases\n> > which uses ^= for inequality?\n> \n> I assume it's because of Oracle compatibility which AFAIK is the only\n> database supporting ^=.\n\nDB2 also supports (or supported) it, but it's deprecated:\n\nhttps://www.ibm.com/docs/en/db2/9.7?topic=predicates-basic-predicate\n\nWe encountered it at least in one customer setting, so we added it to\ndb2fce:\n\nhttps://github.com/credativ/db2fce/blob/master/db2fce.sql#L588\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, Geoff Richardson,\nPeter Lilley\n\nUnser Umgang mit personenbezogenen Daten unterliegt\nfolgenden Bestimmungen: https://www.credativ.de/datenschutz\n\n\n", "msg_date": "Tue, 10 Aug 2021 23:14:13 +0200", "msg_from": "Michael Banck <michael.banck@credativ.de>", "msg_from_op": false, "msg_subject": "Re: add operator ^= to mean not equal (like != and <>)" } ]
[ { "msg_contents": "Good day, hackers.\n\nOur client caught process stuck in tuplehash_grow. There was a query \nlike\n`select ts, count(*) from really_huge_partitioned_table group by ts`, \nand\nplanner decided to use hash aggregation.\n\nBacktrace shows that oldsize were 2147483648 at the moment. While \nnewsize\nwere optimized, looks like it were SH_MAX_SIZE.\n\n#0 0x0000000000603d0c in tuplehash_grow (tb=0x7f18c3c284c8, \nnewsize=<optimized out>) at ../../../src/include/lib/simplehash.h:457\n hash = 2147483654\n startelem = 1\n curelem = 1\n oldentry = 0x7f00c299e0d8\n oldsize = 2147483648\n olddata = 0x7f00c299e048\n newdata = 0x32e0448\n i = 6\n copyelem = 6\n\nEXPLAIN shows that there are 2604186278 rows in all partitions, but \nplanner\nthinks there will be only 200 unique rows after group by. Looks like we \nwas\nmistaken.\n\n Finalize GroupAggregate (cost=154211885.42..154211936.09 rows=200 \nwidth=16)\n Group Key: really_huge_partitioned_table.ts\n -> Gather Merge (cost=154211885.42..154211932.09 rows=400 \nwidth=16)\n Workers Planned: 2\n -> Sort (cost=154210885.39..154210885.89 rows=200 width=16)\n Sort Key: really_huge_partitioned_table.ts\n -> Partial HashAggregate \n(cost=154210875.75..154210877.75 rows=200 width=16)\n Group Key: really_huge_partitioned_table.ts\n -> Append (cost=0.43..141189944.36 \nrows=2604186278 width=8)\n -> Parallel Index Only Scan using \nreally_huge_partitioned_table_001_idx2 on \nreally_huge_partitioned_table_001 (cost=0.43..108117.92 rows=2236977 \nwidth=8)\n -> Parallel Index Only Scan using \nreally_huge_partitioned_table_002_idx2 on \nreally_huge_partitioned_table_002 (cost=0.43..114928.19 rows=2377989 \nwidth=8)\n .... and more than 400 partitions more\n\nAfter some investigation I found bug that is present in simplehash from \nits\nbeginning:\n\n- sizemask is set only in SH_COMPUTE_PARAMETERS . And it is set in this \nway:\n\n /* now set size */\n tb->size = size;\n\n if (tb->size == SH_MAX_SIZE)\n tb->sizemask = 0;\n else\n tb->sizemask = tb->size - 1;\n\n that means, when we are resizing to SH_MAX_SIZE, sizemask becomes \nzero.\n\n- then sizemask is used to SH_INITIAL_BUCKET and SH_NEXT to compute \ninitial and\n next position:\n\n SH_INITIAL_BUCKET(SH_TYPE * tb, uint32 hash)\n return hash & tb->sizemask;\n SH_NEXT(SH_TYPE * tb, uint32 curelem, uint32 startelem)\n curelem = (curelem + 1) & tb->sizemask;\n\n- and then SH_GROW stuck in element placing loop:\n\n startelem = SH_INITIAL_BUCKET(tb, hash);\n curelem = startelem;\n while (true)\n curelem = SH_NEXT(tb, curelem, startelem);\n\nThere is Assert(curelem != startelem) in SH_NEXT, but since no one test \nit\nwith 2 billion elements, it were not triggered. And Assert is not \ncompiled\nin production code.\n\nAttached patch fixes it with removing condition and type casting:\n\n /* now set size */\n tb->size = size;\n tb->sizemask = (uint32)(size - 1);\n\n\nOOOOOOPS\n\nWhile writting this letter, I looke at newdata in the frame of \ntuplehash_grow:\n\n newdata = 0x32e0448\n\nIt is bellow 4GB border. Allocator does not allocate many-gigabytes \nchunks\n(and we certainly need 96GB in this case) in sub 4GB address space. \nBecause\nmmap doesn't do this.\n\nI went to check SH_GROW and.... It is `SH_GROW(SH_TYPE *tb, uint32 \nnewsize)`\n:-(((\nTherefore when `tb->size == SH_MAX_SIZE/2` and we call `SH_GROW(tb, \ntb->size * 2)`,\nthen SH_GROW(tb, 0) is called due to truncation.\nAnd SH_COMPUTE_PARAMETERS is also accepts `uint32 newsize`.\n\nAhh... ok, patch is updated to fix this as well.\n\n\nregards.\n\n-----\n\nYura Sokolov\ny.sokolov@postgrespro.ru\nfunny.falcon@gmail.com", "msg_date": "Tue, 10 Aug 2021 11:52:59 +0300", "msg_from": "Yura Sokolov <y.sokolov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Bug in huge simplehash" }, { "msg_contents": "On Tue, 10 Aug 2021 at 20:53, Yura Sokolov <y.sokolov@postgrespro.ru> wrote:\n> EXPLAIN shows that there are 2604186278 rows in all partitions, but\n> planner\n> thinks there will be only 200 unique rows after group by. Looks like we\n> was\n> mistaken.\n\nThis looks unrelated. Looks like the planner used DEFAULT_NUM_DISTINCT.\n\n> /* now set size */\n> tb->size = size;\n>\n> if (tb->size == SH_MAX_SIZE)\n> tb->sizemask = 0;\n> else\n> tb->sizemask = tb->size - 1;\n\nOuch. That's not great.\n\n> /* now set size */\n> tb->size = size;\n> tb->sizemask = (uint32)(size - 1);\n\nThat fix seems fine.\n\n> I went to check SH_GROW and.... It is `SH_GROW(SH_TYPE *tb, uint32\n> newsize)`\n> :-(((\n> Therefore when `tb->size == SH_MAX_SIZE/2` and we call `SH_GROW(tb,\n> tb->size * 2)`,\n> then SH_GROW(tb, 0) is called due to truncation.\n> And SH_COMPUTE_PARAMETERS is also accepts `uint32 newsize`.\n\nYeah. Agreed. I don't see anything wrong with your fix for that.\n\nI'm surprised nobody has hit this before. I guess having that many\ngroups is not common.\n\nAnnoyingly this just missed the window for being fixed in the minor\nreleases going out soon. We'll need to wait a few days before\npatching.\n\nDavid\n\n\n", "msg_date": "Tue, 10 Aug 2021 21:34:28 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Bug in huge simplehash" }, { "msg_contents": "Em ter., 10 de ago. de 2021 às 05:53, Yura Sokolov <y.sokolov@postgrespro.ru>\nescreveu:\n\n> Good day, hackers.\n>\n> Our client caught process stuck in tuplehash_grow. There was a query\n> like\n> `select ts, count(*) from really_huge_partitioned_table group by ts`,\n> and\n> planner decided to use hash aggregation.\n>\n> Backtrace shows that oldsize were 2147483648 at the moment. While\n> newsize\n> were optimized, looks like it were SH_MAX_SIZE.\n>\n> #0 0x0000000000603d0c in tuplehash_grow (tb=0x7f18c3c284c8,\n> newsize=<optimized out>) at ../../../src/include/lib/simplehash.h:457\n> hash = 2147483654\n> startelem = 1\n> curelem = 1\n> oldentry = 0x7f00c299e0d8\n> oldsize = 2147483648\n> olddata = 0x7f00c299e048\n> newdata = 0x32e0448\n> i = 6\n> copyelem = 6\n>\n> EXPLAIN shows that there are 2604186278 rows in all partitions, but\n> planner\n> thinks there will be only 200 unique rows after group by. Looks like we\n> was\n> mistaken.\n>\n> Finalize GroupAggregate (cost=154211885.42..154211936.09 rows=200\n> width=16)\n> Group Key: really_huge_partitioned_table.ts\n> -> Gather Merge (cost=154211885.42..154211932.09 rows=400\n> width=16)\n> Workers Planned: 2\n> -> Sort (cost=154210885.39..154210885.89 rows=200 width=16)\n> Sort Key: really_huge_partitioned_table.ts\n> -> Partial HashAggregate\n> (cost=154210875.75..154210877.75 rows=200 width=16)\n> Group Key: really_huge_partitioned_table.ts\n> -> Append (cost=0.43..141189944.36\n> rows=2604186278 width=8)\n> -> Parallel Index Only Scan using\n> really_huge_partitioned_table_001_idx2 on\n> really_huge_partitioned_table_001 (cost=0.43..108117.92 rows=2236977\n> width=8)\n> -> Parallel Index Only Scan using\n> really_huge_partitioned_table_002_idx2 on\n> really_huge_partitioned_table_002 (cost=0.43..114928.19 rows=2377989\n> width=8)\n> .... and more than 400 partitions more\n>\n> After some investigation I found bug that is present in simplehash from\n> its\n> beginning:\n>\n> - sizemask is set only in SH_COMPUTE_PARAMETERS . And it is set in this\n> way:\n>\n> /* now set size */\n> tb->size = size;\n>\n> if (tb->size == SH_MAX_SIZE)\n> tb->sizemask = 0;\n> else\n> tb->sizemask = tb->size - 1;\n>\n> that means, when we are resizing to SH_MAX_SIZE, sizemask becomes\n> zero.\n>\n> - then sizemask is used to SH_INITIAL_BUCKET and SH_NEXT to compute\n> initial and\n> next position:\n>\n> SH_INITIAL_BUCKET(SH_TYPE * tb, uint32 hash)\n> return hash & tb->sizemask;\n> SH_NEXT(SH_TYPE * tb, uint32 curelem, uint32 startelem)\n> curelem = (curelem + 1) & tb->sizemask;\n>\n> - and then SH_GROW stuck in element placing loop:\n>\n> startelem = SH_INITIAL_BUCKET(tb, hash);\n> curelem = startelem;\n> while (true)\n> curelem = SH_NEXT(tb, curelem, startelem);\n>\n> There is Assert(curelem != startelem) in SH_NEXT, but since no one test\n> it\n> with 2 billion elements, it were not triggered. And Assert is not\n> compiled\n> in production code.\n>\n> Attached patch fixes it with removing condition and type casting:\n>\n> /* now set size */\n> tb->size = size;\n> tb->sizemask = (uint32)(size - 1);\n>\n>\n> OOOOOOPS\n>\n> While writting this letter, I looke at newdata in the frame of\n> tuplehash_grow:\n>\n> newdata = 0x32e0448\n>\n> It is bellow 4GB border. Allocator does not allocate many-gigabytes\n> chunks\n> (and we certainly need 96GB in this case) in sub 4GB address space.\n> Because\n> mmap doesn't do this.\n>\n> I went to check SH_GROW and.... It is `SH_GROW(SH_TYPE *tb, uint32\n> newsize)`\n> :-(((\n> Therefore when `tb->size == SH_MAX_SIZE/2` and we call `SH_GROW(tb,\n> tb->size * 2)`,\n> then SH_GROW(tb, 0) is called due to truncation.\n> And SH_COMPUTE_PARAMETERS is also accepts `uint32 newsize`.\n>\n> Ahh... ok, patch is updated to fix this as well.\n>\nIt seems that we need to fix the function prototype too.\n\n/* void <prefix>_grow(<prefix>_hash *tb) */\n-SH_SCOPE void SH_GROW(SH_TYPE * tb, uint32 newsize);\n+SH_SCOPE void SH_GROW(SH_TYPE * tb, uint64 newsize);\n\nregards,\nRanier Vilela\n\nEm ter., 10 de ago. de 2021 às 05:53, Yura Sokolov <y.sokolov@postgrespro.ru> escreveu:Good day, hackers.\n\nOur client caught process stuck in tuplehash_grow. There was a query \nlike\n`select ts, count(*) from really_huge_partitioned_table group by ts`, \nand\nplanner decided to use hash aggregation.\n\nBacktrace shows that oldsize were 2147483648 at the moment. While \nnewsize\nwere optimized, looks like it were SH_MAX_SIZE.\n\n#0  0x0000000000603d0c in tuplehash_grow (tb=0x7f18c3c284c8, \nnewsize=<optimized out>) at ../../../src/include/lib/simplehash.h:457\n         hash = 2147483654\n         startelem = 1\n         curelem = 1\n         oldentry = 0x7f00c299e0d8\n         oldsize = 2147483648\n         olddata = 0x7f00c299e048\n         newdata = 0x32e0448\n         i = 6\n         copyelem = 6\n\nEXPLAIN shows that there are 2604186278 rows in all partitions, but \nplanner\nthinks there will be only 200 unique rows after group by. Looks like we \nwas\nmistaken.\n\n  Finalize GroupAggregate  (cost=154211885.42..154211936.09 rows=200 \nwidth=16)\n     Group Key: really_huge_partitioned_table.ts\n     ->  Gather Merge  (cost=154211885.42..154211932.09 rows=400 \nwidth=16)\n           Workers Planned: 2\n           ->  Sort  (cost=154210885.39..154210885.89 rows=200 width=16)\n                 Sort Key: really_huge_partitioned_table.ts\n                 ->  Partial HashAggregate  \n(cost=154210875.75..154210877.75 rows=200 width=16)\n                       Group Key: really_huge_partitioned_table.ts\n                       ->  Append  (cost=0.43..141189944.36 \nrows=2604186278 width=8)\n                             ->  Parallel Index Only Scan using \nreally_huge_partitioned_table_001_idx2 on \nreally_huge_partitioned_table_001  (cost=0.43..108117.92 rows=2236977 \nwidth=8)\n                             ->  Parallel Index Only Scan using \nreally_huge_partitioned_table_002_idx2 on \nreally_huge_partitioned_table_002  (cost=0.43..114928.19 rows=2377989 \nwidth=8)\n                             .... and more than 400 partitions more\n\nAfter some investigation I found bug that is present in simplehash from \nits\nbeginning:\n\n- sizemask is set only in SH_COMPUTE_PARAMETERS . And it is set in this \nway:\n\n         /* now set size */\n         tb->size = size;\n\n         if (tb->size == SH_MAX_SIZE)\n                 tb->sizemask = 0;\n         else\n                 tb->sizemask = tb->size - 1;\n\n   that means, when we are resizing to SH_MAX_SIZE, sizemask becomes \nzero.\n\n- then sizemask is used to SH_INITIAL_BUCKET and SH_NEXT to compute \ninitial and\n   next position:\n\n   SH_INITIAL_BUCKET(SH_TYPE * tb, uint32 hash)\n     return hash & tb->sizemask;\n   SH_NEXT(SH_TYPE * tb, uint32 curelem, uint32 startelem)\n     curelem = (curelem + 1) & tb->sizemask;\n\n- and then SH_GROW stuck in element placing loop:\n\n   startelem = SH_INITIAL_BUCKET(tb, hash);\n   curelem = startelem;\n   while (true)\n     curelem = SH_NEXT(tb, curelem, startelem);\n\nThere is Assert(curelem != startelem) in SH_NEXT, but since no one test \nit\nwith 2 billion elements, it were not triggered. And Assert is not \ncompiled\nin production code.\n\nAttached patch fixes it with removing condition and type casting:\n\n         /* now set size */\n         tb->size = size;\n         tb->sizemask = (uint32)(size - 1);\n\n\nOOOOOOPS\n\nWhile writting this letter, I looke at newdata in the frame of \ntuplehash_grow:\n\n     newdata = 0x32e0448\n\nIt is bellow 4GB border. Allocator does not allocate many-gigabytes \nchunks\n(and we certainly need 96GB in this case) in sub 4GB address space. \nBecause\nmmap doesn't do this.\n\nI went to check SH_GROW and.... It is `SH_GROW(SH_TYPE *tb, uint32 \nnewsize)`\n:-(((\nTherefore when `tb->size == SH_MAX_SIZE/2` and we call `SH_GROW(tb, \ntb->size * 2)`,\nthen SH_GROW(tb, 0) is called due to truncation.\nAnd SH_COMPUTE_PARAMETERS is also accepts `uint32 newsize`.\n\nAhh... ok, patch is updated to fix this as well.It seems that we need to fix the function prototype too./* void <prefix>_grow(<prefix>_hash *tb) */\n-SH_SCOPE void SH_GROW(SH_TYPE * tb, uint32 newsize);\n\n+SH_SCOPE void SH_GROW(SH_TYPE * tb, uint64 newsize);regards,Ranier Vilela", "msg_date": "Tue, 10 Aug 2021 08:21:36 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Bug in huge simplehash" }, { "msg_contents": "Ranier Vilela писал 2021-08-10 14:21:\n> Em ter., 10 de ago. de 2021 às 05:53, Yura Sokolov\n> <y.sokolov@postgrespro.ru> escreveu:\n> \n>> \n>> I went to check SH_GROW and.... It is `SH_GROW(SH_TYPE *tb, uint32\n>> newsize)`\n>> :-(((\n>> Therefore when `tb->size == SH_MAX_SIZE/2` and we call `SH_GROW(tb,\n>> tb->size * 2)`,\n>> then SH_GROW(tb, 0) is called due to truncation.\n>> And SH_COMPUTE_PARAMETERS is also accepts `uint32 newsize`.\n>> \n>> Ahh... ok, patch is updated to fix this as well.\n> \n> It seems that we need to fix the function prototype too.\n> \n> /* void <prefix>_grow(<prefix>_hash *tb) */\n> -SH_SCOPE void SH_GROW(SH_TYPE * tb, uint32 newsize); +SH_SCOPE void\n> SH_GROW(SH_TYPE * tb, uint64 newsize);\n\nAhh... Thank you, Ranier.\nAttached v2.\n\nregards,\n\n-----\n\nYura Sokolov", "msg_date": "Tue, 10 Aug 2021 15:10:49 +0300", "msg_from": "Yura Sokolov <y.sokolov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Bug in huge simplehash" }, { "msg_contents": "On Wed, 11 Aug 2021 at 00:10, Yura Sokolov <y.sokolov@postgrespro.ru> wrote:\n> Attached v2.\n\nEyeballing this it looks fine, but I was a little nervous backpatching\nwithout testing it properly, so I ended up provisioning a machine with\n256GB and doing a round of testing.\n\nI just created the most simple table I could:\n\ncreate table a (a bigserial, b int);\nand inserted 2^31 rows.\n\ninsert into a (b) values(1);\ninsert into a (b) select b from a; -- repeated until I got 2^31 rows.\n\nset work_mem = '256GB';\nset max_parallel_workers_per_gather = 0;\n\nI could recreate the issue described with the following query:\n\nexplain (analyze , timing off) select a from a group by a;\n\nAfter watching perf top for a while it switched to:\n\n 98.90% postgres [.] tuplehash_grow\n 0.36% [kernel] [k] change_p4d_range\n 0.24% postgres [.] LookupTupleHashEntry\n 0.09% postgres [.] tts_minimal_store_tuple\n 0.07% [kernel] [k] vm_normal_page\n 0.02% [kernel] [k] __softirqentry_text_start\n 0.02% postgres [.] heap_fill_tuple\n 0.02% postgres [.] AllocSetAlloc\n\nAfter patching I got:\n\nexplain (analyze , timing off) select a from a group by a;\n QUERY PLAN\n---------------------------------------------------------------------------------------------------------\n HashAggregate (cost=35149810.71..53983243.28 rows=1883343257\nwidth=8) (actual rows=2147483648 loops=1)\n Group Key: a\n Batches: 1 Memory Usage: 201334801kB\n -> Seq Scan on a (cost=0.00..30441452.57 rows=1883343257 width=8)\n(actual rows=2147483648 loops=1)\n Planning Time: 0.105 ms\n Execution Time: 2173480.905 ms\n(6 rows)\nTime: 2173482.166 ms (36:13.482)\n\nAnd, since I only had 256GB of memory on this machine and couldn't\nreally do 2^32 groups, I dropped SH_FILLFACTOR to 0.4 and\nSH_MAX_FILLFACTOR to 0.48 and tried again to ensure I got the hash\ntable full message:\n\npostgres=# explain (analyze on , timing off) select a from a group by a;\nERROR: hash table size exceeded\nTime: 1148554.672 ms (19:08.555)\n\nAfter doing that, I felt a bit better about batch-patching it, so I did.\n\nThanks for the patch.\n\nDavid\n\n\n", "msg_date": "Fri, 13 Aug 2021 16:50:50 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Bug in huge simplehash" }, { "msg_contents": "Hi,\n\nOn 2021-08-10 11:52:59 +0300, Yura Sokolov wrote:\n> - sizemask is set only in SH_COMPUTE_PARAMETERS . And it is set in this way:\n> \n> /* now set size */\n> tb->size = size;\n> \n> if (tb->size == SH_MAX_SIZE)\n> tb->sizemask = 0;\n> else\n> tb->sizemask = tb->size - 1;\n> \n> that means, when we are resizing to SH_MAX_SIZE, sizemask becomes zero.\n\nI think that was intended to be ~0.\n\n\n> Ahh... ok, patch is updated to fix this as well.\n\nAny chance you'd write a test for simplehash with such huge amount of\nvalues? It'd require a small bit of trickery to be practical. On systems\nwith MAP_NORESERVE it should be feasible.\n\n\n> static inline void\n> -SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint32 newsize)\n> +SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint64 newsize)\n> {\n> \tuint64\t\tsize;\n> \n> @@ -322,11 +322,7 @@ SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint32 newsize)\n> \n> \t/* now set size */\n> \ttb->size = size;\n> -\n> -\tif (tb->size == SH_MAX_SIZE)\n> -\t\ttb->sizemask = 0;\n> -\telse\n> -\t\ttb->sizemask = tb->size - 1;\n> +\ttb->sizemask = (uint32)(size - 1);\n\nISTM using ~0 would be nicer here?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 13 Aug 2021 02:21:33 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Bug in huge simplehash" }, { "msg_contents": "Andres Freund писал 2021-08-13 12:21:\n> Hi,\n> \n> On 2021-08-10 11:52:59 +0300, Yura Sokolov wrote:\n>> - sizemask is set only in SH_COMPUTE_PARAMETERS . And it is set in \n>> this way:\n>> \n>> /* now set size */\n>> tb->size = size;\n>> \n>> if (tb->size == SH_MAX_SIZE)\n>> tb->sizemask = 0;\n>> else\n>> tb->sizemask = tb->size - 1;\n>> \n>> that means, when we are resizing to SH_MAX_SIZE, sizemask becomes \n>> zero.\n> \n> I think that was intended to be ~0.\n\nI believe so.\n\n>> Ahh... ok, patch is updated to fix this as well.\n> \n> Any chance you'd write a test for simplehash with such huge amount of\n> values? It'd require a small bit of trickery to be practical. On \n> systems\n> with MAP_NORESERVE it should be feasible.\n\nWhich way C structures should be tested in postgres?\ndynahash/simplhash - do they have any tests currently?\nI'll do if hint is given.\n\n>> static inline void\n>> -SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint32 newsize)\n>> +SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint64 newsize)\n>> {\n>> \tuint64\t\tsize;\n>> \n>> @@ -322,11 +322,7 @@ SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint32 \n>> newsize)\n>> \n>> \t/* now set size */\n>> \ttb->size = size;\n>> -\n>> -\tif (tb->size == SH_MAX_SIZE)\n>> -\t\ttb->sizemask = 0;\n>> -\telse\n>> -\t\ttb->sizemask = tb->size - 1;\n>> +\ttb->sizemask = (uint32)(size - 1);\n> \n> ISTM using ~0 would be nicer here?\n\nI don't think so.\nTo be rigid it should be `~(uint32)0`.\nBut I believe it doesn't differ from `tb->sizemask = (uint32)(size - 1)`\nthat is landed with patch, therefore why `if` is needed?\n\n> \n> Greetings,\n> \n> Andres Freund\n\n\n", "msg_date": "Fri, 13 Aug 2021 12:44:17 +0300", "msg_from": "Yura Sokolov <y.sokolov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Bug in huge simplehash" }, { "msg_contents": "Hi,\n\nOn 2021-08-13 12:44:17 +0300, Yura Sokolov wrote:\n> Andres Freund писал 2021-08-13 12:21:\n> > Any chance you'd write a test for simplehash with such huge amount of\n> > values? It'd require a small bit of trickery to be practical. On systems\n> > with MAP_NORESERVE it should be feasible.\n> \n> Which way C structures should be tested in postgres?\n> dynahash/simplhash - do they have any tests currently?\n> I'll do if hint is given.\n\nWe don't have a great way right now :(. I think the best is to have a\nSQL callable function that uses some API. See e.g. test_atomic_ops() et\nal in src/test/regress/regress.c\n\n\n> > > static inline void\n> > > -SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint32 newsize)\n> > > +SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint64 newsize)\n> > > {\n> > > \tuint64\t\tsize;\n> > > \n> > > @@ -322,11 +322,7 @@ SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint32\n> > > newsize)\n> > > \n> > > \t/* now set size */\n> > > \ttb->size = size;\n> > > -\n> > > -\tif (tb->size == SH_MAX_SIZE)\n> > > -\t\ttb->sizemask = 0;\n> > > -\telse\n> > > -\t\ttb->sizemask = tb->size - 1;\n> > > +\ttb->sizemask = (uint32)(size - 1);\n> > \n> > ISTM using ~0 would be nicer here?\n> \n> I don't think so.\n> To be rigid it should be `~(uint32)0`.\n> But I believe it doesn't differ from `tb->sizemask = (uint32)(size - 1)`\n> that is landed with patch, therefore why `if` is needed?\n\nPersonally I find it more obvious to understand the intended behaviour\nwith ~0 (i.e. all bits set) than with a width truncation.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 13 Aug 2021 03:15:43 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Bug in huge simplehash" }, { "msg_contents": "Em sex., 13 de ago. de 2021 às 07:15, Andres Freund <andres@anarazel.de>\nescreveu:\n\n> Hi,\n>\n> On 2021-08-13 12:44:17 +0300, Yura Sokolov wrote:\n> > Andres Freund писал 2021-08-13 12:21:\n> > > Any chance you'd write a test for simplehash with such huge amount of\n> > > values? It'd require a small bit of trickery to be practical. On\n> systems\n> > > with MAP_NORESERVE it should be feasible.\n> >\n> > Which way C structures should be tested in postgres?\n> > dynahash/simplhash - do they have any tests currently?\n> > I'll do if hint is given.\n>\n> We don't have a great way right now :(. I think the best is to have a\n> SQL callable function that uses some API. See e.g. test_atomic_ops() et\n> al in src/test/regress/regress.c\n>\n>\n> > > > static inline void\n> > > > -SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint32 newsize)\n> > > > +SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint64 newsize)\n> > > > {\n> > > > uint64 size;\n> > > >\n> > > > @@ -322,11 +322,7 @@ SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint32\n> > > > newsize)\n> > > >\n> > > > /* now set size */\n> > > > tb->size = size;\n> > > > -\n> > > > - if (tb->size == SH_MAX_SIZE)\n> > > > - tb->sizemask = 0;\n> > > > - else\n> > > > - tb->sizemask = tb->size - 1;\n> > > > + tb->sizemask = (uint32)(size - 1);\n> > >\n> > > ISTM using ~0 would be nicer here?\n> >\n> > I don't think so.\n> > To be rigid it should be `~(uint32)0`.\n> > But I believe it doesn't differ from `tb->sizemask = (uint32)(size - 1)`\n> > that is landed with patch, therefore why `if` is needed?\n>\n> Personally I find it more obvious to understand the intended behaviour\n> with ~0 (i.e. all bits set) than with a width truncation.\n>\nhttps://godbolt.org/z/57WcjKqMj\nThe generated code is identical.\n\nregards,\nRanier Vilela\n\nEm sex., 13 de ago. de 2021 às 07:15, Andres Freund <andres@anarazel.de> escreveu:Hi,\n\nOn 2021-08-13 12:44:17 +0300, Yura Sokolov wrote:\n> Andres Freund писал 2021-08-13 12:21:\n> > Any chance you'd write a test for simplehash with such huge amount of\n> > values? It'd require a small bit of trickery to be practical. On systems\n> > with MAP_NORESERVE it should be feasible.\n> \n> Which way C structures should be tested in postgres?\n> dynahash/simplhash - do they have any tests currently?\n> I'll do if hint is given.\n\nWe don't have a great way right now :(. I think the best is to have a\nSQL callable function that uses some API. See e.g. test_atomic_ops() et\nal in src/test/regress/regress.c\n\n\n> > >  static inline void\n> > > -SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint32 newsize)\n> > > +SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint64 newsize)\n> > >  {\n> > >   uint64          size;\n> > > \n> > > @@ -322,11 +322,7 @@ SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint32\n> > > newsize)\n> > > \n> > >   /* now set size */\n> > >   tb->size = size;\n> > > -\n> > > - if (tb->size == SH_MAX_SIZE)\n> > > -         tb->sizemask = 0;\n> > > - else\n> > > -         tb->sizemask = tb->size - 1;\n> > > + tb->sizemask = (uint32)(size - 1);\n> > \n> > ISTM using ~0 would be nicer here?\n> \n> I don't think so.\n> To be rigid it should be `~(uint32)0`.\n> But I believe it doesn't differ from `tb->sizemask = (uint32)(size - 1)`\n> that is landed with patch, therefore why `if` is needed?\n\nPersonally I find it more obvious to understand the intended behaviour\nwith ~0 (i.e. all bits set) than with a width truncation.https://godbolt.org/z/57WcjKqMjThe generated code is identical.regards,Ranier Vilela", "msg_date": "Fri, 13 Aug 2021 08:12:59 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Bug in huge simplehash" }, { "msg_contents": "Ranier Vilela писал 2021-08-13 14:12:\n> Em sex., 13 de ago. de 2021 às 07:15, Andres Freund\n> <andres@anarazel.de> escreveu:\n> \n>> Hi,\n>> \n>> On 2021-08-13 12:44:17 +0300, Yura Sokolov wrote:\n>>> Andres Freund писал 2021-08-13 12:21:\n>>>> Any chance you'd write a test for simplehash with such huge\n>> amount of\n>>>> values? It'd require a small bit of trickery to be practical. On\n>> systems\n>>>> with MAP_NORESERVE it should be feasible.\n>>> \n>>> Which way C structures should be tested in postgres?\n>>> dynahash/simplhash - do they have any tests currently?\n>>> I'll do if hint is given.\n>> \n>> We don't have a great way right now :(. I think the best is to have\n>> a\n>> SQL callable function that uses some API. See e.g. test_atomic_ops()\n>> et\n>> al in src/test/regress/regress.c\n>> \n>>>> > static inline void\n>>>> > -SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint32 newsize)\n>>>> > +SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint64 newsize)\n>>>> > {\n>>>> > uint64 size;\n>>>> >\n>>>> > @@ -322,11 +322,7 @@ SH_COMPUTE_PARAMETERS(SH_TYPE * tb,\n>> uint32\n>>>> > newsize)\n>>>> >\n>>>> > /* now set size */\n>>>> > tb->size = size;\n>>>> > -\n>>>> > - if (tb->size == SH_MAX_SIZE)\n>>>> > - tb->sizemask = 0;\n>>>> > - else\n>>>> > - tb->sizemask = tb->size - 1;\n>>>> > + tb->sizemask = (uint32)(size - 1);\n>>>> \n>>>> ISTM using ~0 would be nicer here?\n>>> \n>>> I don't think so.\n>>> To be rigid it should be `~(uint32)0`.\n>>> But I believe it doesn't differ from `tb->sizemask = (uint32)(size\n>> - 1)`\n>>> that is landed with patch, therefore why `if` is needed?\n>> \n>> Personally I find it more obvious to understand the intended\n>> behaviour\n>> with ~0 (i.e. all bits set) than with a width truncation.\n> \n> https://godbolt.org/z/57WcjKqMj\n> The generated code is identical.\n\nI believe, you mean https://godbolt.org/z/qWzE1ePTE\n\n> regards,\n> Ranier Vilela\n\n\n", "msg_date": "Fri, 13 Aug 2021 14:40:08 +0300", "msg_from": "Yura Sokolov <y.sokolov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Bug in huge simplehash" }, { "msg_contents": "\nOn 2021-08-13 14:40:08 +0300, Yura Sokolov wrote:\n> Ranier Vilela писал 2021-08-13 14:12:\n> > Em sex., 13 de ago. de 2021 às 07:15, Andres Freund\n> > <andres@anarazel.de> escreveu:\n> > > Personally I find it more obvious to understand the intended\n> > > behaviour\n> > > with ~0 (i.e. all bits set) than with a width truncation.\n> > \n> > https://godbolt.org/z/57WcjKqMj\n> > The generated code is identical.\n> \n> I believe, you mean https://godbolt.org/z/qWzE1ePTE\n\nI don't think the choice of instructions matters. This is called around\ncreation and resizing - the other costs are several orders of magnitude\nmore expensive than determining the mask.\n\n\n", "msg_date": "Fri, 13 Aug 2021 05:14:31 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Bug in huge simplehash" } ]
[ { "msg_contents": "While fixing up a patch I had dealing with temporary tables I noticed\na bit of a quirk with pg_temp schemas. Namely that we have no actual\nmeta data marking them as temporary aside from their names. And we\ndon't do anything to protect that -- superuser can happily issue ALTER\nSCHEMA RENAME to rename it to a name that doesn't match pg_temp*. The\nrest of the system then treats it as a perfectly normal schema that\njust happens to contain temporary tables....\n\npostgres=# create temporary table t(i integer);\nCREATE TABLE\n\npostgres=# \\d t\n Table \"pg_temp_4.t\"\n Column | Type | Collation | Nullable | Default\n--------+---------+-----------+----------+---------\n i | integer | | |\n\npostgres=# alter schema pg_temp_4 rename to fnord;\nALTER SCHEMA\n\npostgres=# \\d t\n Table \"fnord.t\"\n Column | Type | Collation | Nullable | Default\n--------+---------+-----------+----------+---------\n i | integer | | |\n\n\nWe could, I suppose, say this is just not a problem. Most, perhaps\nall, of the existing code doesn't seem bothered by this situation. But\nit seems a bit fragile. The worst side effect I've found is that\nautovacuum won't drop orphaned temp tables because it can't check if\nthe backend is still alive connected to them.\n\n\nA related point is that super-user is allowed to drop the temp schema.\nIf super-user does do this we still allow new temporary tables to be\ncreated in the now-nonexistent schema resulting in tables that don't\nprint correctly:\n\npostgres=# drop schema pg_temp_3 cascade;\nNOTICE: drop cascades to table t3\nDROP SCHEMA\n\npostgres=# create temporary table t4( i integer);\nCREATE TABLE\n\npostgres=# \\d t4\n Table \".t4\"\n Column | Type | Collation | Nullable | Default\n--------+---------+-----------+----------+---------\n i | integer | | |\n\nI suspect there are sites that will try to fprintf NULL using %s here\nwhich on glibc prints \"(null)\" but may crash elsewhere...\n\nAt the very least we should probably disallow creating temporary\ntables if the temporary schema has been dropped. That's just creating\nbroken references in the catalog tables. Alternately we could rig\nsomething so that dropping the schema unsets myTempNamespace.\n\nThe real fix seems to me adding a \"istemp\" and \"backendid\" columns to\npg_namespace and not depending on the actual name of the schema to\nstore this info in. But I guess the current scheme has worked fine for\nages so I dunno. Perhaps the global temp table work will have to\ninvest in this area.\n\n-- \ngreg\n\n\n", "msg_date": "Tue, 10 Aug 2021 11:13:49 -0400", "msg_from": "Greg Stark <stark@mit.edu>", "msg_from_op": true, "msg_subject": "Quirk of pg_temp schemas ..." }, { "msg_contents": "Greg Stark <stark@mit.edu> writes:\n> While fixing up a patch I had dealing with temporary tables I noticed\n> a bit of a quirk with pg_temp schemas. Namely that we have no actual\n> meta data marking them as temporary aside from their names. And we\n> don't do anything to protect that -- superuser can happily issue ALTER\n> SCHEMA RENAME to rename it to a name that doesn't match pg_temp*.\n\nThis seems to me to be not very different from the 1001 other ways that\na superuser can break a database. If *non* superusers could rename\nthose schemas then I'd agree there's a problem to be solved.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 10 Aug 2021 11:30:35 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Quirk of pg_temp schemas ..." }, { "msg_contents": "On Tue, Aug 10, 2021 at 11:30:35AM -0400, Tom Lane wrote:\n> Greg Stark <stark@mit.edu> writes:\n>> While fixing up a patch I had dealing with temporary tables I noticed\n>> a bit of a quirk with pg_temp schemas. Namely that we have no actual\n>> meta data marking them as temporary aside from their names. And we\n>> don't do anything to protect that -- superuser can happily issue ALTER\n>> SCHEMA RENAME to rename it to a name that doesn't match pg_temp*.\n\nThe fun does not stop here. Here is one: drop the existing temporary\nschema as superuser, keep the connection that dropped it opened, and\nplay with various temporary objects, even types or functions.\n\n> This seems to me to be not very different from the 1001 other ways that\n> a superuser can break a database. If *non* superusers could rename\n> those schemas then I'd agree there's a problem to be solved.\n\nIf non-superusers could do anything that change what's stored in\npg_namespace and make things inconsistent with the backend-specific\nstate stored in memory, we are in trouble.\n--\nMichael", "msg_date": "Wed, 11 Aug 2021 09:35:21 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Quirk of pg_temp schemas ..." } ]
[ { "msg_contents": "we can use regular expressions (<>|!=) to cover \"<>\" and \"!=\". There is no\nneed to have two definitions less_greater and not_equals, because it will confuse developer.\nSo, we can use only not_equals to cover this operator set.\n\nPlease review my patch.\n\nThanks.", "msg_date": "Wed, 11 Aug 2021 11:27:23 +0800", "msg_from": "\"=?UTF-8?B?5a2Z6K+X5rWpKOaAneaJjSk=?=\" <sunshihao.ssh@alibaba-inc.com>", "msg_from_op": true, "msg_subject": "\n =?UTF-8?B?dXNlLXJlZ3VsYXItZXhwcmVzc2lvbnMtdG8tc2ltcGxpZnktbGVzc19ncmVhdGVyLWFuZC1u?=\n =?UTF-8?B?b3RfZXF1YWxzLnBhdGNo?=" }, { "msg_contents": "\"=?UTF-8?B?5a2Z6K+X5rWpKOaAneaJjSk=?=\" <sunshihao.ssh@alibaba-inc.com> writes:\n> we can use regular expressions (<>|!=) to cover \"<>\" and \"!=\". There is no\n> need to have two definitions less_greater and not_equals, because it will confuse developer.\n> So, we can use only not_equals to cover this operator set.\n\nI do not find this an improvement. Yeah, it's a bit shorter, but it's\nless clear; not least because the comment explaining the <>-means-!=\nbehavior is no longer anywhere near the code that implements that\nbehavior. It would also get in the way if we ever had reason to treat <>\nand != as something other than exact equivalents.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 10 Aug 2021 23:36:15 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re:\n =?UTF-8?B?dXNlLXJlZ3VsYXItZXhwcmVzc2lvbnMtdG8tc2ltcGxpZnktbGVzc19ncmVhdGVyLWFuZC1u?=\n =?UTF-8?B?b3RfZXF1YWxzLnBhdGNo?=" }, { "msg_contents": "On Tue, Aug 10, 2021 at 8:36 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> \"=?UTF-8?B?5a2Z6K+X5rWpKOaAneaJjSk=?=\" <sunshihao.ssh@alibaba-inc.com>\n> writes:\n> > we can use regular expressions (<>|!=) to cover \"<>\" and \"!=\".\n> There is no\n> > need to have two definitions less_greater and not_equals, because it\n> will confuse developer.\n> > So, we can use only not_equals to cover this operator set.\n>\n> I do not find this an improvement.\n\n\nAgreed, though mostly on a separation of responsibilities principle.\nLabelling the distinctive tokens and then assigning them meaning are two\ndifferent things.\n\n Yeah, it's a bit shorter, but it's\n> less clear;\n\nnot least because the comment explaining the <>-means-!=\n> behavior is no longer anywhere near the code that implements that\n> behavior.\n\n\nThe patch should just remove the comment for not_equals as well: if both\ntokens are given the same name they would have to be treated identically.\nThe fact they have the same name is clearer in that the equivalency\nknowledge is immediate and impossible to miss (if one doesn't go and check\nhow \"less_greater\" and \"not_equal\" are interpreted.)\n\n It would also get in the way if we ever had reason to treat <>\n> and != as something other than exact equivalents.\n>\n>\nThis is unconvincing both on the odds of being able to treat them\ndifferently and the fact that the degree of effort to overcome this\nobstacle seems minimal - about the same amount as reverting this patch, not\naccounting for the coding of the new behavior.\n\nIn short, for me, is a principled separation of concerns worth the slight\nloss is clarity? I'll stick to my status quo choice, but not strongly.\nSome more context as to exactly what kind of confusion this setup is\ncausing could help tip the scale.\n\nDavid J.\n\nOn Tue, Aug 10, 2021 at 8:36 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\"=?UTF-8?B?5a2Z6K+X5rWpKOaAneaJjSk=?=\" <sunshihao.ssh@alibaba-inc.com> writes:\n>      we can use regular expressions (<>|!=) to cover \"<>\" and \"!=\". There is no\n> need to have two definitions less_greater and not_equals, because it will confuse developer.\n> So, we can use only not_equals to cover this operator set.\n\nI do not find this an improvement.Agreed, though mostly on a separation of responsibilities principle.  Labelling the distinctive tokens and then assigning them meaning are two different things.  Yeah, it's a bit shorter, but it's\nless clear;not least because the comment explaining the <>-means-!=\nbehavior is no longer anywhere near the code that implements that\nbehavior.The patch should just remove the comment for not_equals as well: if both tokens are given the same name they would have to be treated identically.  The fact they have the same name is clearer in that the equivalency knowledge is immediate and impossible to miss (if one doesn't go and check how \"less_greater\" and \"not_equal\" are interpreted.)  It would also get in the way if we ever had reason to treat <>\nand != as something other than exact equivalents.This is unconvincing both on the odds of being able to treat them differently and the fact that the degree of effort to overcome this obstacle seems minimal - about the same amount as reverting this patch, not accounting for the coding of the new behavior.In short, for me, is a principled separation of concerns worth the slight loss is clarity?  I'll stick to my status quo choice, but not strongly.  Some more context as to exactly what kind of confusion this setup is causing could help tip the scale.David J.", "msg_date": "Tue, 10 Aug 2021 21:29:49 -0700", "msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>", "msg_from_op": false, "msg_subject": "Re:\n use-regular-expressions-to-simplify-less_greater-and-not_equals.patch" }, { "msg_contents": "\nOn 8/10/21 11:27 PM, 孙诗浩(思才) wrote:\n>      we can use regular expressions (<>|!=) to cover \"<>\" and \"!=\".\n> There is no\n> need to have two definitions less_greater and not_equals, because it\n> will confuse developer.\n> So, we can use only not_equals to cover this operator set.\n>\n>\n\n\nI don't understand the problem being solved here. This looks like a\nchange with no discernable benefit. I don't agree that the current code\nis substantially more likely to confuse developers. And the lexer is not\nsomething that gets a lot of change.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Wed, 11 Aug 2021 06:10:14 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re:\n use-regular-expressions-to-simplify-less_greater-and-not_equals.patch" }, { "msg_contents": "Andrew Dunstan <andrew@dunslane.net> writes:\n> On 8/10/21 11:27 PM, 孙诗浩(思才) wrote:\n>>      we can use regular expressions (<>|!=) to cover \"<>\" and \"!=\".\n\n> I don't understand the problem being solved here. This looks like a\n> change with no discernable benefit. I don't agree that the current code\n> is substantially more likely to confuse developers. And the lexer is not\n> something that gets a lot of change.\n\nBy my count, the response to this has been two definite \"no\"s, one\nleaning-to-no, and nobody speaking in favor. Nor has the submitter\nprovided a stronger argument for it. I'm going to mark this\nrejected in the CF app.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 05 Sep 2021 16:11:14 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re:\n use-regular-expressions-to-simplify-less_greater-and-not_equals.patch" } ]
[ { "msg_contents": "Back in March 2016, e06a38965 added support for parallel aggregation.\nIIRC, because it was fairly late in the release cycle, I dropped\nparallel DISTINCT to reduce the scope a little. It's been on my list\nof things to fix since then. I just didn't get around to it until\ntoday.\n\nThe patch is just some plumbing work to connect all the correct paths\nup to make it work. It's all fairly trivial.\n\nI thought about refactoring things a bit more to get rid of the\nadditional calls to grouping_is_sortable() and grouping_is_hashable(),\nbut I just don't think it's worth making the code ugly for. We'll\nonly call them again if we're considering a parallel plan, in which\ncase it's most likely not a trivial query. Those functions are pretty\ncheap anyway.\n\nI understand that there's another patch in the September commitfest\nthat does some stuff with Parallel DISTINCT, but that goes about\nthings a completely different way by creating multiple queues to\ndistribute values by hash. I don't think there's any overlap here.\nWe'd likely want to still have the planner consider both methods if we\nget that patch sometime.\n\nDavid", "msg_date": "Wed, 11 Aug 2021 16:51:02 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Allow parallel DISTINCT" }, { "msg_contents": "On Wed, 11 Aug 2021 at 16:51, David Rowley <dgrowleyml@gmail.com> wrote:\n> The patch is just some plumbing work to connect all the correct paths\n> up to make it work. It's all fairly trivial.\n\nI looked at this patch again and realise that it could be done a bit\nbetter. For example, the previous version set the distinct_rel's FDW\nfields twice, once when making the serial paths and once when\nfinalizing the partial paths.\n\nI've now added two new functions; create_final_distinct_paths and\ncreate_partial_distinct_paths. The responsibility of\ncreate_distinct_paths has changed. Instead of it creating the\nnon-parallel DISTINCT paths, it calls the two new functions and also\ntakes charge of calling the create_upper_paths_hook for\nUPPERREL_DISTINCT plus the FDW GetForeignUpperPaths() call. I think\nthis is nicer as I'd previously added a new parameter to\ncreate_distinct_paths() so I could tell it not to call the hook as I\ndidn't want to call that twice on the same relation as it would no\ndoubt result in some plugin just creating the same paths again.\n\nI've also changed my mind about the previous choice I'd made not to\ncall GetForeignUpperPaths for the UPPERREL_PARTIAL_DISTINCT. I now\nthink that's ok.\n\nI think this is a fairly trivial patch that just does a bit of wiring\nup of paths. Unless anyone has anything to say about it in the next\nfew days, I'll be looking at it again with intensions to push it.\n\nDavid\n\n\n", "msg_date": "Tue, 17 Aug 2021 17:07:20 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow parallel DISTINCT" }, { "msg_contents": "On Mon, Aug 16, 2021 at 10:07 PM David Rowley <dgrowleyml@gmail.com> wrote:\n\n> On Wed, 11 Aug 2021 at 16:51, David Rowley <dgrowleyml@gmail.com> wrote:\n> > The patch is just some plumbing work to connect all the correct paths\n> > up to make it work. It's all fairly trivial.\n>\n> I looked at this patch again and realise that it could be done a bit\n> better. For example, the previous version set the distinct_rel's FDW\n> fields twice, once when making the serial paths and once when\n> finalizing the partial paths.\n>\n> I've now added two new functions; create_final_distinct_paths and\n> create_partial_distinct_paths. The responsibility of\n> create_distinct_paths has changed. Instead of it creating the\n> non-parallel DISTINCT paths, it calls the two new functions and also\n> takes charge of calling the create_upper_paths_hook for\n> UPPERREL_DISTINCT plus the FDW GetForeignUpperPaths() call. I think\n> this is nicer as I'd previously added a new parameter to\n> create_distinct_paths() so I could tell it not to call the hook as I\n> didn't want to call that twice on the same relation as it would no\n> doubt result in some plugin just creating the same paths again.\n>\n> I've also changed my mind about the previous choice I'd made not to\n> call GetForeignUpperPaths for the UPPERREL_PARTIAL_DISTINCT. I now\n> think that's ok.\n>\n> I think this is a fairly trivial patch that just does a bit of wiring\n> up of paths. Unless anyone has anything to say about it in the next\n> few days, I'll be looking at it again with intensions to push it.\n>\n> David\n>\n>\n> Hi, David:\nCan you attach updated patch so that we know more detail about the two new\nfunctions; create_final_distinct_paths and\ncreate_partial_distinct_paths ?\n\nThanks\n\nOn Mon, Aug 16, 2021 at 10:07 PM David Rowley <dgrowleyml@gmail.com> wrote:On Wed, 11 Aug 2021 at 16:51, David Rowley <dgrowleyml@gmail.com> wrote:\n> The patch is just some plumbing work to connect all the correct paths\n> up to make it work. It's all fairly trivial.\n\nI looked at this patch again and realise that it could be done a bit\nbetter. For example, the previous version set the distinct_rel's FDW\nfields twice, once when making the serial paths and once when\nfinalizing the partial paths.\n\nI've now added two new functions; create_final_distinct_paths and\ncreate_partial_distinct_paths.  The responsibility of\ncreate_distinct_paths has changed. Instead of it creating the\nnon-parallel DISTINCT paths, it calls the two new functions and also\ntakes charge of calling the create_upper_paths_hook for\nUPPERREL_DISTINCT plus the FDW GetForeignUpperPaths() call.   I think\nthis is nicer as I'd previously added a new parameter to\ncreate_distinct_paths() so I could tell it not to call the hook as I\ndidn't want to call that twice on the same relation as it would no\ndoubt result in some plugin just creating the same paths again.\n\nI've also changed my mind about the previous choice I'd made not to\ncall GetForeignUpperPaths for the UPPERREL_PARTIAL_DISTINCT.  I now\nthink that's ok.\n\nI think this is a fairly trivial patch that just does a bit of wiring\nup of paths.  Unless anyone has anything to say about it in the next\nfew days, I'll be looking at it again with intensions to push it.\n\nDavid\n\nHi, David:Can you attach updated patch so that we know more detail about the two new functions; create_final_distinct_paths andcreate_partial_distinct_paths ?Thanks", "msg_date": "Tue, 17 Aug 2021 01:13:23 -0700", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: Allow parallel DISTINCT" }, { "msg_contents": "On Tue, 17 Aug 2021 at 20:07, Zhihong Yu <zyu@yugabyte.com> wrote:\n> Can you attach updated patch so that we know more detail about the two new functions; create_final_distinct_paths and\n> create_partial_distinct_paths ?\n\nMust've fallen off in transit :)\n\nDavid", "msg_date": "Tue, 17 Aug 2021 22:58:57 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow parallel DISTINCT" }, { "msg_contents": "On Tue, Aug 17, 2021 at 3:59 AM David Rowley <dgrowleyml@gmail.com> wrote:\n\n> On Tue, 17 Aug 2021 at 20:07, Zhihong Yu <zyu@yugabyte.com> wrote:\n> > Can you attach updated patch so that we know more detail about the two\n> new functions; create_final_distinct_paths and\n> > create_partial_distinct_paths ?\n>\n> Must've fallen off in transit :)\n>\n> David\n>\nHi,\nSince create_partial_distinct_paths() calls create_final_distinct_paths(),\nI wonder if numDistinctRows can be passed to create_final_distinct_paths()\nso that the latter doesn't need to call estimate_num_groups().\n\nCheers\n\nOn Tue, Aug 17, 2021 at 3:59 AM David Rowley <dgrowleyml@gmail.com> wrote:On Tue, 17 Aug 2021 at 20:07, Zhihong Yu <zyu@yugabyte.com> wrote:\n> Can you attach updated patch so that we know more detail about the two new functions; create_final_distinct_paths and\n> create_partial_distinct_paths ?\n\nMust've fallen off in transit :)\n\nDavidHi,Since create_partial_distinct_paths() calls create_final_distinct_paths(), I wonder if numDistinctRows can be passed to create_final_distinct_paths() so that the latter doesn't need to call estimate_num_groups().Cheers", "msg_date": "Tue, 17 Aug 2021 07:47:40 -0700", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: Allow parallel DISTINCT" }, { "msg_contents": "On Wed, 18 Aug 2021 at 02:42, Zhihong Yu <zyu@yugabyte.com> wrote:\n> Since create_partial_distinct_paths() calls create_final_distinct_paths(), I wonder if numDistinctRows can be passed to create_final_distinct_paths() so that the latter doesn't need to call estimate_num_groups().\n\nThat can't be done. The two calls to estimate_num_groups() are passing\nin a different number of input rows. In\ncreate_partial_distinct_paths() the number of rows is the number of\nexpected input rows from a partial path. In\ncreate_final_distinct_paths() when called to complete the final\ndistinct step, that's the number of distinct values multiplied by the\nnumber of workers.\n\nIt might be more possible to do something like cache the value of\ndistinctExprs, but I just don't feel the need. If there are partial\npaths in the input_rel then it's most likely that planning time is not\ngoing to dominate much between planning and execution. Also, if we\nwere to calculate the value of distinctExprs in create_distinct_paths\nalways, then we might end up calculating it for nothing as\ncreate_final_distinct_paths() does not always need it. I don't feel\nthe need to clutter up the code by doing any lazy calculating of it\neither.\n\nDavid\n\n\n", "msg_date": "Wed, 18 Aug 2021 08:47:25 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow parallel DISTINCT" }, { "msg_contents": "On Tue, Aug 17, 2021 at 1:47 PM David Rowley <dgrowleyml@gmail.com> wrote:\n\n> On Wed, 18 Aug 2021 at 02:42, Zhihong Yu <zyu@yugabyte.com> wrote:\n> > Since create_partial_distinct_paths() calls\n> create_final_distinct_paths(), I wonder if numDistinctRows can be passed to\n> create_final_distinct_paths() so that the latter doesn't need to call\n> estimate_num_groups().\n>\n> That can't be done. The two calls to estimate_num_groups() are passing\n> in a different number of input rows. In\n> create_partial_distinct_paths() the number of rows is the number of\n> expected input rows from a partial path. In\n> create_final_distinct_paths() when called to complete the final\n> distinct step, that's the number of distinct values multiplied by the\n> number of workers.\n>\n> It might be more possible to do something like cache the value of\n> distinctExprs, but I just don't feel the need. If there are partial\n> paths in the input_rel then it's most likely that planning time is not\n> going to dominate much between planning and execution. Also, if we\n> were to calculate the value of distinctExprs in create_distinct_paths\n> always, then we might end up calculating it for nothing as\n> create_final_distinct_paths() does not always need it. I don't feel\n> the need to clutter up the code by doing any lazy calculating of it\n> either.\n>\n> David\n>\nHi,\nThanks for your explanation.\n\nThe patch is good from my point of view.\n\nOn Tue, Aug 17, 2021 at 1:47 PM David Rowley <dgrowleyml@gmail.com> wrote:On Wed, 18 Aug 2021 at 02:42, Zhihong Yu <zyu@yugabyte.com> wrote:\n> Since create_partial_distinct_paths() calls create_final_distinct_paths(), I wonder if numDistinctRows can be passed to create_final_distinct_paths() so that the latter doesn't need to call estimate_num_groups().\n\nThat can't be done. The two calls to estimate_num_groups() are passing\nin a different number of input rows.  In\ncreate_partial_distinct_paths() the number of rows is the number of\nexpected input rows from a partial path.  In\ncreate_final_distinct_paths() when called to complete the final\ndistinct step, that's the number of distinct values multiplied by the\nnumber of workers.\n\nIt might be more possible to do something like cache the value of\ndistinctExprs, but I just don't feel the need.  If there are partial\npaths in the input_rel then it's most likely that planning time is not\ngoing to dominate much between planning and execution. Also, if we\nwere to calculate the value of distinctExprs in create_distinct_paths\nalways, then we might end up calculating it for nothing as\ncreate_final_distinct_paths() does not always need it. I don't feel\nthe need to clutter up the code by doing any lazy calculating of it\neither.\n\nDavidHi,Thanks for your explanation.The patch is good from my point of view.", "msg_date": "Tue, 17 Aug 2021 13:56:23 -0700", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: Allow parallel DISTINCT" }, { "msg_contents": "On Wed, 18 Aug 2021 at 08:50, Zhihong Yu <zyu@yugabyte.com> wrote:\n> The patch is good from my point of view.\n\nThanks for the review. I looked over the patch again and the only\nthing I adjusted was the order of the RESETs in the regression tests.\n\nI left the \" if (distinct_rel->pathlist == NIL)\" ERROR case check so\nthat the ERROR is raised before we call the FDW function and hook\nfunction to add more paths. Part of me thinks it should probably go\nafterwards, but I didn't want to change the behaviour there. The\nother part of me thinks that if you can't do distinct by sorting or\nhashing then there's not much hope for the hook to add any paths\neither.\n\nI've pushed this to master now.\n\nDavid\n\n\n", "msg_date": "Sun, 22 Aug 2021 23:37:00 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow parallel DISTINCT" }, { "msg_contents": "David Rowley <dgrowleyml@gmail.com> writes:\n> I've pushed this to master now.\n\n... and the buildfarm is pushing back, eg\n\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=hoverfly&dt=2021-08-22%2011%3A31%3A45\n\ndiff -U3 /scratch/nm/farm/xlc64v16/HEAD/pgsql.build/src/test/regress/expected/select_distinct.out /scratch/nm/farm/xlc64v16/HEAD/pgsql.build/src/test/regress/results/select_distinct.out\n--- /scratch/nm/farm/xlc64v16/HEAD/pgsql.build/src/test/regress/expected/select_distinct.out\t2021-08-22 11:26:22.000000000 +0000\n+++ /scratch/nm/farm/xlc64v16/HEAD/pgsql.build/src/test/regress/results/select_distinct.out\t2021-08-22 11:38:43.000000000 +0000\n@@ -223,7 +223,7 @@\n -> Sort\n Sort Key: four\n -> Gather\n- Workers Planned: 2\n+ Workers Planned: 5\n -> HashAggregate\n Group Key: four\n -> Parallel Seq Scan on tenk1\n@@ -270,7 +270,7 @@\n -> Sort\n Sort Key: (distinct_func(1))\n -> Gather\n- Workers Planned: 2\n+ Workers Planned: 5\n -> Parallel Seq Scan on tenk1\n (6 rows)\n \n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 22 Aug 2021 09:58:03 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow parallel DISTINCT" }, { "msg_contents": "On Mon, 23 Aug 2021 at 01:58, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> David Rowley <dgrowleyml@gmail.com> writes:\n> > I've pushed this to master now.\n>\n> ... and the buildfarm is pushing back, eg\n\nThanks. I pushed a fix for that.\n\nDavid\n\n\n", "msg_date": "Mon, 23 Aug 2021 02:35:46 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow parallel DISTINCT" }, { "msg_contents": "David Rowley <dgrowleyml@gmail.com> writes:\n> Thanks. I pushed a fix for that.\n\nYeah, I saw your commit just after complaining. Sorry for the noise.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 22 Aug 2021 11:16:41 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow parallel DISTINCT" } ]
[ { "msg_contents": "Hi,\n\nAttached is a draft for the 2021-08-12 release announcement. Please\nreview for technical accuracy.\n\nPlease ensure you have your feedback in no later than midnight today\n(Aug 11) AoE[1].\n\nThanks!\n\nJonathan\n\n[1] https://en.wikipedia.org/wiki/Anywhere_on_Earth", "msg_date": "Wed, 11 Aug 2021 12:32:41 -0400", "msg_from": "\"Jonathan S. Katz\" <jkatz@postgresql.org>", "msg_from_op": true, "msg_subject": "2021-08-12 release announcement draft" }, { "msg_contents": "On Wed, Aug 11, 2021 at 9:32 AM Jonathan S. Katz <jkatz@postgresql.org> wrote:\n> Please ensure you have your feedback in no later than midnight today\n> (Aug 11) AoE[1].\n\nI think that the pg_upgrade item should say that we now avoid forcing\nan anti-wraparound VACUUM on upgrade. This was never necessary.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Wed, 11 Aug 2021 10:35:16 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: 2021-08-12 release announcement draft" }, { "msg_contents": "On 8/11/21 1:35 PM, Peter Geoghegan wrote:\n> On Wed, Aug 11, 2021 at 9:32 AM Jonathan S. Katz <jkatz@postgresql.org> wrote:\n>> Please ensure you have your feedback in no later than midnight today\n>> (Aug 11) AoE[1].\n> \n> I think that the pg_upgrade item should say that we now avoid forcing\n> an anti-wraparound VACUUM on upgrade. This was never necessary.\n\nHow about:\n\n* `pg_upgrade` now carries forward the old installation's `oldestXID`\nvalue, which can improve things from a performance standpoint by no\nlonger forcing an anti-wraparound `VACUUM`.\n\n?\n\nJonathan", "msg_date": "Wed, 11 Aug 2021 14:23:51 -0400", "msg_from": "\"Jonathan S. Katz\" <jkatz@postgresql.org>", "msg_from_op": true, "msg_subject": "Re: 2021-08-12 release announcement draft" }, { "msg_contents": "On Wed, Aug 11, 2021 at 11:23 AM Jonathan S. Katz <jkatz@postgresql.org> wrote:\n> How about:\n>\n> * `pg_upgrade` now carries forward the old installation's `oldestXID`\n> value, which can improve things from a performance standpoint by no\n> longer forcing an anti-wraparound `VACUUM`.\n\nI don't think that framing this as a performance thing really makes\nsense. It certainly helps performance to not do something that's\ntotally unnecessary, and only ever happened because of a bug in the\nimplementation. But to me the point is that we're not doing these\nweird wholly unnecessary antiwraparound VACUUMs on upgrade now.\nRunning pg_upgrade no longer affects when or how we VACUUM, which is\nexactly what you'd expect all along.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Wed, 11 Aug 2021 11:29:24 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: 2021-08-12 release announcement draft" }, { "msg_contents": "On 8/11/21 2:29 PM, Peter Geoghegan wrote:\n> On Wed, Aug 11, 2021 at 11:23 AM Jonathan S. Katz <jkatz@postgresql.org> wrote:\n>> How about:\n>>\n>> * `pg_upgrade` now carries forward the old installation's `oldestXID`\n>> value, which can improve things from a performance standpoint by no\n>> longer forcing an anti-wraparound `VACUUM`.\n> \n> I don't think that framing this as a performance thing really makes\n> sense.\n\nI had grabbed the performance bit from the release notes (though the\ncomment was \"[t]hat's not desirable from a performance standpoint.\").\n\n It certainly helps performance to not do something that's\n> totally unnecessary, and only ever happened because of a bug in the\n> implementation. But to me the point is that we're not doing these\n> weird wholly unnecessary antiwraparound VACUUMs on upgrade now.\n> Running pg_upgrade no longer affects when or how we VACUUM, which is\n> exactly what you'd expect all along.\n\nSo perhaps:\n\n\"* `pg_upgrade` now carries forward the old installation's `oldestXID`\nvalue and no longer forces an anti-wraparound `VACUUM`.\"\n\nor maybe even:\n\n\"* `pg_upgrade` no longer forces an anti-wraparound `VACUUM`.\"\n\nJonathan", "msg_date": "Wed, 11 Aug 2021 14:42:38 -0400", "msg_from": "\"Jonathan S. Katz\" <jkatz@postgresql.org>", "msg_from_op": true, "msg_subject": "Re: 2021-08-12 release announcement draft" }, { "msg_contents": "On Wed, Aug 11, 2021 at 11:42 AM Jonathan S. Katz <jkatz@postgresql.org> wrote:\n> So perhaps:\n>\n> \"* `pg_upgrade` now carries forward the old installation's `oldestXID`\n> value and no longer forces an anti-wraparound `VACUUM`.\"\n>\n> or maybe even:\n>\n> \"* `pg_upgrade` no longer forces an anti-wraparound `VACUUM`.\"\n\nI prefer the first one, fwiw.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Wed, 11 Aug 2021 11:45:12 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: 2021-08-12 release announcement draft" }, { "msg_contents": "On Wed, Aug 11, 2021 at 12:32:41PM -0400, Jonathan S. Katz wrote:\n\n> * walsenders now show their latest replication commands in `pg_stat_activity`,\n> instead of just showing the latest SQL command.\n\nsingular \"command\" in pg_stat_activity ?\n\n> * `pg_settings.pending_restart` now show as true when a pertinent entry in\n> `postgresql.conf` is removed.\n\n\"is now shown\"\n\n> All PostgreSQL update releases are cumulative. As with other minor releases,\n> users are not required to dump and reload their database or use `pg_upgrade` in\n> order to apply this update release; you may simply shutdown PostgreSQL and\n\nshut down\n\n-- \nJustin\n\n\n", "msg_date": "Wed, 11 Aug 2021 13:46:20 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: 2021-08-12 release announcement draft" }, { "msg_contents": "On 8/11/21 2:46 PM, Justin Pryzby wrote:\n> On Wed, Aug 11, 2021 at 12:32:41PM -0400, Jonathan S. Katz wrote:\n> \n>> * walsenders now show their latest replication commands in `pg_stat_activity`,\n>> instead of just showing the latest SQL command.\n> \n> singular \"command\" in pg_stat_activity ?\n\nAdjusted to be singular.\n\n> \n>> * `pg_settings.pending_restart` now show as true when a pertinent entry in\n>> `postgresql.conf` is removed.\n> \n> \"is now shown\"\n\nI went with the active voice: \"now shows\"\n\n>> All PostgreSQL update releases are cumulative. As with other minor releases,\n>> users are not required to dump and reload their database or use `pg_upgrade` in\n>> order to apply this update release; you may simply shutdown PostgreSQL and\n> \n> shut down\n\nAdjusted.\n\nThanks,\n\nJonathan", "msg_date": "Wed, 11 Aug 2021 15:01:18 -0400", "msg_from": "\"Jonathan S. Katz\" <jkatz@postgresql.org>", "msg_from_op": true, "msg_subject": "Re: 2021-08-12 release announcement draft" }, { "msg_contents": "Thanks for drafting this up.\n\nOn Thu, 12 Aug 2021 at 04:32, Jonathan S. Katz <jkatz@postgresql.org> wrote:\n> Please ensure you have your feedback in no later than midnight today\n> (Aug 11) AoE[1].\n\nIt might not be the exact technical feedback you had in mind, but I\nthink the following could be improved:\n\n+ This release marks the third beta release of PostgreSQL 14 and puts the\n+ community one step closer to general availability this fall.\n\nI think the above wording is pretty good if your audience was entirely\nbased in, or at least expected to be based in North America. The\npeople from the South of India might have been under the impression\nthat the release was shortly after the monsoon season ended. The\npeople from the Nothern parts of Australia likely think it's around\nwhen the wet season starts. The people from temperate parts of the\nSouthern hemisphere think it's in the Spring. The people in the UK\nthink it's in Autumn.\n\nI'd really like to see us move away from using seasons as an indicator\nof when something is occurring when the audience is based all over the\nworld.\n\nMaybe something like \"one step closer to general availability around\nthe start of the final quarter of 2021\" would have more meaning to the\nrest of the world?\n\nDavid\n\n\n", "msg_date": "Thu, 12 Aug 2021 11:25:10 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: 2021-08-12 release announcement draft" }, { "msg_contents": "On 12/08/21 11:25 am, David Rowley wrote:\n> Thanks for drafting this up.\n>\n> On Thu, 12 Aug 2021 at 04:32, Jonathan S. Katz <jkatz@postgresql.org> wrote:\n>> Please ensure you have your feedback in no later than midnight today\n>> (Aug 11) AoE[1].\n> It might not be the exact technical feedback you had in mind, but I\n> think the following could be improved:\n>\n> + This release marks the third beta release of PostgreSQL 14 and puts the\n> + community one step closer to general availability this fall.\n>\n> I think the above wording is pretty good if your audience was entirely\n> based in, or at least expected to be based in North America. The\n> people from the South of India might have been under the impression\n> that the release was shortly after the monsoon season ended. The\n> people from the Nothern parts of Australia likely think it's around\n> when the wet season starts. The people from temperate parts of the\n> Southern hemisphere think it's in the Spring. The people in the UK\n> think it's in Autumn.\n>\n> I'd really like to see us move away from using seasons as an indicator\n> of when something is occurring when the audience is based all over the\n> world.\n>\n> Maybe something like \"one step closer to general availability around\n> the start of the final quarter of 2021\" would have more meaning to the\n> rest of the world?\n>\n> David\n>\n>\nLiving in New Zealand, I'd definitely agreed with not using seasons as \nthey are hemispheric specific.\n\nDoes anybody, other than the Americans, use 'Fall'' for Autumn???\n\n\n\n\n", "msg_date": "Thu, 12 Aug 2021 11:49:55 +1200", "msg_from": "Gavin Flower <GavinFlower@archidevsys.co.nz>", "msg_from_op": false, "msg_subject": "Re: 2021-08-12 release announcement draft" }, { "msg_contents": "On Wed, 11 Aug 2021 at 19:50, Gavin Flower <GavinFlower@archidevsys.co.nz>\nwrote:\n\n\n> Living in New Zealand, I'd definitely agreed with not using seasons as\n> they are hemispheric specific.\n>\n> Does anybody, other than the Americans, use 'Fall'' for Autumn???\n>\n\nCanadian here. We often use “Fall”, and we’re not Americans even though we\nare North Americans. But for the same reasons as others, I agree with the\nidea of using months or quarters (depending on how vague one wants to be!).\n\nOn Wed, 11 Aug 2021 at 19:50, Gavin Flower <GavinFlower@archidevsys.co.nz> wrote: \nLiving in New Zealand, I'd definitely agreed with not using seasons as \nthey are hemispheric specific.\n\nDoes anybody, other than the Americans, use 'Fall'' for Autumn???Canadian here. We often use “Fall”, and we’re not Americans even though we are North Americans. But for the same reasons as others, I agree with the idea of using months or quarters (depending on how vague one wants to be!).", "msg_date": "Wed, 11 Aug 2021 20:05:46 -0400", "msg_from": "Isaac Morland <isaac.morland@gmail.com>", "msg_from_op": false, "msg_subject": "Re: 2021-08-12 release announcement draft" }, { "msg_contents": "On 8/11/21 7:25 PM, David Rowley wrote:\n> Thanks for drafting this up.\n> \n> On Thu, 12 Aug 2021 at 04:32, Jonathan S. Katz <jkatz@postgresql.org> wrote:\n>> Please ensure you have your feedback in no later than midnight today\n>> (Aug 11) AoE[1].\n> \n> It might not be the exact technical feedback you had in mind, but I\n> think the following could be improved:\n> \n> + This release marks the third beta release of PostgreSQL 14 and puts the\n> + community one step closer to general availability this fall.\n> \n> I think the above wording is pretty good if your audience was entirely\n> based in, or at least expected to be based in North America. \n\nThis is a fair point, and elsewhere on the website we reference major\nreleases occurring near the end of the third quarter.\n\nI've updated it to:\n\n\"This release marks the third beta release of PostgreSQL 14 and puts the\ncommunity one step closer to general availability around the end of the\nthird quarter.\"\n\nThanks,\n\nJonathan", "msg_date": "Wed, 11 Aug 2021 20:53:40 -0400", "msg_from": "\"Jonathan S. Katz\" <jkatz@postgresql.org>", "msg_from_op": true, "msg_subject": "Re: 2021-08-12 release announcement draft" }, { "msg_contents": "On 8/11/21 8:53 PM, Jonathan S. Katz wrote:\n> On 8/11/21 7:25 PM, David Rowley wrote:\n\n> I've updated it to:\n> \n> \"This release marks the third beta release of PostgreSQL 14 and puts the\n> community one step closer to general availability around the end of the\n> third quarter.\"\n\nAnd made another update:\n\n\"This release marks the third beta release of PostgreSQL 14 and puts the\ncommunity one step closer to general availability tentatively around the\nend of the third quarter.\"\n\nadding the qualifier \"tentatively.\"\n\nThanks,\n\nJonathan", "msg_date": "Wed, 11 Aug 2021 21:05:05 -0400", "msg_from": "\"Jonathan S. Katz\" <jkatz@postgresql.org>", "msg_from_op": true, "msg_subject": "Re: 2021-08-12 release announcement draft" } ]
[ { "msg_contents": "Currently, all platforms must indirect through a function pointer to call\npopcount on a word-sized input, even though we don't arrange for a fast\nimplementation on non-x86 to make it worthwhile.\n\n0001 moves some declarations around so that \"slow\" popcount functions are\ncalled directly on non-x86 platforms.\n\n0002 was an idea to simplify and unify the coding for the slow functions.\n\nAlso attached is a test module for building microbenchmarks.\n\nOn a Power8 machine using gcc 4.8, and running\ntime ./inst/bin/psql -c 'select drive_popcount(100000, 1024)'\n\nI get\n\nmaster: 647ms\n0001: 183ms\n0002: 228ms\n\nSo 0001 is a clear winner on that platform. 0002 is still good, but slower\nthan 0001 for some reason, and it turns out that on master, gcc does emit a\npopcnt instruction from the intrinsic:\n\n0000000000000000 <pg_popcount32_slow>:\n 0: f4 02 63 7c popcntw r3,r3\n 4: b4 07 63 7c extsw r3,r3\n 8: 20 00 80 4e blr\n ...\n\nThe gcc docs mention a flag for this, but I'm not sure why it seems not to\nneed it:\n\nhttps://gcc.gnu.org/onlinedocs/gcc/RS_002f6000-and-PowerPC-Options.html#RS_002f6000-and-PowerPC-Options\n\nMaybe that's because the machine I used was ppc64le, but I'm not sure a ppc\nbinary built like this is portable to other hardware. For that reason,\nmaybe 0002 is a good idea.\n\n-- \nJohn Naylor\nEDB: http://www.enterprisedb.com", "msg_date": "Wed, 11 Aug 2021 13:11:22 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": true, "msg_subject": "call popcount32/64 directly on non-x86 platforms" }, { "msg_contents": "On Thu, 12 Aug 2021 at 05:11, John Naylor <john.naylor@enterprisedb.com> wrote:\n> 0001 moves some declarations around so that \"slow\" popcount functions are called directly on non-x86 platforms.\n\nI was wondering if there was a reason that you didn't implement this\nby just changing pg_popcount32 and pg_popcount64 to be actual\nfunctions rather than function pointers when TRY_POPCNT_FAST is not\ndefined? These functions would then just return\npg_popcountNN_slow(word);\n\nThis would save from having to change all the current callers of the\nfunctions to use the macro instead. That might be nice for any\nextensions which are using these functions.\n\nDavid\n\n\n", "msg_date": "Thu, 12 Aug 2021 12:13:09 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: call popcount32/64 directly on non-x86 platforms" }, { "msg_contents": "On Wed, Aug 11, 2021 at 8:13 PM David Rowley <dgrowleyml@gmail.com> wrote:\n>\n> On Thu, 12 Aug 2021 at 05:11, John Naylor <john.naylor@enterprisedb.com>\nwrote:\n> > 0001 moves some declarations around so that \"slow\" popcount functions\nare called directly on non-x86 platforms.\n>\n> I was wondering if there was a reason that you didn't implement this\n> by just changing pg_popcount32 and pg_popcount64 to be actual\n> functions rather than function pointers when TRY_POPCNT_FAST is not\n> defined? These functions would then just return\n> pg_popcountNN_slow(word);\n>\n> This would save from having to change all the current callers of the\n> functions to use the macro instead. That might be nice for any\n> extensions which are using these functions.\n\nHmm, it wasn't obvious to me that would work, but I tried it and came up\nwith v2. Is this what you had in mind?\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com", "msg_date": "Wed, 11 Aug 2021 22:02:04 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: call popcount32/64 directly on non-x86 platforms" }, { "msg_contents": "On Thu, 12 Aug 2021 at 14:02, John Naylor <john.naylor@enterprisedb.com> wrote:\n>\n>\n> On Wed, Aug 11, 2021 at 8:13 PM David Rowley <dgrowleyml@gmail.com> wrote:\n> >\n> > On Thu, 12 Aug 2021 at 05:11, John Naylor <john.naylor@enterprisedb.com> wrote:\n> > > 0001 moves some declarations around so that \"slow\" popcount functions are called directly on non-x86 platforms.\n> >\n> > I was wondering if there was a reason that you didn't implement this\n> > by just changing pg_popcount32 and pg_popcount64 to be actual\n> > functions rather than function pointers when TRY_POPCNT_FAST is not\n> > defined? These functions would then just return\n> > pg_popcountNN_slow(word);\n> >\n> > This would save from having to change all the current callers of the\n> > functions to use the macro instead. That might be nice for any\n> > extensions which are using these functions.\n>\n> Hmm, it wasn't obvious to me that would work, but I tried it and came up with v2. Is this what you had in mind?\n\nCloser, but I don't see why there's any need to make the fast and slow\nfunctions external. It should be perfectly fine to keep them static.\n\nI didn't test the performance, but the attached works for me.\n\nGoing by https://godbolt.org/z/ocv1Kj5K4 f2 seems to inline f1\n\nDavid", "msg_date": "Thu, 12 Aug 2021 17:25:55 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: call popcount32/64 directly on non-x86 platforms" }, { "msg_contents": "So when on MSVC, you don't have to check CPUID for support?\n\n-- \nÁlvaro Herrera PostgreSQL Developer — 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)\n\n\n", "msg_date": "Thu, 12 Aug 2021 09:11:06 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: call popcount32/64 directly on non-x86 platforms" }, { "msg_contents": "On Fri, 13 Aug 2021 at 01:11, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> So when on MSVC, you don't have to check CPUID for support?\n\nThat still needs to be checked in MSVC and as far as I can see it is\nbeing properly checked.\n\nDavid\n\n\n", "msg_date": "Fri, 13 Aug 2021 01:28:32 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: call popcount32/64 directly on non-x86 platforms" }, { "msg_contents": "On Fri, 13 Aug 2021 at 01:28, David Rowley <dgrowleyml@gmail.com> wrote:\n>\n> On Fri, 13 Aug 2021 at 01:11, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> > So when on MSVC, you don't have to check CPUID for support?\n>\n> That still needs to be checked in MSVC and as far as I can see it is\n> being properly checked.\n\nSomething there that might cause confusion is we do a configure check\nto see if popcntq works and define HAVE_X86_64_POPCNTQ if it does.\nI'm still a bit confused at why we bother doing that. Surely it just\nmeans that if the build machine does not have popcntq that we'll\nalways use pg_popcount64_slow, regardless if the machine that's\nactually running the code has popcntq.\n\nMaybe you saw that there's no such equivalent test when we set\nHAVE_X86_64_POPCNTQ for MSVC on x86_64. The reason for that is that\nwe do the run-time test using cpuid.\n\nDavid\n\n\n", "msg_date": "Fri, 13 Aug 2021 01:33:06 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: call popcount32/64 directly on non-x86 platforms" }, { "msg_contents": "On Thu, Aug 12, 2021 at 9:33 AM David Rowley <dgrowleyml@gmail.com> wrote:\n\n> Something there that might cause confusion is we do a configure check\n> to see if popcntq works and define HAVE_X86_64_POPCNTQ if it does.\n> I'm still a bit confused at why we bother doing that. Surely it just\n> means that if the build machine does not have popcntq that we'll\n> always use pg_popcount64_slow, regardless if the machine that's\n> actually running the code has popcntq.\n\nYeah, it's a bit strange, a configure check makes more sense if we have a\nway to specify we can build with a direct call (like x86-64-v2), but we\ndon't right now. Maybe short-term we could always do the runtime check on\nx86-64.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Thu, Aug 12, 2021 at 9:33 AM David Rowley <dgrowleyml@gmail.com> wrote:> Something there that might cause confusion is we do a configure check> to see if popcntq works and define HAVE_X86_64_POPCNTQ if it does.> I'm still a bit confused at why we bother doing that. Surely it just> means that if the build machine does not have popcntq that we'll> always use pg_popcount64_slow, regardless if the machine that's> actually running the code has popcntq.Yeah, it's a bit strange, a configure check makes more sense if we have a way to specify we can build with a direct call (like x86-64-v2), but we don't right now. Maybe short-term we could always do the runtime check on x86-64.--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Thu, 12 Aug 2021 10:01:14 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: call popcount32/64 directly on non-x86 platforms" }, { "msg_contents": "On 2021-Aug-13, David Rowley wrote:\n\n> Maybe you saw that there's no such equivalent test when we set\n> HAVE_X86_64_POPCNTQ for MSVC on x86_64. The reason for that is that\n> we do the run-time test using cpuid.\n\nYeah, that and also I mistook the two independent \"ifdef\" blocks for one\nblock with an \"#else\". Re-reading the ifdef maze, it looks reasonable.\n\n-- \nÁlvaro Herrera 39°49'30\"S 73°17'W — https://www.EnterpriseDB.com/\n\n\n", "msg_date": "Thu, 12 Aug 2021 10:33:58 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: call popcount32/64 directly on non-x86 platforms" }, { "msg_contents": "On Thu, Aug 12, 2021 at 1:26 AM David Rowley <dgrowleyml@gmail.com> wrote:\n> Closer, but I don't see why there's any need to make the fast and slow\n> functions external. It should be perfectly fine to keep them static.\n>\n> I didn't test the performance, but the attached works for me.\n\nThanks for that! I still get a big improvement to on Power8 / gcc 4.8, but\nit's not quite as fast as earlier versions, which were around 200ms:\n\nmaster: 646ms\nv3: 312ms\n\nThis machine does seem to be pickier about code layout than any other I've\ntried running benchmarks on, but that's still a bit much. In any case, your\nversion is clearer and has the intended effect, so I plan to commit that,\nbarring other comments.\n\nI think I'll leave my v2-0002 aside for now, since it has wider\nimplications, and I have bigger things to work on.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Thu, Aug 12, 2021 at 1:26 AM David Rowley <dgrowleyml@gmail.com> wrote:> Closer, but I don't see why there's any need to make the fast and slow> functions external.  It should be perfectly fine to keep them static.>> I didn't test the performance, but the attached works for me.Thanks for that! I still get a big improvement to on Power8 / gcc 4.8, but it's not quite as fast as earlier versions, which were around 200ms:master: 646ms v3:     312msThis machine does seem to be pickier about code layout than any other I've tried running benchmarks on, but that's still a bit much. In any case, your version is clearer and has the intended effect, so I plan to commit that, barring other comments.I think I'll leave my v2-0002 aside for now, since it has wider implications, and I have bigger things to work on.--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Thu, 12 Aug 2021 13:54:25 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: call popcount32/64 directly on non-x86 platforms" }, { "msg_contents": "I wrote:\n> On Thu, Aug 12, 2021 at 1:26 AM David Rowley <dgrowleyml@gmail.com> wrote:\n> > Closer, but I don't see why there's any need to make the fast and slow\n> > functions external. It should be perfectly fine to keep them static.\n> >\n> > I didn't test the performance, but the attached works for me.\n>\n> Thanks for that! I still get a big improvement to on Power8 / gcc 4.8,\nbut it's not quite as fast as earlier versions, which were around 200ms:\n>\n> master: 646ms\n> v3: 312ms\n>\n> This machine does seem to be pickier about code layout than any other\nI've tried running benchmarks on, but that's still a bit much. In any case,\nyour version is clearer and has the intended effect, so I plan to commit\nthat, barring other comments.\n\nPushed, thanks for looking1\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nI wrote:> On Thu, Aug 12, 2021 at 1:26 AM David Rowley <dgrowleyml@gmail.com> wrote:> > Closer, but I don't see why there's any need to make the fast and slow> > functions external.  It should be perfectly fine to keep them static.> >> > I didn't test the performance, but the attached works for me.>> Thanks for that! I still get a big improvement to on Power8 / gcc 4.8, but it's not quite as fast as earlier versions, which were around 200ms:>> master: 646ms> v3:     312ms>> This machine does seem to be pickier about code layout than any other I've tried running benchmarks on, but that's still a bit much. In any case, your version is clearer and has the intended effect, so I plan to commit that, barring other comments.Pushed, thanks for looking1--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Mon, 16 Aug 2021 11:56:17 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: call popcount32/64 directly on non-x86 platforms" } ]
[ { "msg_contents": "While reading through the README of the hash index I noticed a grammar\nerror, the attached patch fixes the same.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Thu, 12 Aug 2021 14:09:59 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": true, "msg_subject": "Grammar fix in hash index README" }, { "msg_contents": "On Thu, Aug 12, 2021 at 4:40 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> While reading through the README of the hash index I noticed a grammar\n> error, the attached patch fixes the same.\n\nLGTM, pushed.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Thu, Aug 12, 2021 at 4:40 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:>> While reading through the README of the hash index I noticed a grammar> error, the attached patch fixes the same.LGTM, pushed.--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Thu, 12 Aug 2021 08:55:29 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Grammar fix in hash index README" } ]
[ { "msg_contents": "A recent thread gave me the idea that it would be convenient to have\nanother flag for `regexp_matches` to make it return a singular\ntwo-dimensional array of matches when performing a global match.\n\nWhy? Well, basically you avoid having to aggregate the rows afterwards\nusing by wrapping it in a subquery.\n\nIs there some interest in this?\n\nThe idea is to add a new flag `a` that would imply `g` internally when\nperforming the match, but then return an array, instead of a set. Or\nmore accurately it will return a set that will always have exactly one\narray. The array would be empty if no matches are found, or would\ncontain arrays of match results otherwise.\n\nI have not looked into implementing this yet, but I may have time in\n8-9 days or so.\n\nFor now, I'm just looking if there's support or opposition to the idea.\n\n\n", "msg_date": "Thu, 12 Aug 2021 18:23:41 +0300", "msg_from": "Jordan Gigov <coladict@gmail.com>", "msg_from_op": true, "msg_subject": "Expanding regexp_matches flags" }, { "msg_contents": "Jordan Gigov <coladict@gmail.com> writes:\n> A recent thread gave me the idea that it would be convenient to have\n> another flag for `regexp_matches` to make it return a singular\n> two-dimensional array of matches when performing a global match.\n\n> Why? Well, basically you avoid having to aggregate the rows afterwards\n> using by wrapping it in a subquery.\n\n> Is there some interest in this?\n\nI'm not really convinced that has any value. The first question you\nought to be answering is whether the recently-pushed regexp function\nadditions don't already serve whatever use-case you had in mind.\n\nIf we do do it, I think it ought to be a different function. \"flag\"\nvalues that utterly change the meaning of the output sound like a\npretty bad idea. Also, \"returns setof text[]\" is very different from\n\"returns text[]\". The primary reason we invented regexp_match() a few\nyears ago was to get away from the ugliness involved in trying to\npretend the former is the latter.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 12 Aug 2021 11:31:55 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Expanding regexp_matches flags" } ]
[ { "msg_contents": "I heard the moan about \"Why doesn't TIMESTAMP mean TIMESTAMP WITH TIME\nZONE\" again today, so here is something concrete to address that.\n\nAFAIK, SQL Standard requires the default to be WITHOUT TIME ZONE, but\nnobody seems to think that is useful. We even added a specially\noptimized ALTER TABLE command to make switching from WITHOUT to WITH\nTIME ZONE easy, so it is clearly an important thing to solve.\n\nSo add a parameter called\n default_timestamp_with_timezone = off (default) | on\n\nThoughts?\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/", "msg_date": "Thu, 12 Aug 2021 19:24:58 +0100", "msg_from": "Simon Riggs <simon.riggs@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "On Thu, Aug 12, 2021 at 07:24:58PM +0100, Simon Riggs wrote:\n> I heard the moan about \"Why doesn't TIMESTAMP mean TIMESTAMP WITH TIME\n> ZONE\" again today, so here is something concrete to address that.\n> \n> AFAIK, SQL Standard requires the default to be WITHOUT TIME ZONE, but\n> nobody seems to think that is useful. We even added a specially\n> optimized ALTER TABLE command to make switching from WITHOUT to WITH\n> TIME ZONE easy, so it is clearly an important thing to solve.\n> \n> So add a parameter called\n> default_timestamp_with_timezone = off (default) | on\n\nI thought we found that changing behavior via GUC usually ends badly.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Thu, 12 Aug 2021 14:32:49 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "Bruce Momjian <bruce@momjian.us> writes:\n> On Thu, Aug 12, 2021 at 07:24:58PM +0100, Simon Riggs wrote:\n>> I heard the moan about \"Why doesn't TIMESTAMP mean TIMESTAMP WITH TIME\n>> ZONE\" again today, so here is something concrete to address that.\n>> \n>> AFAIK, SQL Standard requires the default to be WITHOUT TIME ZONE, but\n>> nobody seems to think that is useful.\n\nStandards compliance is useful, no? If it isn't, there are about 1001\nother things nobody much likes about SQL.\n\n>> We even added a specially\n>> optimized ALTER TABLE command to make switching from WITHOUT to WITH\n>> TIME ZONE easy, so it is clearly an important thing to solve.\n>> \n>> So add a parameter called\n>> default_timestamp_with_timezone = off (default) | on\n\n> I thought we found that changing behavior via GUC usually ends badly.\n\nYeah. Changing from SQL-spec to not-SQL-spec behavior is going to be\none tough sell to begin with, even without the point that that's been\nour behavior for over two decades. But proposing to do it via a GUC\nis just not-even-worth-discussing territory. That would force every\nwannabe-portable program to cope with both behaviors; which would\nend up meaning that not only do you still have to take care to write\nWITH TIME ZONE when you want that, but *also* you'd have to be sure\nto write WITHOUT TIME ZONE when you want that. In short, the worst\nof both worlds.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 12 Aug 2021 15:07:47 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "On Thu, 12 Aug 2021 at 20:07, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Bruce Momjian <bruce@momjian.us> writes:\n> > On Thu, Aug 12, 2021 at 07:24:58PM +0100, Simon Riggs wrote:\n> >> I heard the moan about \"Why doesn't TIMESTAMP mean TIMESTAMP WITH TIME\n> >> ZONE\" again today, so here is something concrete to address that.\n> >>\n> >> AFAIK, SQL Standard requires the default to be WITHOUT TIME ZONE, but\n> >> nobody seems to think that is useful.\n>\n> Standards compliance is useful, no? If it isn't, there are about 1001\n> other things nobody much likes about SQL.\n>\n> >> We even added a specially\n> >> optimized ALTER TABLE command to make switching from WITHOUT to WITH\n> >> TIME ZONE easy, so it is clearly an important thing to solve.\n> >>\n> >> So add a parameter called\n> >> default_timestamp_with_timezone = off (default) | on\n>\n> > I thought we found that changing behavior via GUC usually ends badly.\n>\n> Yeah. Changing from SQL-spec to not-SQL-spec behavior is going to be\n> one tough sell to begin with, even without the point that that's been\n> our behavior for over two decades. But proposing to do it via a GUC\n> is just not-even-worth-discussing territory. That would force every\n> wannabe-portable program to cope with both behaviors; which would\n> end up meaning that not only do you still have to take care to write\n> WITH TIME ZONE when you want that, but *also* you'd have to be sure\n> to write WITHOUT TIME ZONE when you want that. In short, the worst\n> of both worlds.\n\nAll of which I agree with, but this wasn't a cute idea of mine, this\nwas what our users have requested because of the extreme annoyance\ncaused by the current behavior.\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/\n\n\n", "msg_date": "Fri, 13 Aug 2021 00:25:00 +0100", "msg_from": "Simon Riggs <simon.riggs@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "On Fri, Aug 13, 2021 at 12:25:00AM +0100, Simon Riggs wrote:\n> > > I thought we found that changing behavior via GUC usually ends badly.\n> >\n> > Yeah. Changing from SQL-spec to not-SQL-spec behavior is going to be\n> > one tough sell to begin with, even without the point that that's been\n> > our behavior for over two decades. But proposing to do it via a GUC\n> > is just not-even-worth-discussing territory. That would force every\n> > wannabe-portable program to cope with both behaviors; which would\n> > end up meaning that not only do you still have to take care to write\n> > WITH TIME ZONE when you want that, but *also* you'd have to be sure\n> > to write WITHOUT TIME ZONE when you want that. In short, the worst\n> > of both worlds.\n> \n> All of which I agree with, but this wasn't a cute idea of mine, this\n> was what our users have requested because of the extreme annoyance\n> caused by the current behavior.\n\nUnderstood, but the problem is that our users sometimes don't think\nthrough the ramifications of their suggestions.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Thu, 12 Aug 2021 19:55:51 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "An idea just occurred to me: a systematic way to provide this feature might\nbe to support aliases for objects. So I could declare an alternate name for\nan object, something like:\n\nCREATE ALIAS timestamp FOR TYPE timestamptz;\n\nWhich would mean that [current schema].timestamp would now be an alternate\nname for the built-in timestamptz object. There are other situations in\nwhich being able to define aliases would be handy, including schema\nmigrations and probably other compatibility scenarios.\n\nOf course I'm aware that this idea itself would need a lot of discussion\nand I'm not volunteering to implement it right now, but it might be a\nworkable approach if aliases ever become a feature.\n\nAn idea just occurred to me: a systematic way to provide this feature might be to support aliases for objects. So I could declare an alternate name for an object, something like:CREATE ALIAS timestamp FOR TYPE timestamptz;Which would mean that [current schema].timestamp would now be an alternate name for the built-in timestamptz object. There are other situations in which being able to define aliases would be handy, including schema migrations and probably other compatibility scenarios.Of course I'm aware that this idea itself would need a lot of discussion and I'm not volunteering to implement it right now, but it might be a workable approach if aliases ever become a feature.", "msg_date": "Thu, 12 Aug 2021 20:16:09 -0400", "msg_from": "Isaac Morland <isaac.morland@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "I think having a GUC to change to a different set of semantics is not workable.\n\nHowever that doesn't mean we can't do anything. We could have a GUC\nthat just disables allowing creating columns of type timestamp without\ntz. That could print an error with a hint suggesting you can change\nthe variable if you really want to allow them.\n\nI still would hesitate to make it the default but admins could set it\nto help their developers.\n\nYou could maybe imagine a set of parameters to disable various options\nthat can be seen as undesirable features that sites may not want their\ndevelopers accidentally introducing.\n\nThat said, even disabling a feature is a semantic change. Consider for\nexample an extension that did make use of some feature. To be portable\nand reliable it would have to start with a block of temporary GUC\nsettings to ensure it worked properly on user databases where various\nsettings may be in place. But that's a lot easier to manage than\nsubtle behavioural changes.\n\n\n", "msg_date": "Fri, 13 Aug 2021 01:14:56 -0400", "msg_from": "Greg Stark <stark@mit.edu>", "msg_from_op": false, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "On 13/08/21 5:14 pm, Greg Stark wrote:\n> I think having a GUC to change to a different set of semantics is not workable.\n>\n> However that doesn't mean we can't do anything. We could have a GUC\n> that just disables allowing creating columns of type timestamp without\n> tz. That could print an error with a hint suggesting you can change\n> the variable if you really want to allow them.\n>\n> I still would hesitate to make it the default but admins could set it\n> to help their developers.\n>\n[...]\n\nI always use the tz version, except when I forget.  Initially, I was \ntotally unaware of the need & usefulness of storing time in tz. So I \nwould use the GUC.\n\nSuspect that it is extremely rare when one would not want to use the TZ \noption, which suggests to me that using TZ should be the default.\n\n\nCheers,\nGavin\n\n\n\n", "msg_date": "Fri, 13 Aug 2021 19:33:25 +1200", "msg_from": "Gavin Flower <GavinFlower@archidevsys.co.nz>", "msg_from_op": false, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "On Fri, Aug 13, 2021 at 12:33 AM Gavin Flower <GavinFlower@archidevsys.co.nz>\nwrote:\n\n>\n> I always use the tz version, except when I forget.\n\n\nI find it nearly impossible for me to forget how this works. But that is\nprobably because I just pretend that the standard, multi-word, data types\ndon't even exist. It's not that \"timestamp\" defaults to \"WITHOUT TIME\nZONE\" but rather that there are only two types in existence: timestamp and\ntimestamptz. It's self-evident which one doesn't handle time zones.\n\n\n> Suspect that it is extremely rare when one would not want to use the TZ\n> option, which suggests to me that using TZ should be the default.\n>\n>\nI would agree, but at this point I'd leave it up to documentation and\neducational materials to teach/encourage, not runtime behaviors.\n\nDavid J.\n\nOn Fri, Aug 13, 2021 at 12:33 AM Gavin Flower <GavinFlower@archidevsys.co.nz> wrote:\nI always use the tz version, except when I forget.I find it nearly impossible for me to forget how this works.  But that is probably because I just pretend that the standard, multi-word, data types don't even exist.  It's not that \"timestamp\" defaults to \"WITHOUT TIME ZONE\" but rather that there are only two types in existence: timestamp and timestamptz.  It's self-evident which one doesn't handle time zones.\nSuspect that it is extremely rare when one would not want to use the TZ \noption, which suggests to me that using TZ should be the default.I would agree, but at this point I'd leave it up to documentation and educational materials to teach/encourage, not runtime behaviors.David J.", "msg_date": "Fri, 13 Aug 2021 07:09:15 -0700", "msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "On Fri, Aug 13, 2021 at 07:09:15AM -0700, David G. Johnston wrote:\n> On Fri, Aug 13, 2021 at 12:33 AM Gavin Flower <GavinFlower@archidevsys.co.nz>\n> wrote:\n> \n> \n> I always use the tz version, except when I forget.\n> \n> \n> I find it nearly impossible for me to forget how this works.  But that is\n> probably because I just pretend that the standard, multi-word, data types don't\n> even exist.  It's not that \"timestamp\" defaults to \"WITHOUT TIME ZONE\" but\n> rather that there are only two types in existence: timestamp and timestamptz. \n> It's self-evident which one doesn't handle time zones.\n> \n> \n> \n> Suspect that it is extremely rare when one would not want to use the TZ\n> option, which suggests to me that using TZ should be the default.\n> \n> \n> \n> I would agree, but at this point I'd leave it up to documentation and\n> educational materials to teach/encourage, not runtime behaviors.\n\nYes, only using 'timetamptz' does fix it.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Fri, 13 Aug 2021 11:47:49 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "\nOn 8/12/21 7:25 PM, Simon Riggs wrote:\n> I thought we found that changing behavior via GUC usually ends badly.\n>> Yeah. Changing from SQL-spec to not-SQL-spec behavior is going to be\n>> one tough sell to begin with, even without the point that that's been\n>> our behavior for over two decades. But proposing to do it via a GUC\n>> is just not-even-worth-discussing territory. That would force every\n>> wannabe-portable program to cope with both behaviors; which would\n>> end up meaning that not only do you still have to take care to write\n>> WITH TIME ZONE when you want that, but *also* you'd have to be sure\n>> to write WITHOUT TIME ZONE when you want that. In short, the worst\n>> of both worlds.\n> All of which I agree with, but this wasn't a cute idea of mine, this\n> was what our users have requested because of the extreme annoyance\n> caused by the current behavior.\n>\n\nWhat do other DBMSs do? This strikes me as primarily an education issue\n(I did a webinar on it not that long ago)\n\n\nIf you want to protect against people using tz-less timestamp, maybe an\nevent trigger would be a solution, although maybe that's using a\nsledgehammer to crack a nut.\n\n\ncheers\n\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Fri, 13 Aug 2021 12:23:19 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "On Fri, 13 Aug 2021 at 17:23, Andrew Dunstan <andrew@dunslane.net> wrote:\n\n> What do other DBMSs do?\n\nI think MySQL defaults to WITH TIME ZONE, not sure, but I would bet a\nfew others follow the standard.\n\n> This strikes me as primarily an education issue\n> (I did a webinar on it not that long ago)\n\nYes, agreed.\n\n> If you want to protect against people using tz-less timestamp, maybe an\n> event trigger would be a solution, although maybe that's using a\n> sledgehammer to crack a nut.\n\nIf you know about the issue, I guess you fix it in lots of different ways.\n\nThe issue is about those that don't know and my patch didn't help them\neither. The only hope is to eventually change the default, so probably\nthe best thing is to apply pressure via the SQL Std process.\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/\n\n\n", "msg_date": "Fri, 13 Aug 2021 17:28:25 +0100", "msg_from": "Simon Riggs <simon.riggs@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "On Fri, Aug 13, 2021 at 9:28 AM Simon Riggs <simon.riggs@enterprisedb.com>\nwrote:\n\n>\n> The only hope is to eventually change the default, so probably\n> the best thing is to apply pressure via the SQL Std process.\n>\n>\nThen there is no hope because this makes the situation worse.\n\nIf anything I'd suggest the SQL standard should probably just admit this\n\"default behavior of timestamp\" is a bad idea and deprecate its existence.\nIOW, the only two standard conforming syntaxes are the\nexplicit WITH/WITHOUT TIME ZONE ones. Any database implementation that\nimplements \"timestamp\" as a type alias is doing so in an implementation\ndependent way. Code that wants to be SQL standard conforming portable\nneeds to use the explicit types.\n\nDavid J.\n\nOn Fri, Aug 13, 2021 at 9:28 AM Simon Riggs <simon.riggs@enterprisedb.com> wrote:The only hope is to eventually change the default, so probably\nthe best thing is to apply pressure via the SQL Std process.Then there is no hope because this makes the situation worse.If anything I'd suggest the SQL standard should probably just admit this \"default behavior of timestamp\" is a bad idea and deprecate its existence.  IOW, the only two standard conforming syntaxes are the explicit WITH/WITHOUT TIME ZONE ones.  Any database implementation that implements \"timestamp\" as a type alias is doing so in an implementation dependent way.  Code that wants to be SQL standard conforming portable needs to use the explicit types.David J.", "msg_date": "Fri, 13 Aug 2021 09:53:23 -0700", "msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "\"David G. Johnston\" <david.g.johnston@gmail.com> writes:\n> On Fri, Aug 13, 2021 at 9:28 AM Simon Riggs <simon.riggs@enterprisedb.com>\n> wrote:\n>> The only hope is to eventually change the default, so probably\n>> the best thing is to apply pressure via the SQL Std process.\n\n> Then there is no hope because this makes the situation worse.\n\nAgreed; the points I made upthread are just as valid if the change\nis made in the standard. But I'd be astonished if the SQL committee\nwould consider such a change anyway.\n\nThe one thing I could potentially see us doing is more strongly\nencouraging the use of the names \"timestamp\" and \"timestamptz\",\nup to and including changing what format_type() et al. put out.\nYeah, \"timestamptz\" is not standard, but so what? At least it's\nnot actually *contrary* to the standard, as the original proposal\nhere is. (Also, while I hate to bring it up in this context,\nour timestamptz data type is not really compatible with the spec\nin the first place, so that a case could be made that this behavior\nis more honest/spec-compatible than what we do today.)\n\nIf you wanted to be even more in people's faces about it, you\ncould print the type names as \"timestamptz\" and \"timestamp\nwithout time zone\".\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 13 Aug 2021 13:07:28 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "On Friday, August 13, 2021, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> The one thing I could potentially see us doing is more strongly\n> encouraging the use of the names \"timestamp\" and \"timestamptz\",\n> up to and including changing what format_type() et al. put out.\n\n\n +1. Having the canonical form be timestamptz would make pretending the\n“with time zone” version doesn’t exist much easier.\n\nDavid J.\n\nOn Friday, August 13, 2021, Tom Lane <tgl@sss.pgh.pa.us> wrote:\nThe one thing I could potentially see us doing is more strongly\nencouraging the use of the names \"timestamp\" and \"timestamptz\",\nup to and including changing what format_type() et al. put out. +1.  Having the canonical form be timestamptz would make pretending the “with time zone” version doesn’t exist much easier.David J.", "msg_date": "Fri, 13 Aug 2021 11:47:45 -0700", "msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "On 13.08.21 19:07, Tom Lane wrote:\n> \"David G. Johnston\" <david.g.johnston@gmail.com> writes:\n>> On Fri, Aug 13, 2021 at 9:28 AM Simon Riggs <simon.riggs@enterprisedb.com>\n>> wrote:\n>>> The only hope is to eventually change the default, so probably\n>>> the best thing is to apply pressure via the SQL Std process.\n> \n>> Then there is no hope because this makes the situation worse.\n> \n> Agreed; the points I made upthread are just as valid if the change\n> is made in the standard. But I'd be astonished if the SQL committee\n> would consider such a change anyway.\n\nAFAIU, our timestamp with time zone type doesn't really do what the SQL \nstandard specifies anyway, as it doesn't actually record the time zone, \nbut it's more of a \"timestamp with time zone aware formatting\". For \nSQL, it might make sense to add a (third) time stamp type that behaves \nmore like that.\n\n\n", "msg_date": "Sat, 14 Aug 2021 10:03:01 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "On Sat, 14 Aug 2021 at 09:03, Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n>\n> On 13.08.21 19:07, Tom Lane wrote:\n> > \"David G. Johnston\" <david.g.johnston@gmail.com> writes:\n> >> On Fri, Aug 13, 2021 at 9:28 AM Simon Riggs <simon.riggs@enterprisedb.com>\n> >> wrote:\n> >>> The only hope is to eventually change the default, so probably\n> >>> the best thing is to apply pressure via the SQL Std process.\n> >\n> >> Then there is no hope because this makes the situation worse.\n> >\n> > Agreed; the points I made upthread are just as valid if the change\n> > is made in the standard. But I'd be astonished if the SQL committee\n> > would consider such a change anyway.\n>\n> AFAIU, our timestamp with time zone type doesn't really do what the SQL\n> standard specifies anyway, as it doesn't actually record the time zone,\n> but it's more of a \"timestamp with time zone aware formatting\". For\n> SQL, it might make sense to add a (third) time stamp type that behaves\n> more like that.\n\nHmm, a new datatype would make sense, but I would go in the direction\nof usability, since that's where this thread started.\n\nIt would also make sense to have a type called timestampUTC, where\n1. all inputs that specify a timezone are converted to UTC\n2. all inputs that do not specify a timezone are assumed to be UTC,\nignoring the setting of time zone\n3. output is not affected by the session time zone, so wherever you\nlook at it from, you see UTC values\n\nThis allows the UTC Everywhere design pattern and also ensures that\nall functions are immutable, so will not cause optimization problems.\n\nThis is useful because using TIMESTAMP WITHOUT TIME ZONE for UTC\nEverywhere only works if nobody ever sets their time zone, which every\nuser can do.\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/\n\n\n", "msg_date": "Sat, 14 Aug 2021 11:46:36 +0100", "msg_from": "Simon Riggs <simon.riggs@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" }, { "msg_contents": "On Sat, Aug 14, 2021 at 10:03:01AM +0200, Peter Eisentraut wrote:\n> On 13.08.21 19:07, Tom Lane wrote:\n> > \"David G. Johnston\" <david.g.johnston@gmail.com> writes:\n> > > On Fri, Aug 13, 2021 at 9:28 AM Simon Riggs <simon.riggs@enterprisedb.com>\n> > > wrote:\n> > > > The only hope is to eventually change the default, so probably\n> > > > the best thing is to apply pressure via the SQL Std process.\n> > \n> > > Then there is no hope because this makes the situation worse.\n> > \n> > Agreed; the points I made upthread are just as valid if the change\n> > is made in the standard. But I'd be astonished if the SQL\n> > committee would consider such a change anyway.\n> \n> AFAIU, our timestamp with time zone type doesn't really do what the\n> SQL standard specifies anyway, as it doesn't actually record the\n> time zone, but it's more of a \"timestamp with time zone aware\n> formatting\". For SQL, it might make sense to add a (third) time\n> stamp type that behaves more like that.\n\nThe way the standard defines time zones, namely as fix offsets from\nUTC, is just ludicrous and has been baseless in fact much longer than\nSQL has existed. If we're going to capture input time zones, we\nshould come up with a way to capture the time zone as it existed when\nthe write occurred, i.e. both its name and the UTC offset it\nrepresented at that time of the write.\n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate\n\n\n", "msg_date": "Mon, 16 Aug 2021 00:51:56 +0000", "msg_from": "David Fetter <david@fetter.org>", "msg_from_op": false, "msg_subject": "Re: Default to TIMESTAMP WITH TIME ZONE?" } ]
[ { "msg_contents": "Hi hackers,\n\nWhile working on [1], it appears that (on master) the issue reproduction \n(of toast rewrite not resetting the toast_hash) is triggering a failed \nassertion:\n\n#2  0x0000000000b29fab in ExceptionalCondition (conditionName=0xce6850\n\"(rb->size >= sz) && (txn->size >= sz)\", errorType=0xce5f84\n\"FailedAssertion\", fileName=0xce5fd0 \"reorderbuffer.c\", lineNumber=3141)\nat assert.c:69\n#3  0x00000000008ff1fb in ReorderBufferChangeMemoryUpdate (rb=0x11a7a40,\nchange=0x11c94b8, addition=false) at reorderbuffer.c:3141\n#4  0x00000000008fab27 in ReorderBufferReturnChange (rb=0x11a7a40,\nchange=0x11c94b8, upd_mem=true) at reorderbuffer.c:477\n#5  0x0000000000902ec1 in ReorderBufferToastReset (rb=0x11a7a40,\ntxn=0x11b1998) at reorderbuffer.c:4799\n#6  0x00000000008faaa2 in ReorderBufferReturnTXN (rb=0x11a7a40,\ntxn=0x11b1998) at reorderbuffer.c:448\n#7  0x00000000008fc95b in ReorderBufferCleanupTXN (rb=0x11a7a40,\ntxn=0x11b1998) at reorderbuffer.c:1540\n\nwhile on 12.5 for example, we would get (with the exact same repro):\n\nERROR:  could not open relation with OID 0\n\nThe failed assertion is happening in the PG_CATCH() section of \nReorderBufferProcessTXN().\n\nWe entered PG_CATCH() because elog(ERROR, \"could not open relation with \nOID %u\",...) has been triggered in ReorderBufferToastReplace().\n\nBut this elog(ERROR,) is being called after \nReorderBufferChangeMemoryUpdate() being triggered with \"addition\" set to \nfalse.\n\nAs a consequence of elog(ERROR,) then ReorderBufferChangeMemoryUpdate() \nwith \"addition\" set to true is not called at the end of \nReorderBufferToastReplace().\n\nThat leads to a subsequent call to ReorderBufferChangeMemoryUpdate() \n(being triggered by 4daa140a2f adding ReorderBufferToastReset() calls to \nReorderBufferReturnTXN()) triggering the failed assertion.\n\n\nPlease find attached a patch proposal to avoid the failed assertion (by \nensuring that ReorderBufferChangeMemoryUpdate() being triggered with \n\"addition\" set to false in ReorderBufferToastReplace() is done after the \nelog(ERROR,)).\n\nAdding Amit and Dilip as they are also aware of [1] and have worked on \n4daa140a2f.\n\nAlso adding this patch in the commitfest.\n\nThanks\n\nBertrand\n\n[1]: \nhttps://www.postgresql.org/message-id/b5146fb1-ad9e-7d6e-f980-98ed68744a7c@amazon.com", "msg_date": "Fri, 13 Aug 2021 11:45:37 +0200", "msg_from": "\"Drouvot, Bertrand\" <bdrouvot@amazon.com>", "msg_from_op": true, "msg_subject": "[BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "On Fri, Aug 13, 2021 at 3:15 PM Drouvot, Bertrand <bdrouvot@amazon.com> wrote:\n>\n>\n> Please find attached a patch proposal to avoid the failed assertion (by ensuring that ReorderBufferChangeMemoryUpdate() being triggered with \"addition\" set to false in ReorderBufferToastReplace() is done after the elog(ERROR,)).\n>\n\nThe error can occur at multiple places (like via palloc or various\nother places) between the first time we subtract the change_size and\nadd it back after the change is re-computed. I think the correct fix\nwould be that in the beginning we just compute the change_size by\nReorderBufferChangeSize and then after re-computing the change, we\njust subtract the old change_size and add the new change_size. What do\nyou think?\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Mon, 6 Sep 2021 16:04:40 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "On Mon, Sep 6, 2021 at 4:04 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> On Fri, Aug 13, 2021 at 3:15 PM Drouvot, Bertrand <bdrouvot@amazon.com>\n> wrote:\n> >\n> >\n> > Please find attached a patch proposal to avoid the failed assertion (by\n> ensuring that ReorderBufferChangeMemoryUpdate() being triggered with\n> \"addition\" set to false in ReorderBufferToastReplace() is done after the\n> elog(ERROR,)).\n> >\n>\n> The error can occur at multiple places (like via palloc or various\n> other places) between the first time we subtract the change_size and\n> add it back after the change is re-computed. I think the correct fix\n> would be that in the beginning we just compute the change_size by\n> ReorderBufferChangeSize and then after re-computing the change, we\n> just subtract the old change_size and add the new change_size. What do\n> you think?\n>\n\nYeah, that seems more logical to me.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Mon, Sep 6, 2021 at 4:04 PM Amit Kapila <amit.kapila16@gmail.com> wrote:On Fri, Aug 13, 2021 at 3:15 PM Drouvot, Bertrand <bdrouvot@amazon.com> wrote:\n>\n>\n> Please find attached a patch proposal to avoid the failed assertion (by ensuring that ReorderBufferChangeMemoryUpdate() being triggered with \"addition\" set to false in ReorderBufferToastReplace() is done after the elog(ERROR,)).\n>\n\nThe error can occur at multiple places (like via palloc or various\nother places) between the first time we subtract the change_size and\nadd it back after the change is re-computed. I think the correct fix\nwould be that in the beginning we just compute the change_size by\nReorderBufferChangeSize and then after re-computing the change, we\njust subtract the old change_size and add the new change_size. What do\nyou think?Yeah, that seems more logical to me.-- Regards,Dilip KumarEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Mon, 6 Sep 2021 17:24:59 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "Hi,\n\nOn 9/6/21 1:54 PM, Dilip Kumar wrote:\n>\n> *CAUTION*: This email originated from outside of the organization. Do \n> not click links or open attachments unless you can confirm the sender \n> and know the content is safe.\n>\n>\n> On Mon, Sep 6, 2021 at 4:04 PM Amit Kapila <amit.kapila16@gmail.com \n> <mailto:amit.kapila16@gmail.com>> wrote:\n>\n> On Fri, Aug 13, 2021 at 3:15 PM Drouvot, Bertrand\n> <bdrouvot@amazon.com <mailto:bdrouvot@amazon.com>> wrote:\n> >\n> >\n> > Please find attached a patch proposal to avoid the failed\n> assertion (by ensuring that ReorderBufferChangeMemoryUpdate()\n> being triggered with \"addition\" set to false in\n> ReorderBufferToastReplace() is done after the elog(ERROR,)).\n> >\n>\n> The error can occur at multiple places (like via palloc or various\n> other places) between the first time we subtract the change_size and\n> add it back after the change is re-computed. I think the correct fix\n> would be that in the beginning we just compute the change_size by\n> ReorderBufferChangeSize and then after re-computing the change, we\n> just subtract the old change_size and add the new change_size. What do\n> you think?\n>\n>\n> Yeah, that seems more logical to me.\n\nThanks for your feedback!\n\nThat seems indeed more logical, so I see 3 options to do so:\n\n  1) Add a new API say ReorderBufferChangeMemorySubstractSize() (with a \nSize as one parameter) and make use of it in ReorderBufferToastReplace()\n\n  2) Add a new \"Size\" parameter to ReorderBufferChangeMemoryUpdate(), so \nthat if this parameter is > 0 then it would be used instead of \"sz = \nReorderBufferChangeSize(change)\"\n\n  3) Do the substraction directly into ReorderBufferToastReplace() \nwithout any API\n\nI'm inclined to go for option 2), what do you think?\n\nThanks\n\nBertrand\n\n\n\n\n\n\n\nHi,\n\nOn 9/6/21 1:54 PM, Dilip Kumar wrote:\n\n\n\n\n\n\n\n\nCAUTION: This email originated\n from outside of the organization. Do not click links\n or open attachments unless you can confirm the\n sender and know the content is safe.\n\n\n\n\n\n\n\n\n\nOn Mon, Sep 6, 2021 at 4:04 PM Amit Kapila <amit.kapila16@gmail.com>\n wrote:\n\n\n\n\n On Fri, Aug 13, 2021 at 3:15 PM Drouvot, Bertrand <bdrouvot@amazon.com>\n wrote:\n >\n >\n > Please find attached a patch proposal to avoid the\n failed assertion (by ensuring that\n ReorderBufferChangeMemoryUpdate() being triggered with\n \"addition\" set to false in ReorderBufferToastReplace() is\n done after the elog(ERROR,)).\n >\n\n The error can occur at multiple places (like via palloc or\n various\n other places) between the first time we subtract the\n change_size and\n add it back after the change is re-computed. I think the\n correct fix\n would be that in the beginning we just compute the\n change_size by\n ReorderBufferChangeSize and then after re-computing the\n change, we\n just subtract the old change_size and add the new\n change_size. What do\n you think?\n\n\n\nYeah, that seems more logical to me.\n\n\n\n\nThanks for your feedback!\nThat seems indeed more logical, so I see 3 options to do so:\n 1) Add a new API say ReorderBufferChangeMemorySubstractSize()\n (with a Size as one parameter) and make use of it in\n ReorderBufferToastReplace()\n 2) Add a new \"Size\" parameter to\n ReorderBufferChangeMemoryUpdate(), so that if this parameter is\n > 0 then it would be used instead of \"sz =\n ReorderBufferChangeSize(change)\"\n 3) Do the substraction directly into ReorderBufferToastReplace()\n without any API \n\nI'm inclined to go for option 2), what do you think?\nThanks\nBertrand", "msg_date": "Mon, 6 Sep 2021 17:24:23 +0200", "msg_from": "\"Drouvot, Bertrand\" <bdrouvot@amazon.com>", "msg_from_op": true, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "On Mon, Sep 6, 2021 at 8:54 PM Drouvot, Bertrand <bdrouvot@amazon.com>\nwrote:\n\n> Thanks for your feedback!\n>\n> That seems indeed more logical, so I see 3 options to do so:\n>\n> 1) Add a new API say ReorderBufferChangeMemorySubstractSize() (with a\n> Size as one parameter) and make use of it in ReorderBufferToastReplace()\n>\n> 2) Add a new \"Size\" parameter to ReorderBufferChangeMemoryUpdate(), so\n> that if this parameter is > 0 then it would be used instead of \"sz =\n> ReorderBufferChangeSize(change)\"\n>\n> 3) Do the substraction directly into ReorderBufferToastReplace() without\n> any API\n>\n> I'm inclined to go for option 2), what do you think?\n>\nYet another option could be to create a new API say\nReorderBufferReplaceChangeMemoryUpdate(), which takes, 2 parameters,\noldchange, and newchange as inputs, it will compute the difference and\nadd/subtract that size. Logically, that is what we are actually trying to\ndo right? i.e. replacing old change with the new change.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Mon, Sep 6, 2021 at 8:54 PM Drouvot, Bertrand <bdrouvot@amazon.com> wrote:\n\n\n\n\nThanks for your feedback!\nThat seems indeed more logical, so I see 3 options to do so:\n 1) Add a new API say ReorderBufferChangeMemorySubstractSize()\n (with a Size as one parameter) and make use of it in\n ReorderBufferToastReplace()\n 2) Add a new \"Size\" parameter to\n ReorderBufferChangeMemoryUpdate(), so that if this parameter is\n > 0 then it would be used instead of \"sz =\n ReorderBufferChangeSize(change)\"\n 3) Do the substraction directly into ReorderBufferToastReplace()\n without any API \n\nI'm inclined to go for option 2), what do you think?Yet another option could be to create a new API say ReorderBufferReplaceChangeMemoryUpdate(), which takes, 2 parameters, oldchange, and newchange as inputs, it will compute the difference and add/subtract that size.  Logically, that is what we are actually trying to do right? i.e. replacing old change with the new change.-- Regards,Dilip KumarEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Mon, 6 Sep 2021 21:13:50 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "On Mon, Sep 6, 2021 at 9:14 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Mon, Sep 6, 2021 at 8:54 PM Drouvot, Bertrand <bdrouvot@amazon.com> wrote:\n>>\n>> Thanks for your feedback!\n>>\n>> That seems indeed more logical, so I see 3 options to do so:\n>>\n>> 1) Add a new API say ReorderBufferChangeMemorySubstractSize() (with a Size as one parameter) and make use of it in ReorderBufferToastReplace()\n>>\n>> 2) Add a new \"Size\" parameter to ReorderBufferChangeMemoryUpdate(), so that if this parameter is > 0 then it would be used instead of \"sz = ReorderBufferChangeSize(change)\"\n>>\n>> 3) Do the substraction directly into ReorderBufferToastReplace() without any API\n>>\n>> I'm inclined to go for option 2), what do you think?\n>\n\nIsn't it better if we use option 2) at all places as then we won't\nneed any special check inside ReorderBufferChangeMemoryUpdate()?\n\n> Yet another option could be to create a new API say ReorderBufferReplaceChangeMemoryUpdate(), which takes, 2 parameters, oldchange, and newchange as inputs, it will compute the difference and add/subtract that size. Logically, that is what we are actually trying to do right? i.e. replacing old change with the new change.\n>\n\nNote that in ReorderBufferToastReplace(), the new tuple is replaced in\nchange so by the time we want to do this computation oldchange won't\nbe preserved.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 7 Sep 2021 08:38:47 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "On Tue, Sep 7, 2021 at 8:38 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> On Mon, Sep 6, 2021 at 9:14 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n> >\n> > On Mon, Sep 6, 2021 at 8:54 PM Drouvot, Bertrand <bdrouvot@amazon.com>\n> wrote:\n> >>\n> >> Thanks for your feedback!\n> >>\n> >> That seems indeed more logical, so I see 3 options to do so:\n> >>\n> >> 1) Add a new API say ReorderBufferChangeMemorySubstractSize() (with a\n> Size as one parameter) and make use of it in ReorderBufferToastReplace()\n> >>\n> >> 2) Add a new \"Size\" parameter to ReorderBufferChangeMemoryUpdate(), so\n> that if this parameter is > 0 then it would be used instead of \"sz =\n> ReorderBufferChangeSize(change)\"\n> >>\n> >> 3) Do the substraction directly into ReorderBufferToastReplace()\n> without any API\n> >>\n> >> I'm inclined to go for option 2), what do you think?\n> >\n>\n> Isn't it better if we use option 2) at all places as then we won't\n> need any special check inside ReorderBufferChangeMemoryUpdate()?\n>\n\nIf we want to do this then be careful about\nREORDER_BUFFER_CHANGE_INTERNAL_TUPLECID change.\nBasically, ReorderBufferChangeMemoryUpdate() ignores this type of change\nwhereas ReorderBufferChangeSize(), consider at\nleast sizeof(ReorderBufferChange) bytes to this change. So if we compute\nthe size using ReorderBufferChangeSize() outside of\nReorderBufferChangeMemoryUpdate(), then total size will be different from\nwhat we have now. Logically, we should be ignoring/asserting\nREORDER_BUFFER_CHANGE_INTERNAL_TUPLECID in ReorderBufferChangeSize(),\nbecause ReorderBufferChangeMemoryUpdate() is the only caller for this\nfunction.\n\n\n> > Yet another option could be to create a new API say\n> ReorderBufferReplaceChangeMemoryUpdate(), which takes, 2 parameters,\n> oldchange, and newchange as inputs, it will compute the difference and\n> add/subtract that size. Logically, that is what we are actually trying to\n> do right? i.e. replacing old change with the new change.\n> >\n>\n> Note that in ReorderBufferToastReplace(), the new tuple is replaced in\n> change so by the time we want to do this computation oldchange won't\n> be preserved.\n>\n\nRight\n\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Tue, Sep 7, 2021 at 8:38 AM Amit Kapila <amit.kapila16@gmail.com> wrote:On Mon, Sep 6, 2021 at 9:14 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Mon, Sep 6, 2021 at 8:54 PM Drouvot, Bertrand <bdrouvot@amazon.com> wrote:\n>>\n>> Thanks for your feedback!\n>>\n>> That seems indeed more logical, so I see 3 options to do so:\n>>\n>>  1) Add a new API say ReorderBufferChangeMemorySubstractSize() (with a Size as one parameter) and make use of it in ReorderBufferToastReplace()\n>>\n>>  2) Add a new \"Size\" parameter to ReorderBufferChangeMemoryUpdate(), so that if this parameter is > 0 then it would be used instead of \"sz = ReorderBufferChangeSize(change)\"\n>>\n>>  3) Do the substraction directly into ReorderBufferToastReplace() without any API\n>>\n>> I'm inclined to go for option 2), what do you think?\n>\n\nIsn't it better if we use option 2) at all places as then we won't\nneed any special check inside ReorderBufferChangeMemoryUpdate()?If we want to do this then be careful about REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID change.  Basically, ReorderBufferChangeMemoryUpdate() ignores this type of change whereas ReorderBufferChangeSize(), consider at least sizeof(ReorderBufferChange) bytes to this change.  So if we compute the size using ReorderBufferChangeSize() outside of ReorderBufferChangeMemoryUpdate(), then total size will be different from what we have now.   Logically, we should be ignoring/asserting REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID in ReorderBufferChangeSize(), because ReorderBufferChangeMemoryUpdate() is the only caller for this function. \n> Yet another option could be to create a new API say ReorderBufferReplaceChangeMemoryUpdate(), which takes, 2 parameters, oldchange, and newchange as inputs, it will compute the difference and add/subtract that size.  Logically, that is what we are actually trying to do right? i.e. replacing old change with the new change.\n>\n\nNote that in ReorderBufferToastReplace(), the new tuple is replaced in\nchange so by the time we want to do this computation oldchange won't\nbe preserved.Right -- Regards,Dilip KumarEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Tue, 7 Sep 2021 11:07:48 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "On Tue, Sep 7, 2021 at 11:08 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>\n> On Tue, Sep 7, 2021 at 8:38 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>\n>> On Mon, Sep 6, 2021 at 9:14 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>> >\n>> > On Mon, Sep 6, 2021 at 8:54 PM Drouvot, Bertrand <bdrouvot@amazon.com> wrote:\n>> >>\n>> >> Thanks for your feedback!\n>> >>\n>> >> That seems indeed more logical, so I see 3 options to do so:\n>> >>\n>> >> 1) Add a new API say ReorderBufferChangeMemorySubstractSize() (with a Size as one parameter) and make use of it in ReorderBufferToastReplace()\n>> >>\n>> >> 2) Add a new \"Size\" parameter to ReorderBufferChangeMemoryUpdate(), so that if this parameter is > 0 then it would be used instead of \"sz = ReorderBufferChangeSize(change)\"\n>> >>\n>> >> 3) Do the substraction directly into ReorderBufferToastReplace() without any API\n>> >>\n>> >> I'm inclined to go for option 2), what do you think?\n>> >\n>>\n>> Isn't it better if we use option 2) at all places as then we won't\n>> need any special check inside ReorderBufferChangeMemoryUpdate()?\n>\n>\n> If we want to do this then be careful about REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID change. Basically, ReorderBufferChangeMemoryUpdate() ignores this type of change whereas ReorderBufferChangeSize(), consider at least sizeof(ReorderBufferChange) bytes to this change. So if we compute the size using ReorderBufferChangeSize() outside of ReorderBufferChangeMemoryUpdate(), then total size will be different from what we have now. Logically, we should be ignoring/asserting REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID in ReorderBufferChangeSize(), because ReorderBufferChangeMemoryUpdate() is the only caller for this function.\n>\n\nWhy can't we simply ignore it in ReorderBufferChangeMemoryUpdate() as\nwe are doing now?\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 7 Sep 2021 11:10:14 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "On Tue, Sep 7, 2021 at 11:10 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n>> Isn't it better if we use option 2) at all places as then we won't\n> >> need any special check inside ReorderBufferChangeMemoryUpdate()?\n> >\n> >\n> > If we want to do this then be careful about\n> REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID change. Basically,\n> ReorderBufferChangeMemoryUpdate() ignores this type of change whereas\n> ReorderBufferChangeSize(), consider at least sizeof(ReorderBufferChange)\n> bytes to this change. So if we compute the size using\n> ReorderBufferChangeSize() outside of ReorderBufferChangeMemoryUpdate(),\n> then total size will be different from what we have now. Logically, we\n> should be ignoring/asserting REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID in\n> ReorderBufferChangeSize(), because ReorderBufferChangeMemoryUpdate() is the\n> only caller for this function.\n> >\n>\n> Why can't we simply ignore it in ReorderBufferChangeMemoryUpdate() as\n> we are doing now?\n>\n\nYeah right, we can actually do that, it doesn't matter even if we are\npassing the size from outside.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Tue, Sep 7, 2021 at 11:10 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>> Isn't it better if we use option 2) at all places as then we won't\n>> need any special check inside ReorderBufferChangeMemoryUpdate()?\n>\n>\n> If we want to do this then be careful about REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID change.  Basically, ReorderBufferChangeMemoryUpdate() ignores this type of change whereas ReorderBufferChangeSize(), consider at least sizeof(ReorderBufferChange) bytes to this change.  So if we compute the size using ReorderBufferChangeSize() outside of ReorderBufferChangeMemoryUpdate(), then total size will be different from what we have now.   Logically, we should be ignoring/asserting REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID in ReorderBufferChangeSize(), because ReorderBufferChangeMemoryUpdate() is the only caller for this function.\n>\n\nWhy can't we simply ignore it in ReorderBufferChangeMemoryUpdate() as\nwe are doing now?Yeah right, we can actually do that, it doesn't matter even if we are passing the size from outside. -- Regards,Dilip KumarEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Tue, 7 Sep 2021 11:28:24 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "Hi,\n\nOn 9/7/21 7:58 AM, Dilip Kumar wrote:\n>\n> On Tue, Sep 7, 2021 at 11:10 AM Amit Kapila <amit.kapila16@gmail.com \n> <mailto:amit.kapila16@gmail.com>> wrote:\n>\n> >> Isn't it better if we use option 2) at all places as then we won't\n> >> need any special check inside ReorderBufferChangeMemoryUpdate()?\n> >\n> >\n> > If we want to do this then be careful about\n> REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID change. Basically,\n> ReorderBufferChangeMemoryUpdate() ignores this type of change\n> whereas ReorderBufferChangeSize(), consider at least\n> sizeof(ReorderBufferChange) bytes to this change.  So if we\n> compute the size using ReorderBufferChangeSize() outside of\n> ReorderBufferChangeMemoryUpdate(), then total size will be\n> different from what we have now.   Logically, we should be\n> ignoring/asserting REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID in\n> ReorderBufferChangeSize(), because\n> ReorderBufferChangeMemoryUpdate() is the only caller for this\n> function.\n> >\n>\n> Why can't we simply ignore it in ReorderBufferChangeMemoryUpdate() as\n> we are doing now?\n>\n>\n> Yeah right, we can actually do that, it doesn't matter even if we are \n> passing the size from outside.\n\nAgree, if no objections, I'll prepare a patch with the modified approach \nof option 2) proposed by Amit (means passing the size from the outside \nin all the cases).\n\nThanks\n\nBertrand\n\n\n\n\n\n\n\nHi,\n\nOn 9/7/21 7:58 AM, Dilip Kumar wrote:\n\n\n\n\n\n\n\n\nOn Tue, Sep 7, 2021 at 11:10 AM Amit Kapila <amit.kapila16@gmail.com>\n wrote:\n\n\n\n\n\n >> Isn't it better if we use option 2) at all places\n as then we won't\n >> need any special check inside\n ReorderBufferChangeMemoryUpdate()?\n >\n >\n > If we want to do this then be careful about\n REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID change. \n Basically, ReorderBufferChangeMemoryUpdate() ignores this\n type of change whereas ReorderBufferChangeSize(), consider\n at least sizeof(ReorderBufferChange) bytes to this\n change.  So if we compute the size using\n ReorderBufferChangeSize() outside of\n ReorderBufferChangeMemoryUpdate(), then total size will be\n different from what we have now.   Logically, we should be\n ignoring/asserting REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID\n in ReorderBufferChangeSize(), because\n ReorderBufferChangeMemoryUpdate() is the only caller for\n this function.\n >\n\n Why can't we simply ignore it in\n ReorderBufferChangeMemoryUpdate() as\n we are doing now?\n\n\n\nYeah right, we can actually do that, it doesn't matter\n even if we are passing the size from outside. \n\n\n\n\n\nAgree, if no objections, I'll prepare a patch with the modified\n approach of option 2) proposed by Amit (means passing the size\n from the outside in all the cases). \n\nThanks\nBertrand", "msg_date": "Tue, 7 Sep 2021 08:03:38 +0200", "msg_from": "\"Drouvot, Bertrand\" <bdrouvot@amazon.com>", "msg_from_op": true, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "On Tue, Sep 7, 2021 at 11:33 AM Drouvot, Bertrand <bdrouvot@amazon.com> wrote:\n>\n> Hi,\n>\n> On 9/7/21 7:58 AM, Dilip Kumar wrote:\n>\n>\n> On Tue, Sep 7, 2021 at 11:10 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n>> >> Isn't it better if we use option 2) at all places as then we won't\n>> >> need any special check inside ReorderBufferChangeMemoryUpdate()?\n>> >\n>> >\n>> > If we want to do this then be careful about REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID change. Basically, ReorderBufferChangeMemoryUpdate() ignores this type of change whereas ReorderBufferChangeSize(), consider at least sizeof(ReorderBufferChange) bytes to this change. So if we compute the size using ReorderBufferChangeSize() outside of ReorderBufferChangeMemoryUpdate(), then total size will be different from what we have now. Logically, we should be ignoring/asserting REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID in ReorderBufferChangeSize(), because ReorderBufferChangeMemoryUpdate() is the only caller for this function.\n>> >\n>>\n>> Why can't we simply ignore it in ReorderBufferChangeMemoryUpdate() as\n>> we are doing now?\n>\n>\n> Yeah right, we can actually do that, it doesn't matter even if we are passing the size from outside.\n>\n> Agree, if no objections, I'll prepare a patch with the modified approach of option 2) proposed by Amit (means passing the size from the outside in all the cases).\n>\n\nSounds reasonable. Another point that needs some thought is do we want\nto backpatch this change till v13? I am not sure if there is any\nuser-visible bug here but maybe it is still good to fix this in back\nbranches. What do you think?\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 7 Sep 2021 12:21:53 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "\nOn 9/7/21 8:51 AM, Amit Kapila wrote:\n> On Tue, Sep 7, 2021 at 11:33 AM Drouvot, Bertrand <bdrouvot@amazon.com> wrote:\n>> Hi,\n>>\n>> On 9/7/21 7:58 AM, Dilip Kumar wrote:\n>>\n>>\n>> On Tue, Sep 7, 2021 at 11:10 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>\n>>>>> Isn't it better if we use option 2) at all places as then we won't\n>>>>> need any special check inside ReorderBufferChangeMemoryUpdate()?\n>>>>\n>>>> If we want to do this then be careful about REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID change. Basically, ReorderBufferChangeMemoryUpdate() ignores this type of change whereas ReorderBufferChangeSize(), consider at least sizeof(ReorderBufferChange) bytes to this change. So if we compute the size using ReorderBufferChangeSize() outside of ReorderBufferChangeMemoryUpdate(), then total size will be different from what we have now. Logically, we should be ignoring/asserting REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID in ReorderBufferChangeSize(), because ReorderBufferChangeMemoryUpdate() is the only caller for this function.\n>>>>\n>>> Why can't we simply ignore it in ReorderBufferChangeMemoryUpdate() as\n>>> we are doing now?\n>>\n>> Yeah right, we can actually do that, it doesn't matter even if we are passing the size from outside.\n>>\n>> Agree, if no objections, I'll prepare a patch with the modified approach of option 2) proposed by Amit (means passing the size from the outside in all the cases).\n>>\n> Sounds reasonable. Another point that needs some thought is do we want\n> to backpatch this change till v13? I am not sure if there is any\n> user-visible bug here but maybe it is still good to fix this in back\n> branches. What do you think?\n\nYes, +1 to backpatch till v13 \"per precaution\".\n\nI will first come back with a proposed version for master and once we \nagree on a final/polished version then I'll do the backpatch ones (if \nneeded).\n\nThanks\n\nBertrand\n\n\n\n", "msg_date": "Tue, 7 Sep 2021 09:11:01 +0200", "msg_from": "\"Drouvot, Bertrand\" <bdrouvot@amazon.com>", "msg_from_op": true, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "On 9/7/21 9:11 AM, Drouvot, Bertrand wrote:\n>\n> On 9/7/21 8:51 AM, Amit Kapila wrote:\n>> On Tue, Sep 7, 2021 at 11:33 AM Drouvot, Bertrand \n>> <bdrouvot@amazon.com> wrote:\n>>> Hi,\n>>>\n>>> On 9/7/21 7:58 AM, Dilip Kumar wrote:\n>>>\n>>>\n>>> On Tue, Sep 7, 2021 at 11:10 AM Amit Kapila \n>>> <amit.kapila16@gmail.com> wrote:\n>>>\n>>>>>> Isn't it better if we use option 2) at all places as then we won't\n>>>>>> need any special check inside ReorderBufferChangeMemoryUpdate()?\n>>>>>\n>>>>> If we want to do this then be careful about \n>>>>> REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID change. Basically, \n>>>>> ReorderBufferChangeMemoryUpdate() ignores this type of change \n>>>>> whereas ReorderBufferChangeSize(), consider at least \n>>>>> sizeof(ReorderBufferChange) bytes to this change.  So if we \n>>>>> compute the size using ReorderBufferChangeSize() outside of \n>>>>> ReorderBufferChangeMemoryUpdate(), then total size will be \n>>>>> different from what we have now.   Logically, we should be \n>>>>> ignoring/asserting REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID in \n>>>>> ReorderBufferChangeSize(), because \n>>>>> ReorderBufferChangeMemoryUpdate() is the only caller for this \n>>>>> function.\n>>>>>\n>>>> Why can't we simply ignore it in ReorderBufferChangeMemoryUpdate() as\n>>>> we are doing now?\n>>>\n>>> Yeah right, we can actually do that, it doesn't matter even if we \n>>> are passing the size from outside.\n>>>\n>>> Agree, if no objections, I'll prepare a patch with the modified \n>>> approach of option 2) proposed by Amit (means passing the size from \n>>> the outside in all the cases).\n>>>\n>> Sounds reasonable. Another point that needs some thought is do we want\n>> to backpatch this change till v13?  I am not sure if there is any\n>> user-visible bug here but maybe it is still good to fix this in back\n>> branches. What do you think?\n>\n> Yes, +1 to backpatch till v13 \"per precaution\".\n>\n> I will first come back with a proposed version for master and once we \n> agree on a final/polished version then I'll do the backpatch ones (if \n> needed).\n\nPlease find enclosed patch v2 (for the master branch) implementing the \nmodified approach of option 2) proposed by Amit.\n\nThanks\n\nBertrand", "msg_date": "Tue, 7 Sep 2021 10:32:06 +0200", "msg_from": "\"Drouvot, Bertrand\" <bdrouvot@amazon.com>", "msg_from_op": true, "msg_subject": "Re: [UNVERIFIED SENDER] Re: [BUG] Failed Assertion in\n ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "On Tue, Sep 7, 2021 at 2:02 PM Drouvot, Bertrand <bdrouvot@amazon.com> wrote:\n>\n> On 9/7/21 9:11 AM, Drouvot, Bertrand wrote:\n> >\n>\n> Please find enclosed patch v2 (for the master branch) implementing the\n> modified approach of option 2) proposed by Amit.\n>\n\nThe patch looks good to me. I have made a minor modification in the\ncomment to make it explicit why we are not subtracting the size\nimmediately and ran pgindent. Kindly prepare back-branch patches and\ntest the same.\n\n-- \nWith Regards,\nAmit Kapila.", "msg_date": "Thu, 9 Sep 2021 16:46:41 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [UNVERIFIED SENDER] Re: [BUG] Failed Assertion in\n ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "Hi,\n\nOn 9/9/21 1:16 PM, Amit Kapila wrote:\n> On Tue, Sep 7, 2021 at 2:02 PM Drouvot, Bertrand <bdrouvot@amazon.com> wrote:\n>> On 9/7/21 9:11 AM, Drouvot, Bertrand wrote:\n>> Please find enclosed patch v2 (for the master branch) implementing the\n>> modified approach of option 2) proposed by Amit.\n>>\n> The patch looks good to me. I have made a minor modification in the\n> comment to make it explicit why we are not subtracting the size\n> immediately\n\nThanks!\n\nIndeed, good point to also mention in the comment why it has been done \nthat way.\n\n> Kindly prepare back-branch patches and\n> test the same.\n\nPlease find enclosed the modified (and tested) version for the \nREL_13_STABLE branch (the master patch version also applied on \nREL_14_STABLE).\n\nThanks\n\nBertrand", "msg_date": "Thu, 9 Sep 2021 15:16:00 +0200", "msg_from": "\"Drouvot, Bertrand\" <bdrouvot@amazon.com>", "msg_from_op": true, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "Hi,\n\nOn 9/9/21 3:16 PM, Drouvot, Bertrand wrote:\n> Hi,\n>\n> On 9/9/21 1:16 PM, Amit Kapila wrote:\n>> On Tue, Sep 7, 2021 at 2:02 PM Drouvot, Bertrand \n>> <bdrouvot@amazon.com> wrote:\n>>> On 9/7/21 9:11 AM, Drouvot, Bertrand wrote:\n>>> Please find enclosed patch v2 (for the master branch) implementing the\n>>> modified approach of option 2) proposed by Amit.\n>>>\n>> The patch looks good to me. I have made a minor modification in the\n>> comment to make it explicit why we are not subtracting the size\n>> immediately\n>\n> Thanks!\n>\n> Indeed, good point to also mention in the comment why it has been done \n> that way.\n>\n>> Kindly prepare back-branch patches and\n>> test the same.\n>\n> Please find enclosed the modified (and tested) version for the \n> REL_13_STABLE branch (the master patch version also applied on \n> REL_14_STABLE).\n>\nI've seen that the patches have been committed, thanks!\n\nI'm marking the corresponding CF entry as committed.\n\nThanks\n\nBertrand\n\n\n\n", "msg_date": "Mon, 13 Sep 2021 08:34:44 +0200", "msg_from": "\"Drouvot, Bertrand\" <bdrouvot@amazon.com>", "msg_from_op": true, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "On 2021-Sep-06, Amit Kapila wrote:\n\n> The error can occur at multiple places (like via palloc or various\n> other places) between the first time we subtract the change_size and\n> add it back after the change is re-computed. I think the correct fix\n> would be that in the beginning we just compute the change_size by\n> ReorderBufferChangeSize and then after re-computing the change, we\n> just subtract the old change_size and add the new change_size. What do\n> you think?\n\nAm I the only that that thinks this code is doing far too much in a\nPG_CATCH block?\n\n-- \nÁlvaro Herrera Valdivia, Chile — 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": "Mon, 13 Sep 2021 13:52:39 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> Am I the only that that thinks this code is doing far too much in a\n> PG_CATCH block?\n\nYou mean the one in ReorderBufferProcessTXN? Yeah, that is mighty\nugly. It might be all right given that it almost immediately does\nAbortCurrentTransaction, since that should basically clean up\nwhatever is wrong. But I'm still full of questions after a brief\nlook at it.\n\n* What is the sense in calling RollbackAndReleaseCurrentSubTransaction\nafter having done AbortCurrentTransaction?\n\n* Is it really sane that we re-throw the error in some cases and\nnot others? What is likely to catch that thrown error, and is it\ngoing to be prepared for us having already aborted the transaction?\n(It doesn't give me a warm feeling that the code coverage report\nshows that path to be un-exercised.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 13 Sep 2021 13:12:48 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" }, { "msg_contents": "On Mon, Sep 13, 2021 at 10:42 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> > Am I the only that that thinks this code is doing far too much in a\n> > PG_CATCH block?\n>\n> You mean the one in ReorderBufferProcessTXN? Yeah, that is mighty\n> ugly. It might be all right given that it almost immediately does\n> AbortCurrentTransaction, since that should basically clean up\n> whatever is wrong. But I'm still full of questions after a brief\n> look at it.\n>\n> * What is the sense in calling RollbackAndReleaseCurrentSubTransaction\n> after having done AbortCurrentTransaction?\n>\n\nIt is required for the cases where we are starting internal\nsub-transaction (when decoding via SQL SRF). The first\nAbortCurrentTransaction will make the current subtransaction state to\nTBLOCK_SUBABORT and then RollbackAndReleaseCurrentSubTransaction will\npop and release the current subtransaction. Note that the same\nsequence is performed outside catch and if we comment out\nRollbackAndReleaseCurrentSubTransaction, there are a lot of failures\nin test_decoding. I have manually debugged and checked that if we\ndon't call RollbackAndReleaseCurrentSubTransaction in the catch block,\nit will retain the transaction in a bad state which on the next\noperation leads to a FATAL error.\n\n> * Is it really sane that we re-throw the error in some cases and\n> not others? What is likely to catch that thrown error, and is it\n> going to be prepared for us having already aborted the transaction?\n>\n\nThere are two different ways which deal with the re-thrown error. For\nWALSender processes, we don't start internal subtransaction and on\nerror, they simply exist. For SQL SRFs, we start internal transactions\nwhich will be released in the catch block, and then the top\ntransaction will be aborted after we re-throw the error.\n\nThe cases where we don't immediately rethrow are specifically for\nstreaming transactions where we might have already sent some changes\nto the subscriber and we want to continue processing and send the\nabort to subscribers.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 14 Sep 2021 14:40:43 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [BUG] Failed Assertion in ReorderBufferChangeMemoryUpdate()" } ]
[ { "msg_contents": "Hi,\n\nWe are using Postgres 10 (Single client)and observed that there are multiple PostgreSQL Server process are running in background.\nWhy these additional process are created or is this an expected behavior.\n\n[cid:image001.png@01D7905A.F629F440]\n\nRegards,\nRamCharan", "msg_date": "Fri, 13 Aug 2021 10:20:41 +0000", "msg_from": "Ram Charan Kallem <RamCharan.Kallem@non.se.com>", "msg_from_op": true, "msg_subject": "RE: Multiple Postgres process are running in background" }, { "msg_contents": "On 8/13/21 3:20 AM, Ram Charan Kallem wrote:\n> Hi,\n> \n> We are using Postgres 10 (Single client)and observed that there are \n> multiple PostgreSQL Server process are running in background.\n> \n> Why these additional process are created �or is this an expected behavior.\n\nYes. From my Linux machine:\n\n ps ax | grep postgres\n 818 ? Ss 0:00 /usr/local/pgsql12/bin/postgres -D \n/usr/local/pgsql12_test/data\n 906 ? Ss 0:00 /usr/local/pgsql12/bin/postgres -D \n/usr/local/pgsql12/data\n 954 ? Ss 0:00 postgres: logger\n 982 ? Ss 0:00 postgres: logger\n 984 ? Ss 0:00 postgres: checkpointer\n 985 ? Ss 0:00 postgres: background writer\n 986 ? Ss 0:00 postgres: walwriter\n 987 ? Ss 0:00 postgres: autovacuum launcher\n 988 ? Ss 0:00 postgres: stats collector\n 989 ? Ss 0:00 postgres: logical replication launcher\n 1001 ? Ss 0:00 postgres: checkpointer\n 1002 ? Ss 0:00 postgres: background writer\n 1003 ? Ss 0:00 postgres: walwriter\n 1004 ? Ss 0:00 postgres: autovacuum launcher\n 1005 ? Ss 0:00 postgres: stats collector\n 1006 ? Ss 0:00 postgres: logical replication launcher\n 7204 pts/0 S+ 0:00 psql -d test -U postgres\n 7205 ? Ss 0:00 postgres: postgres test [local] idle\n 7250 pts/1 S+ 0:00 psql -d production -U postgres -p 5442\n 7251 ? Ss 0:00 postgres: postgres production [local] idle\n 7296 pts/2 S+ 0:00 grep --color=auto postgres\n\nThere are background processes that run as well as process for each \nconnection.\n\n> \n> Regards,\n> \n> RamCharan\n> \n\n\n-- \nAdrian Klaver\nadrian.klaver@aklaver.com\n\n\n", "msg_date": "Fri, 13 Aug 2021 08:34:56 -0700", "msg_from": "Adrian Klaver <adrian.klaver@aklaver.com>", "msg_from_op": false, "msg_subject": "Re: Multiple Postgres process are running in background" }, { "msg_contents": "Em sex., 13 de ago. de 2021 às 11:55, Ram Charan Kallem <\nRamCharan.Kallem@non.se.com> escreveu:\n\n> Hi,\n>\n>\n>\n> We are using Postgres 10 (Single client)and observed that there are\n> multiple PostgreSQL Server process are running in background.\n>\n> Why these additional process are created or is this an expected behavior.\n>\nThis is a normal and expected behavior.\n\npgsql-hackers@, is not an appropriate place to such questions.\n\nregards,\nRanier Vilela\n\nEm sex., 13 de ago. de 2021 às 11:55, Ram Charan Kallem <RamCharan.Kallem@non.se.com> escreveu:\n\n\nHi,\n \nWe are using Postgres 10 (Single client)and observed that there are multiple PostgreSQL Server process are running in background.\nWhy these additional process are created  or is this an expected behavior.This is a normal and expected behavior. pgsql-hackers@, is not an appropriate place to such questions.regards,Ranier Vilela", "msg_date": "Fri, 13 Aug 2021 13:16:07 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Multiple Postgres process are running in background" } ]
[ { "msg_contents": "Hello,\n\nThe attached patch adds native spinlock support to PostgreSQL on RISC-V \nsystems. As suspected by Richard W.M. Jones of Red Hat back in 2016, the \n__sync_lock_test_and_set() approach applied on arm and arm64 works here \nas well.\n\nTested against PostgreSQL 13.3 on a physical rv64gc system (BeagleV \nStarlight beta board) - builds and installs fine, all tests pass. From \nwhat I can see in gcc documentation this should in theory work on rv32 \n(and possibly rv128) as well, therefore the patch as it stands covers \nall RISC-V systems (i.e. doesn't check the value of __risc_xlen) - but I \nhaven't confirmed this experimentally.\n\n-- \nMS", "msg_date": "Fri, 13 Aug 2021 12:54:52 +0100", "msg_from": "Marek Szuba <marecki@gentoo.org>", "msg_from_op": true, "msg_subject": "[PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "Marek Szuba <marecki@gentoo.org> writes:\n> Tested against PostgreSQL 13.3 on a physical rv64gc system (BeagleV \n> Starlight beta board) - builds and installs fine, all tests pass.\n\nCool ... I had hoped to acquire one of those myself, but I didn't\nmake the cut.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 13 Aug 2021 11:09:04 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "Hi,\n\nOn 2021-08-13 11:09:04 -0400, Tom Lane wrote:\n> Marek Szuba <marecki@gentoo.org> writes:\n> > Tested against PostgreSQL 13.3 on a physical rv64gc system (BeagleV\n> > Starlight beta board) - builds and installs fine, all tests pass.\n\nSeems like a good idea to me.\n\n> Cool ... I had hoped to acquire one of those myself, but I didn't\n> make the cut.\n\nShould we backpatch this? It's not like we're going to break existing\nrisc-v systems by enabling spinlock support...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 13 Aug 2021 08:30:01 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2021-08-13 11:09:04 -0400, Tom Lane wrote:\n>> Marek Szuba <marecki@gentoo.org> writes:\n>>> Tested against PostgreSQL 13.3 on a physical rv64gc system (BeagleV\n>>> Starlight beta board) - builds and installs fine, all tests pass.\n\n> Should we backpatch this? It's not like we're going to break existing\n> risc-v systems by enabling spinlock support...\n\nYeah, why not? If you were building with --disable-spinlocks before,\nthis shouldn't change anything for you.\n\n(I haven't actually looked at the patch, mind you, but in principle\nit shouldn't break anything that worked before.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 13 Aug 2021 12:03:28 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "I wrote:\n> Andres Freund <andres@anarazel.de> writes:\n>> Should we backpatch this? It's not like we're going to break existing\n>> risc-v systems by enabling spinlock support...\n\n> Yeah, why not? If you were building with --disable-spinlocks before,\n> this shouldn't change anything for you.\n> (I haven't actually looked at the patch, mind you, but in principle\n> it shouldn't break anything that worked before.)\n\nI now have looked at the patch, and it seems good as far as it goes,\nbut I wonder whether some effort ought to be expended in\nsrc/include/port/atomics/.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 13 Aug 2021 13:25:05 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "Hi,\n\nOn Fri, Aug 13, 2021, at 19:25, Tom Lane wrote:\n> I wrote:\n> > Andres Freund <andres@anarazel.de> writes:\n> >> Should we backpatch this? It's not like we're going to break existing\n> >> risc-v systems by enabling spinlock support...\n> \n> > Yeah, why not? If you were building with --disable-spinlocks before,\n> > this shouldn't change anything for you.\n> > (I haven't actually looked at the patch, mind you, but in principle\n> > it shouldn't break anything that worked before.)\n> \n> I now have looked at the patch, and it seems good as far as it goes,\n> but I wonder whether some effort ought to be expended in\n> src/include/port/atomics/.\n\nThat should automatically pick up the intrinsic. I think we should do the same on modern compilers for spinlocks, but that's a separate discussion I guess.\n\nAddress\n\n\n", "msg_date": "Fri, 13 Aug 2021 19:29:54 +0200", "msg_from": "\"Andres Freund\" <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "\"Andres Freund\" <andres@anarazel.de> writes:\n> On Fri, Aug 13, 2021, at 19:25, Tom Lane wrote:\n>> I now have looked at the patch, and it seems good as far as it goes,\n>> but I wonder whether some effort ought to be expended in\n>> src/include/port/atomics/.\n\n> That should automatically pick up the intrinsic. I think we should do the same on modern compilers for spinlocks, but that's a separate discussion I guess.\n\nI was looking at the comment in atomics.h about\n\n * Provide a full fallback of the pg_*_barrier(), pg_atomic**_flag and\n * pg_atomic_* APIs for platforms without sufficient spinlock and/or atomics\n * support. In the case of spinlock backed atomics the emulation is expected\n * to be efficient, although less so than native atomics support.\n\nso it seems like someday we might want to expend some effort on native\natomics. I agree that that day need not be today, though. This patch\nseems sufficient until we get to the point of (at least) having some\nRISC-V in the buildfarm.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 13 Aug 2021 13:37:02 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "Hi,\n\nOn 2021-08-13 13:37:02 -0400, Tom Lane wrote:\n> \"Andres Freund\" <andres@anarazel.de> writes:\n> > On Fri, Aug 13, 2021, at 19:25, Tom Lane wrote:\n> >> I now have looked at the patch, and it seems good as far as it goes,\n> >> but I wonder whether some effort ought to be expended in\n> >> src/include/port/atomics/.\n> \n> > That should automatically pick up the intrinsic. I think we should do the same on modern compilers for spinlocks, but that's a separate discussion I guess.\n> \n> I was looking at the comment in atomics.h about\n> \n> * Provide a full fallback of the pg_*_barrier(), pg_atomic**_flag and\n> * pg_atomic_* APIs for platforms without sufficient spinlock and/or atomics\n> * support. In the case of spinlock backed atomics the emulation is expected\n> * to be efficient, although less so than native atomics support.\n> \n> so it seems like someday we might want to expend some effort on native\n> atomics. I agree that that day need not be today, though. This patch\n> seems sufficient until we get to the point of (at least) having some\n> RISC-V in the buildfarm.\n\nFor gcc compatible compilers the relevant comments would be\n\n * There exist generic, hardware independent, implementations for several\n * compilers which might be sufficient, although possibly not optimal, for a\n * new platform. If no such generic implementation is available spinlocks (or\n * even OS provided semaphores) will be used to implement the API.\n\nand\n\n/*\n * Compiler specific, but architecture independent implementations.\n *\n * Provide architecture independent implementations of the atomic\n * facilities. At the very least compiler barriers should be provided, but a\n * full implementation of\n * * pg_compiler_barrier(), pg_write_barrier(), pg_read_barrier()\n * * pg_atomic_compare_exchange_u32(), pg_atomic_fetch_add_u32()\n * using compiler intrinsics are a good idea.\n */\n\nGcc's intriniscs are pretty good these days (and if not, a *lot* of\nprojects just outright break).\n\nWhat's more, It turns out that using intrinsics with compilers of the\nlast ~5 years often generates *better* code than inline assembly\n(e.g. because the compiler can utilize condition codes more effectively\nand has more detailed information about clobbers). So for new platforms\nthat'll only have support by new compilers it doesn't really make sense\nto add inline assembler imo.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 13 Aug 2021 10:55:53 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2021-08-13 13:37:02 -0400, Tom Lane wrote:\n>> so it seems like someday we might want to expend some effort on native\n>> atomics. I agree that that day need not be today, though. This patch\n>> seems sufficient until we get to the point of (at least) having some\n>> RISC-V in the buildfarm.\n\n> Gcc's intriniscs are pretty good these days (and if not, a *lot* of\n> projects just outright break).\n> What's more, It turns out that using intrinsics with compilers of the\n> last ~5 years often generates *better* code than inline assembly\n> (e.g. because the compiler can utilize condition codes more effectively\n> and has more detailed information about clobbers). So for new platforms\n> that'll only have support by new compilers it doesn't really make sense\n> to add inline assembler imo.\n\nI didn't say it had to be __asm blocks ;-). I was thinking more of the\nsort of stuff we have in e.g. arch-arm.h and arch-ia64.h, where we know\nsome things about what is efficient or less efficient on a particular\narchitecture. gcc will do its best to provide implementations of\nits builtins, but that doesn't mean that using a particular one of\nthem is always the most sane thing to do.\n\nBut anyway, that seems like minor optimization that maybe someday\nsomebody will be motivated to do. We're on the same page about this\nbeing enough for today.\n\nI did not like confusing the RISC-V case with the ARM case: duplicating\nthe code block seems better, in case there's ever reason to add\narch-specific stuff like SPIN_DELAY. So I split it off to its own\ncode block and pushed it.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 13 Aug 2021 14:09:04 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "> On 13 Aug 2021, at 20:09, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> ..I split it off to its own code block and pushed it.\n\n\nThere didn’t seem to be anything left here (at least until there is hardware in\nthe buildfarm) so I took the liberty to close it as committed in the CF app.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Mon, 16 Aug 2021 20:17:27 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "Daniel Gustafsson <daniel@yesql.se> writes:\n> There didn’t seem to be anything left here (at least until there is hardware in\n> the buildfarm) so I took the liberty to close it as committed in the CF app.\n\nAh, sorry, I did not realize there was a CF entry.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 16 Aug 2021 15:09:03 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "Re: Tom Lane\n> I did not like confusing the RISC-V case with the ARM case: duplicating\n> the code block seems better, in case there's ever reason to add\n> arch-specific stuff like SPIN_DELAY. So I split it off to its own\n> code block and pushed it.\n\nFwiw I can report success on Debian's riscv port with that commit\ncherry-picked onto 13.4:\n\nhttps://buildd.debian.org/status/fetch.php?pkg=postgresql-13&arch=riscv64&ver=13.4-3&stamp=1630411643&raw=0\n\nChristoph\n\n\n", "msg_date": "Wed, 1 Sep 2021 11:21:58 +0200", "msg_from": "Christoph Berg <myon@debian.org>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "On Wed, Sep 1, 2021 at 9:22 PM Christoph Berg <myon@debian.org> wrote:\n> Re: Tom Lane\n> > I did not like confusing the RISC-V case with the ARM case: duplicating\n> > the code block seems better, in case there's ever reason to add\n> > arch-specific stuff like SPIN_DELAY. So I split it off to its own\n> > code block and pushed it.\n>\n> Fwiw I can report success on Debian's riscv port with that commit\n> cherry-picked onto 13.4:\n>\n> https://buildd.debian.org/status/fetch.php?pkg=postgresql-13&arch=riscv64&ver=13.4-3&stamp=1630411643&raw=0\n\nA couple of things I noticed on this architecture:\n\n1. Even though we're using generic built-ins for atomics, I guess we\ncould still use a src/include/port/atomics/arch-riscv.h file so we\nhave a place to define PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY when\nbuilding for 64 bit. We'd need to find the chapter-and-verse to\njustify that, of course, which I can try to do; if someone more\nfamiliar with the ISA/spec/manual can point to it I'm all ears.\n\n2. When configured with all options on FreeBSD 13, everything looks\ngood so far except LLVM JIT, which fails with various \"Cannot select\"\nerrors. Clang works fine for compiling PostgreSQL itself. Tested\nwith LLVM 12 (LLVM has supported RISCV since 9). Example:\n\n+FATAL: fatal llvm error: Cannot select: 0x4f772068: ch = brcond\n0x4f770f70, 0x4f772208, BasicBlock:ch< 0x4f76d600>\n+ 0x4f772208: i64 = setcc 0x4f7723a8, Constant:i64<0>, setlt:ch\n+ 0x4f7723a8: i64,ch = load<(load 4 from `i32* inttoptr (i64\n1260491408 to i32*)`, align 16), sext from i32> 0x4fdee058,\nConstant:i64<1260491408>, undef:i64\n+ 0x4f770a90: i64 = Constant<1260491408>\n+ 0x4f7703a8: i64 = undef\n+ 0x4f7701a0: i64 = Constant<0>\n+In function: evalexpr_0_0\n\n\n", "msg_date": "Wed, 3 Nov 2021 11:55:58 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "Hi, \n\nOn November 2, 2021 3:55:58 PM PDT, Thomas Munro <thomas.munro@gmail.com> wrote:\n>2. When configured with all options on FreeBSD 13, everything looks\n>good so far except LLVM JIT, which fails with various \"Cannot select\"\n>errors. Clang works fine for compiling PostgreSQL itself. Tested\n>with LLVM 12 (LLVM has supported RISCV since 9). Example:\n>\n>+FATAL: fatal llvm error: Cannot select: 0x4f772068: ch = brcond\n>0x4f770f70, 0x4f772208, BasicBlock:ch< 0x4f76d600>\n>+ 0x4f772208: i64 = setcc 0x4f7723a8, Constant:i64<0>, setlt:ch\n>+ 0x4f7723a8: i64,ch = load<(load 4 from `i32* inttoptr (i64\n>1260491408 to i32*)`, align 16), sext from i32> 0x4fdee058,\n>Constant:i64<1260491408>, undef:i64\n>+ 0x4f770a90: i64 = Constant<1260491408>\n>+ 0x4f7703a8: i64 = undef\n>+ 0x4f7701a0: i64 = Constant<0>\n>+In function: evalexpr_0_0\n\nAny chance you could enable jit_dump_bitcode and manually try a failing query? That should dump. bc files in the data directory. That'd might allow debugging this outside the emulated environment.\n\nI don't see where the undef is originating from, but I think it might suggest that something lead to that code being considered unreachable.\n\nAndres\n-- \nSent from my Android device with K-9 Mail. Please excuse my brevity.\n\n\n", "msg_date": "Tue, 02 Nov 2021 21:13:24 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "On Wed, Nov 3, 2021 at 5:13 PM Andres Freund <andres@anarazel.de> wrote:\n> Any chance you could enable jit_dump_bitcode and manually try a failing query? That should dump. bc files in the data directory. That'd might allow debugging this outside the emulated environment.\n>\n> I don't see where the undef is originating from, but I think it might suggest that something lead to that code being considered unreachable.\n\npostgres=# set jit_above_cost = 0;\nSET\npostgres=# select 1 + 1;\nFATAL: fatal llvm error: Cannot select: 0x4b3ec1a0: i64,ch =\nload<(load 8 from %ir.14)> 0x41ef6fe8, 0x4b3ec138, undef:i64\n 0x4b3ec138: i64 = add nuw 0x4b3eab60, Constant:i64<24>\n 0x4b3eab60: i64,ch = load<(load 8 from %ir.7)> 0x41ef6fe8,\n0x4b3eaaf8, undef:i64\n 0x4b3eaaf8: i64 = add nuw 0x4b3ea068, Constant:i64<16>\n 0x4b3ea068: i64,ch = CopyFromReg 0x41ef6fe8, Register:i64 %4\n 0x4b3ea000: i64 = Register %4\n 0x4b3ea888: i64 = Constant<16>\n 0x4b3ea6e8: i64 = undef\n 0x4b3ea9c0: i64 = Constant<24>\n 0x4b3ea6e8: i64 = undef\nIn function: evalexpr_0_0\n\nAh, I hadn't noticed this in the log before:\n\n'generic' is not a recognized processor for this target (ignoring processor)\n\nSounds kinda serious :-)\n\nResulting .bc files and .ll files (produced by llvm-dis) attached.", "msg_date": "Wed, 3 Nov 2021 17:41:47 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "On Wed, Nov 3, 2021 at 5:41 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> 'generic' is not a recognized processor for this target (ignoring processor)\n\nI still don't know what's wrong but I spent 20 minutes searching for\nmore clues this morning...\n\nFirst, 'generic' is coming from LLVMGetHostCPUName(), and yet it's not\naccepted by LLVMCreateTargetMachine(). Ok then, let's try something\nelse:\n\n$ clang12 --print-supported-cpus\n\nTarget: riscv64-portbld-freebsd13.0\nThread model: posix\nInstalledDir: /usr/local/llvm12/bin\nAvailable CPUs for this target:\n\n generic-rv32\n generic-rv64\n rocket-rv32\n rocket-rv64\n sifive-7-rv32\n sifive-7-rv64\n sifive-e31\n sifive-e76\n sifive-u54\n sifive-u74\n\nSo I hacked my copy of PostgreSQL thusly:\n\n+ cpu = LLVMCreateMessage(\"generic-rv64\");\n\n... and now I get:\n\n2021-11-03 20:27:28.487 UTC [26880] FATAL: fatal llvm error:\nRelocation type not implemented yet!\n\nTaking that at face value, instead of LLVMRelocDefault, I tried a\ncouple of other values like LLVMRelocDynamicNoPic, but same result.\nSo I attached a debugger to see the stack producing the error, and\nhuh, I see a clue that it's confusing this architecture with SystemZ\n(= IBM mainframe).\n\n(gdb) break fatal_llvm_error_handler\nFunction \"fatal_llvm_error_handler\" not defined.\nMake breakpoint pending on future shared library load? (y or [n]) y\nBreakpoint 1 (fatal_llvm_error_handler) pending.\n(gdb) cont\nContinuing.\n\nBreakpoint 1, fatal_llvm_error_handler (user_data=0x0,\nreason=\"Relocation type not implemented yet!\", gen_crash_diag=true) at\nllvmjit_error.cpp:147\n147 ereport(FATAL,\n(gdb) bt\n#0 fatal_llvm_error_handler (user_data=0x0, reason=\"Relocation type\nnot implemented yet!\", gen_crash_diag=true) at llvmjit_error.cpp:147\n#1 0x000000004dc3729a in llvm::report_fatal_error(llvm::Twine const&,\nbool) () from /usr/local/llvm12/lib/libLLVM-12.so\n#2 0x000000004dc371d0 in llvm::report_fatal_error(char const*, bool)\n() from /usr/local/llvm12/lib/libLLVM-12.so\n#3 0x000000004ef61010 in\nllvm::RuntimeDyldELF::resolveSystemZRelocation(llvm::SectionEntry\nconst&, unsigned long, unsigned long, unsigned int, long) () from\n/usr/local/llvm12/lib/libLLVM-12.so\n#4 0x000000004ef547c6 in\nllvm::RuntimeDyldImpl::applyExternalSymbolRelocations(llvm::StringMap<llvm::JITEvaluatedSymbol,\nllvm::MallocAllocator>) () from /usr/local/llvm12/lib/libLLVM-12.so\n#5 0x000000004ef54fb4 in ?? () from /usr/local/llvm12/lib/libLLVM-12.so\n#6 0x000000004ef54be6 in\nllvm::RuntimeDyldImpl::finalizeAsync(std::__1::unique_ptr<llvm::RuntimeDyldImpl,\nstd::__1::default_delete<llvm::RuntimeDyldImpl> >,\nllvm::unique_function<void\n(llvm::object::OwningBinary<llvm::object::ObjectFile>,\nstd::__1::unique_ptr<llvm::RuntimeDyld::LoadedObjectInfo,\nstd::__1::default_delete<llvm::RuntimeDyld::LoadedObjectInfo> >,\nllvm::Error)>, llvm::object::OwningBinary<llvm::object::ObjectFile>,\nstd::__1::unique_ptr<llvm::RuntimeDyld::LoadedObjectInfo,\nstd::__1::default_delete<llvm::RuntimeDyld::LoadedObjectInfo> >) ()\n from /usr/local/llvm12/lib/libLLVM-12.so\n#7 0x000000004ef55e2a in\nllvm::jitLinkForORC(llvm::object::OwningBinary<llvm::object::ObjectFile>,\nllvm::RuntimeDyld::MemoryManager&, llvm::JITSymbolResolver&, bool,\nllvm::unique_function<llvm::Error (llvm::object::ObjectFile const&,\nllvm::RuntimeDyld::LoadedObjectInfo&, std::__1::map<llvm::StringRef,\nllvm::JITEvaluatedSymbol, std::__1::less<llvm::StringRef>,\nstd::__1::allocator<std::__1::pair<llvm::StringRef const,\nllvm::JITEvaluatedSymbol> > >)>, llvm::unique_function<void\n(llvm::object::OwningBinary<llvm::object::ObjectFile>,\nstd::__1::unique_ptr<llvm::RuntimeDyld::LoadedObjectInfo,\nstd::__1::default_delete<llvm::RuntimeDyld::LoadedObjectInfo> >,\nllvm::Error)>) ()\n from /usr/local/llvm12/lib/libLLVM-12.so\n#8 0x000000004ef421ea in\nllvm::orc::RTDyldObjectLinkingLayer::emit(std::__1::unique_ptr<llvm::orc::MaterializationResponsibility,\nstd::__1::default_delete<llvm::orc::MaterializationResponsibility> >,\nstd::__1::unique_ptr<llvm::MemoryBuffer,\nstd::__1::default_delete<llvm::MemoryBuffer> >) () from\n/usr/local/llvm12/lib/libLLVM-12.so\n#9 0x000000004ef3e946 in\nllvm::orc::ObjectTransformLayer::emit(std::__1::unique_ptr<llvm::orc::MaterializationResponsibility,\nstd::__1::default_delete<llvm::orc::MaterializationResponsibility> >,\nstd::__1::unique_ptr<llvm::MemoryBuffer,\nstd::__1::default_delete<llvm::MemoryBuffer> >) () from\n/usr/local/llvm12/lib/libLLVM-12.so\n#10 0x000000004ef25c0c in\nllvm::orc::IRCompileLayer::emit(std::__1::unique_ptr<llvm::orc::MaterializationResponsibility,\nstd::__1::default_delete<llvm::orc::MaterializationResponsibility> >,\nllvm::orc::ThreadSafeModule) () from\n/usr/local/llvm12/lib/libLLVM-12.so\n#11 0x000000004ef25fb2 in\nllvm::orc::IRTransformLayer::emit(std::__1::unique_ptr<llvm::orc::MaterializationResponsibility,\nstd::__1::default_delete<llvm::orc::MaterializationResponsibility> >,\nllvm::orc::ThreadSafeModule) () from\n/usr/local/llvm12/lib/libLLVM-12.so\n#12 0x000000004ef25fb2 in\nllvm::orc::IRTransformLayer::emit(std::__1::unique_ptr<llvm::orc::MaterializationResponsibility,\nstd::__1::default_delete<llvm::orc::MaterializationResponsibility> >,\nllvm::orc::ThreadSafeModule) () from\n/usr/local/llvm12/lib/libLLVM-12.so\n#13 0x000000004ef2a614 in\nllvm::orc::BasicIRLayerMaterializationUnit::materialize(std::__1::unique_ptr<llvm::orc::MaterializationResponsibility,\nstd::__1::default_delete<llvm::orc::MaterializationResponsibility> >)\n() from /usr/local/llvm12/lib/libLLVM-12.so\n#14 0x000000004ef08dc2 in ?? () from /usr/local/llvm12/lib/libLLVM-12.so\n#15 0x000000004ef0f61c in std::__1::__function::__func<void\n(*)(std::__1::unique_ptr<llvm::orc::MaterializationUnit,\nstd::__1::default_delete<llvm::orc::MaterializationUnit> >,\nstd::__1::unique_ptr<llvm::orc::MaterializationResponsibility,\nstd::__1::default_delete<llvm::orc::MaterializationResponsibility> >),\nstd::__1::allocator<void\n(*)(std::__1::unique_ptr<llvm::orc::MaterializationUnit,\nstd::__1::default_delete<llvm::orc::MaterializationUnit> >,\nstd::__1::unique_ptr<llvm::orc::MaterializationResponsibility,\nstd::__1::default_delete<llvm::orc::MaterializationResponsibility>\n>)>, void (std::__1::unique_ptr<llvm::orc::MaterializationUnit,\nstd::__1::default_delete<llvm::orc::MaterializationUnit> >,\nstd::__1::unique_ptr<llvm::orc::MaterializationResponsibility,\nstd::__1::default_delete<llvm::orc::MaterializationResponsibility>\n>)>::operator()(std::__1::unique_ptr<llvm::orc::MaterializationUnit,\nstd::__1::default_delete<llvm::orc::MaterializationUnit> >&&,\nstd::__1::unique_ptr<llvm::orc::MaterializationResponsibility,\nstd::__1::default_delete<llvm::orc::MaterializationResponsibility>\n>&&) ()\n from /usr/local/llvm12/lib/libLLVM-12.so\n#16 0x000000004ef09c12 in\nllvm::orc::ExecutionSession::dispatchOutstandingMUs() () from\n/usr/local/llvm12/lib/libLLVM-12.so\n#17 0x000000004ef0b684 in\nllvm::orc::ExecutionSession::OL_completeLookup(std::__1::unique_ptr<llvm::orc::InProgressLookupState,\nstd::__1::default_delete<llvm::orc::InProgressLookupState> >,\nstd::__1::shared_ptr<llvm::orc::AsynchronousSymbolQuery>,\nstd::__1::function<void (llvm::DenseMap<llvm::orc::JITDylib*,\nllvm::DenseSet<llvm::orc::SymbolStringPtr,\nllvm::DenseMapInfo<llvm::orc::SymbolStringPtr> >,\nllvm::DenseMapInfo<llvm::orc::JITDylib*>,\nllvm::detail::DenseMapPair<llvm::orc::JITDylib*,\nllvm::DenseSet<llvm::orc::SymbolStringPtr,\nllvm::DenseMapInfo<llvm::orc::SymbolStringPtr> > > > const&)>) () from\n/usr/local/llvm12/lib/libLLVM-12.so\n#18 0x000000004ef141ee in ?? () from /usr/local/llvm12/lib/libLLVM-12.so\n#19 0x000000004ef01c1e in\nllvm::orc::ExecutionSession::OL_applyQueryPhase1(std::__1::unique_ptr<llvm::orc::InProgressLookupState,\nstd::__1::default_delete<llvm::orc::InProgressLookupState> >,\nllvm::Error) () from /usr/local/llvm12/lib/libLLVM-12.so\n#20 0x000000004ef0096c in\nllvm::orc::ExecutionSession::lookup(llvm::orc::LookupKind,\nstd::__1::vector<std::__1::pair<llvm::orc::JITDylib*,\nllvm::orc::JITDylibLookupFlags>,\nstd::__1::allocator<std::__1::pair<llvm::orc::JITDylib*,\nllvm::orc::JITDylibLookupFlags> > > const&,\nllvm::orc::SymbolLookupSet, llvm::orc::SymbolState,\nllvm::unique_function<void\n(llvm::Expected<llvm::DenseMap<llvm::orc::SymbolStringPtr,\nllvm::JITEvaluatedSymbol,\nllvm::DenseMapInfo<llvm::orc::SymbolStringPtr>,\nllvm::detail::DenseMapPair<llvm::orc::SymbolStringPtr,\nllvm::JITEvaluatedSy--Type <RET> for more, q to quit, c to continue\nwithout paging--\nmbol> > >)>, std::__1::function<void\n(llvm::DenseMap<llvm::orc::JITDylib*,\nllvm::DenseSet<llvm::orc::SymbolStringPtr,\nllvm::DenseMapInfo<llvm::orc::SymbolStringPtr> >,\nllvm::DenseMapInfo<llvm::orc::JITDylib*>,\nllvm::detail::DenseMapPair<llvm::orc::JITDylib*,\nllvm::DenseSet<llvm::orc::SymbolStringPtr,\nllvm::DenseMapInfo<llvm::orc::SymbolStringPtr> > > > const&)>) () from\n/usr/local/llvm12/lib/libLLVM-12.so\n#21 0x000000004ef09f8a in\nllvm::orc::ExecutionSession::lookup(std::__1::vector<std::__1::pair<llvm::orc::JITDylib*,\nllvm::orc::JITDylibLookupFlags>,\nstd::__1::allocator<std::__1::pair<llvm::orc::JITDylib*,\nllvm::orc::JITDylibLookupFlags> > > const&, llvm::orc::SymbolLookupSet\nconst&, llvm::orc::LookupKind, llvm::orc::SymbolState,\nstd::__1::function<void (llvm::DenseMap<llvm::orc::JITDylib*,\nllvm::DenseSet<llvm::orc::SymbolStringPtr,\nllvm::DenseMapInfo<llvm::orc::SymbolStringPtr> >,\nllvm::DenseMapInfo<llvm::orc::JITDylib*>,\nllvm::detail::DenseMapPair<llvm::orc::JITDylib*,\nllvm::DenseSet<llvm::orc::SymbolStringPtr,\nllvm::DenseMapInfo<llvm::orc::SymbolStringPtr> > > > const&)>) ()\n from /usr/local/llvm12/lib/libLLVM-12.so\n#22 0x000000004ef0a2ba in\nllvm::orc::ExecutionSession::lookup(std::__1::vector<std::__1::pair<llvm::orc::JITDylib*,\nllvm::orc::JITDylibLookupFlags>,\nstd::__1::allocator<std::__1::pair<llvm::orc::JITDylib*,\nllvm::orc::JITDylibLookupFlags> > > const&,\nllvm::orc::SymbolStringPtr, llvm::orc::SymbolState) () from\n/usr/local/llvm12/lib/libLLVM-12.so\n#23 0x000000004ef2b724 in\nllvm::orc::LLJIT::lookupLinkerMangled(llvm::orc::JITDylib&,\nllvm::orc::SymbolStringPtr) ()\n from /usr/local/llvm12/lib/libLLVM-12.so\n#24 0x000000004ef41364 in LLVMOrcLLJITLookup () from\n/usr/local/llvm12/lib/libLLVM-12.so\n#25 0x0000000041a67c06 in llvm_get_function (context=0x41f75530,\nfuncname=0x41ff8070 \"evalexpr_0_0\") at llvmjit.c:311\n#26 0x0000000041a73b9c in ExecRunCompiledExpr (state=0x41ff7770,\necontext=0x41ff7470, isNull=0x3fffffd5b7) at llvmjit_expr.c:2402\n#27 0x00000000004f70ea in ExecEvalExprSwitchContext (state=0x41ff7770,\necontext=0x41ff7470, isNull=0x3fffffd5b7)\n at ../../../src/include/executor/executor.h:339\n#28 ExecProject (projInfo=0x41ff7768) at\n../../../src/include/executor/executor.h:373\n#29 ExecResult (pstate=<optimized out>) at nodeResult.c:136\n#30 0x00000000004c90b0 in ExecProcNode (node=0x41ff7358) at\n../../../src/include/executor/executor.h:257\n#31 ExecutePlan (estate=0x41ff7120, planstate=0x41ff7358,\nuse_parallel_mode=<optimized out>, operation=<optimized out>,\n numberTuples=<optimized out>, direction=<optimized out>,\ndest=0x41ff5d80, execute_once=<optimized out>, sendTuples=<optimized\nout>)\n at execMain.c:1551\n#32 standard_ExecutorRun (queryDesc=0x41e9c520, direction=<optimized\nout>, count=<optimized out>, execute_once=<optimized out>)\n at execMain.c:361\n#33 0x000000000064e356 in PortalRunSelect (portal=0x41f24120,\nforward=<optimized out>, count=0, dest=<optimized out>) at\npquery.c:921\n#34 0x000000000064df50 in PortalRun (portal=0x41f24120,\ncount=9223372036854775807, isTopLevel=true, run_once=<optimized out>,\n dest=0x41ff5d80, altdest=0x41ff5d80, qc=0x3fffffd9b8) at pquery.c:765\n#35 0x000000000064d040 in exec_simple_query (query_string=0x41e1f120\n\"select 1 + 1;\") at postgres.c:1214\n#36 0x000000000064a674 in PostgresMain (dbname=<optimized out>,\nusername=<optimized out>) at postgres.c:4313\n#37 0x00000000005b62d6 in BackendRun (port=<optimized out>) at postmaster.c:4560\n#38 0x00000000005b5ab2 in BackendStartup (port=0x41ec2000) at postmaster.c:4288\n#39 ServerLoop () at postmaster.c:1801\n#40 0x00000000005b2fec in PostmasterMain (argc=3, argv=0x3fffffeac0)\nat postmaster.c:1473\n#41 0x000000000051d8ca in main (argc=3, argv=0x3fffffeac0) at main.c:198\n\n\n", "msg_date": "Thu, 4 Nov 2021 10:06:34 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "On Wed, Nov 3, 2021 at 11:55 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> 1. Even though we're using generic built-ins for atomics, I guess we\n> could still use a src/include/port/atomics/arch-riscv.h file so we\n> have a place to define PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY when\n> building for 64 bit. We'd need to find the chapter-and-verse to\n> justify that, of course, which I can try to do; if someone more\n> familiar with the ISA/spec/manual can point to it I'm all ears.\n\nI randomly remembered this topic after seeing an s390x announcement\nfrom Christoph[1], and figured he or someone else might be interested\nin the same observation about that platform. That is, we finally got\naround to defining this for ARM, but I bet one internet point that\nRISCV64 and s390x have that property too (but would need to find a\nwritten reference, or perhaps a similar declaration in the Linux\nsources, etc):\n\n$ git grep '#define PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY'\nsrc/include/port/atomics/arch-arm.h:#define PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY\nsrc/include/port/atomics/arch-ppc.h:#define PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY\nsrc/include/port/atomics/arch-x86.h:#define PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY\n\n[1] https://www.postgresql.org/about/news/postgresql-on-s390x-on-debian-and-ubuntu-2752/\n\n\n", "msg_date": "Thu, 30 Nov 2023 17:14:14 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" }, { "msg_contents": "Re: Thomas Munro\n> I randomly remembered this topic after seeing an s390x announcement\n> from Christoph[1], and figured he or someone else might be interested\n> in the same observation about that platform. That is, we finally got\n> around to defining this for ARM, but I bet one internet point that\n> RISCV64 and s390x have that property too (but would need to find a\n> written reference, or perhaps a similar declaration in the Linux\n> sources, etc):\n\nFwiw, while s390x is admittedly more of historical interest, riscv64\nis well on the way of becoming an official release architecture with\nthe next Debian stable release, so having it supported properly by\nPostgreSQL would be appreciated.\n\nChristoph\n\n\n", "msg_date": "Thu, 30 Nov 2023 12:45:43 +0100", "msg_from": "Christoph Berg <myon@debian.org>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Native spinlock support on RISC-V" } ]
[ { "msg_contents": "Hello,\n\nThe logging system already captures a lot of information in the ErrorData. But \nat present there is no way for a log message authors to include more metadata \nabout the log outside of the log message itself. For example, including the \nextension name which can be useful for filtering / dispatching log messages.\nThis can be done in the log message itself, but that requires specialized \nparsing in the log output. \n\nEven though among the available loggers in core, only the csv logger would be \nable to make sense of it, I feel it would be beneficial to add a tagging system \nto logs, by adding different (tag, value) combinations to a log entry, with an \nAPI similar to what we do for other ErrorData fields:\n\nereport(NOTICE,\n (errmsg(\"My log message\")),\n (errtag(\"EMITTER\", \"MYEXTENSION\")),\n (errtag(\"MSG-ID\", \"%d\", error_message_id))\n);\n\nPlease find attached a very small POC patch to better demonstrate what I \npropose. \n\nThird party logging hooks could then exploit those values to output them \ncorrectly. For example the json loggger written by Michael Paquier here: \nhttps://github.com/michaelpq/pg_plugins/tree/master/jsonlog, or the \nseeminlgy-abandonned journald hook here: https://github.com/intgr/pg_journal \ncould add those information in a structured way.\n\nI think the pgaudit extension (or something similar) could also make good use \nof such a feature instead of dumping a CSV entry in the log file. \n\nAs for Postgres own log messages, I'm sure we could find practical use cases \nfor tagging messages like this.\n\nOn a related note, the only structured logger we have in-core is the CSV \nlogger. Many users nowadays end up feeding the logs to journald either by \ncapturing the stderr output with systemd, or by having syslog implemented by \njournald itself. Would there be any interest in having native journald support \nas a logging_destination ?\n\nBest regards,\n\n-- \nRonan Dunklau", "msg_date": "Fri, 13 Aug 2021 15:23:03 +0200", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": true, "msg_subject": "Proposal: More structured logging" }, { "msg_contents": "On 2021-Aug-13, Ronan Dunklau wrote:\n\n> ereport(NOTICE,\n> (errmsg(\"My log message\")),\n> (errtag(\"EMITTER\", \"MYEXTENSION\")),\n> (errtag(\"MSG-ID\", \"%d\", error_message_id))\n> );\n\nInteresting idea. I agree this would be useful.\n\n> Please find attached a very small POC patch to better demonstrate what I \n> propose. \n\nSeems like a good start. I think a further step towards a committable\npatch would include a test module that uses the new tagging\nfunctionality.\n\n> On a related note, the only structured logger we have in-core is the CSV \n> logger. Many users nowadays end up feeding the logs to journald either by \n> capturing the stderr output with systemd, or by having syslog implemented by \n> journald itself. Would there be any interest in having native journald support \n> as a logging_destination ?\n\nI don't know anything about journald, but I agree that we sorely need\nsome better way to emit structured log entries.\n\n-- \nÁlvaro Herrera Valdivia, Chile — https://www.EnterpriseDB.com/\n\"The problem with the facetime model is not just that it's demoralizing, but\nthat the people pretending to work interrupt the ones actually working.\"\n (Paul Graham)\n\n\n", "msg_date": "Thu, 19 Aug 2021 09:04:30 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "On Thu, Aug 19, 2021 at 3:04 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>\n> On 2021-Aug-13, Ronan Dunklau wrote:\n>\n> > ereport(NOTICE,\n> > (errmsg(\"My log message\")),\n> > (errtag(\"EMITTER\", \"MYEXTENSION\")),\n> > (errtag(\"MSG-ID\", \"%d\", error_message_id))\n> > );\n>\n> Interesting idea. I agree this would be useful.\n>\n> > Please find attached a very small POC patch to better demonstrate what I\n> > propose.\n>\n> Seems like a good start. I think a further step towards a committable\n> patch would include a test module that uses the new tagging\n> functionality.\n>\n> > On a related note, the only structured logger we have in-core is the CSV\n> > logger. Many users nowadays end up feeding the logs to journald either by\n> > capturing the stderr output with systemd, or by having syslog implemented by\n> > journald itself. Would there be any interest in having native journald support\n> > as a logging_destination ?\n>\n> I don't know anything about journald, but I agree that we sorely need\n> some better way to emit structured log entries.\n\n+1. I think having the ability to natively send structured data to\njournald would be useful.\n\nAnother thing I've noticed in more and more other products is to be\nable to log as json, which is then later thrown into a central logging\nsystem somewhere. Basically like csv, but with the schema defined in\neach row. Yes, a lot more overhead, but some systems really do like to\nconsume json.... So when we're on the topic of more structured\nlogging...\n\n--\n Magnus Hagander\n Me: https://www.hagander.net/\n Work: https://www.redpill-linpro.com/\n\n\n", "msg_date": "Thu, 19 Aug 2021 16:14:25 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "On 2021-Aug-19, Magnus Hagander wrote:\n\n> Another thing I've noticed in more and more other products is to be\n> able to log as json, which is then later thrown into a central logging\n> system somewhere. Basically like csv, but with the schema defined in\n> each row. Yes, a lot more overhead, but some systems really do like to\n> consume json.... So when we're on the topic of more structured\n> logging...\n\nYeah, I was thinking in json logging too -- specifically thinking about\nFluentbit and similar tools.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\n\n", "msg_date": "Thu, 19 Aug 2021 10:50:10 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "Le jeudi 19 août 2021, 15:04:30 CEST Alvaro Herrera a écrit :\n> On 2021-Aug-13, Ronan Dunklau wrote:\n> > ereport(NOTICE,\n> > \n> > (errmsg(\"My log message\")),\n> > (errtag(\"EMITTER\", \"MYEXTENSION\")),\n> > (errtag(\"MSG-ID\", \"%d\", error_message_id))\n> > \n> > );\n> \n> Interesting idea. I agree this would be useful.\n> \n> > Please find attached a very small POC patch to better demonstrate what I\n> > propose.\n> \n> Seems like a good start. I think a further step towards a committable\n> patch would include a test module that uses the new tagging\n> functionality.\n\nPlease find attached the original patch + a new one adding a test module.\nThe test module exposes a function for generating logs with tags, and a log \nhook which format the tags in the DETAIL field for easy regression testing.\n\nNext step would be to emit those tags in the CSV logs. I'm not sure what \nrepresentation they should have though: a nested csv in it's own column ? A \nkey => value pairs list similar to hstore ? A json object ? \n\nAlso we should probably make this available to the client too, but once again \nthe format of the tag field needs to be defined. Any opinion ? \n\n\n\n-- \nRonan Dunklau", "msg_date": "Fri, 20 Aug 2021 11:31:21 +0200", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": true, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "Le jeudi 19 août 2021, 16:50:10 CEST Alvaro Herrera a écrit :\n> On 2021-Aug-19, Magnus Hagander wrote:\n> > Another thing I've noticed in more and more other products is to be\n> > able to log as json, which is then later thrown into a central logging\n> > system somewhere. Basically like csv, but with the schema defined in\n> > each row. Yes, a lot more overhead, but some systems really do like to\n> > consume json.... So when we're on the topic of more structured\n> > logging...\n> \n> Yeah, I was thinking in json logging too -- specifically thinking about\n> Fluentbit and similar tools.\n\nMichael, your jsonlog module already fullfills this need. Is it something that \nshould be merged into our tree ?\n\n-- \nRonan Dunklau\n\n\n\n\n", "msg_date": "Fri, 20 Aug 2021 11:35:29 +0200", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": true, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "On Fri, Aug 20, 2021 at 11:35:29AM +0200, Ronan Dunklau wrote:\n> Michael, your jsonlog module already fullfills this need. Is it something that \n> should be merged into our tree ?\n\nYes, there is nothing technically preventing to have this stuff in\ncore, of course, and that would even take care of the issues in\ndetecting if the piping protocol should be used or not.\n\nNow, the last time this was proposed, there was a lot of drawback\nbecause the presence of the JSON keys increases significantly the size\nof the logs compared to CSV, and usually users care a lot about the\nsize of the log files. I would support the presence of JSON format\nfor the logs in core, FWIW.\n\nThe module is here, for reference:\nhttps://github.com/michaelpq/pg_plugins/tree/master/jsonlog\n--\nMichael", "msg_date": "Sat, 21 Aug 2021 09:37:26 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "Le vendredi 20 août 2021, 11:31:21 CEST Ronan Dunklau a écrit :\n> Le jeudi 19 août 2021, 15:04:30 CEST Alvaro Herrera a écrit :\n> > On 2021-Aug-13, Ronan Dunklau wrote:\n> > > ereport(NOTICE,\n> > > \n> > > (errmsg(\"My log message\")),\n> > > (errtag(\"EMITTER\", \"MYEXTENSION\")),\n> > > (errtag(\"MSG-ID\", \"%d\", error_message_id))\n> > > \n> > > );\n> > \n> > Interesting idea. I agree this would be useful.\n> > \n> > > Please find attached a very small POC patch to better demonstrate what I\n> > > propose.\n> > \n> > Seems like a good start. I think a further step towards a committable\n> > patch would include a test module that uses the new tagging\n> > functionality.\n> \n> Please find attached the original patch + a new one adding a test module.\n> The test module exposes a function for generating logs with tags, and a log\n> hook which format the tags in the DETAIL field for easy regression testing.\n> \n> Next step would be to emit those tags in the CSV logs. I'm not sure what\n> representation they should have though: a nested csv in it's own column ? A\n> key => value pairs list similar to hstore ? A json object ?\n\nI opted for a JSON representation in the CSV logs, please find attached v3 \nwhich is the same thing as v2 with another patch for CSV log output.\n\n> \n> Also we should probably make this available to the client too, but once\n> again the format of the tag field needs to be defined. Any opinion ?\n\n\n-- \nRonan Dunklau", "msg_date": "Mon, 23 Aug 2021 08:58:50 +0200", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": true, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "On Sat, Aug 21, 2021 at 2:37 AM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> On Fri, Aug 20, 2021 at 11:35:29AM +0200, Ronan Dunklau wrote:\n> > Michael, your jsonlog module already fullfills this need. Is it something that\n> > should be merged into our tree ?\n>\n> Yes, there is nothing technically preventing to have this stuff in\n> core, of course, and that would even take care of the issues in\n> detecting if the piping protocol should be used or not.\n>\n> Now, the last time this was proposed, there was a lot of drawback\n> because the presence of the JSON keys increases significantly the size\n> of the logs compared to CSV, and usually users care a lot about the\n> size of the log files. I would support the presence of JSON format\n> for the logs in core, FWIW.\n\nAs long as it's optional, I don't think that drawback holds as an\nargument. The same argument could be made against the cvs logs in the\nfirst place -- they add information to every row that a lot of people\ndon't need. But it's optional. Leaving it up to the administrator to\nchoose whether they prefer the verbose-and-easier-to-parse-maybe\nformat or the more compact format seems like the right path for that.\nI bet quite a few would actually choose json -- easier to integrate\nwith other systems (because newer systems love json), and unless\nyou're actually logging a lot of queries (which many people don't),\nthe size of the logfile is often not a concern at all.\n\nIn short, I would also support the presence of JSON log format in\ncore. (but as a proper log_destination of course -- or if it's time to\nactually split that into a separaet thing, being one parameter for\nlog_destination and another for log_format)\n\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/\n Work: https://www.redpill-linpro.com/\n\n\n", "msg_date": "Mon, 23 Aug 2021 11:33:09 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "On Mon, Aug 23, 2021 at 11:33:09AM +0200, Magnus Hagander wrote:\n> As long as it's optional, I don't think that drawback holds as an\n> argument. The same argument could be made against the cvs logs in the\n> first place -- they add information to every row that a lot of people\n> don't need. But it's optional. Leaving it up to the administrator to\n> choose whether they prefer the verbose-and-easier-to-parse-maybe\n> format or the more compact format seems like the right path for that.\n\nFrom a code perspective, and while on it, we could split a bit elog.c\nand move the log entries generated for each format into their own\nfile. That would be cleaner for CSV and JSON. As a whole I don't\nhave an objection with moving the JSON format into core. If one\nproposes a patch, feel free to reuse the code from the module I have\nreleased.\n\n> I bet quite a few would actually choose json -- easier to integrate\n> with other systems (because newer systems love json), and unless\n> you're actually logging a lot of queries (which many people don't),\n> the size of the logfile is often not a concern at all.\n\nThe module I publish on github to do this work is the most popular\nthing of my plugin repo, FWIW. It even gets bug reports, sometimes.\n\n> In short, I would also support the presence of JSON log format in\n> core. (but as a proper log_destination of course -- or if it's time to\n> actually split that into a separaet thing, being one parameter for\n> log_destination and another for log_format)\n\nWhat would you gain with a new parameter here? I think that this\nwould be rather confusing and log_destination has been around for\nyears.\n--\nMichael", "msg_date": "Wed, 25 Aug 2021 08:21:43 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "On Tue, Aug 24, 2021 at 7:22 PM Michael Paquier <michael@paquier.xyz> wrote:\n\n> From a code perspective, and while on it, we could split a bit elog.c\n> and move the log entries generated for each format into their own\n> file. That would be cleaner for CSV and JSON. As a whole I don't\n> have an objection with moving the JSON format into core. If one\n> proposes a patch, feel free to reuse the code from the module I have\n> released.\n>\n\nI had a patch that does exactly this from a few years ago. It started off\ncopying a bunch out of your json logging module and adds it as a new\n\"jsonlog\" destination.\n\nIt needed some cleanup due to bit rot, but it now builds and works atop\nmaster. I'll post it in its own thread.\n\nRegards,\n-- Sehrope Sarkuni\nFounder & CEO | JackDB, Inc. | https://www.jackdb.com/\n\nOn Tue, Aug 24, 2021 at 7:22 PM Michael Paquier <michael@paquier.xyz> wrote:From a code perspective, and while on it, we could split a bit elog.c\nand move the log entries generated for each format into their own\nfile.  That would be cleaner for CSV and JSON.  As a whole I don't\nhave an objection with moving the JSON format into core.  If one\nproposes a patch, feel free to reuse the code from the module I have\nreleased.I had a patch that does exactly this from a few years ago. It started off copying a bunch out of your json logging module and adds it as a new \"jsonlog\" destination.It needed some cleanup due to bit rot, but it now builds and works atop master. I'll post it in its own thread.Regards,-- Sehrope SarkuniFounder & CEO | JackDB, Inc. | https://www.jackdb.com/", "msg_date": "Tue, 31 Aug 2021 10:46:30 -0400", "msg_from": "Sehrope Sarkuni <sehrope@jackdb.com>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "On Tue, Aug 31, 2021 at 10:46:30AM -0400, Sehrope Sarkuni wrote:\n> It needed some cleanup due to bit rot, but it now builds and works atop\n> master. I'll post it in its own thread.\n\nThanks.\n--\nMichael", "msg_date": "Wed, 1 Sep 2021 09:28:02 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "On 23.08.21 11:33, Magnus Hagander wrote:\n> In short, I would also support the presence of JSON log format in\n> core. (but as a proper log_destination of course -- or if it's time to\n> actually split that into a separaet thing, being one parameter for\n> log_destination and another for log_format)\n\nIt would be useful if there was some kind of standardized schema for \nJSON logging, meaning what the keys should be named etc. Then we don't \nneed to make this all up from scratch, and there could be some \nintegration with existing log analysis tools.\n\n\n", "msg_date": "Wed, 1 Sep 2021 09:35:19 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "On 13.08.21 15:23, Ronan Dunklau wrote:\n> The logging system already captures a lot of information in the ErrorData. But\n> at present there is no way for a log message authors to include more metadata\n> about the log outside of the log message itself. For example, including the\n> extension name which can be useful for filtering / dispatching log messages.\n> This can be done in the log message itself, but that requires specialized\n> parsing in the log output.\n> \n> Even though among the available loggers in core, only the csv logger would be\n> able to make sense of it, I feel it would be beneficial to add a tagging system\n> to logs, by adding different (tag, value) combinations to a log entry, with an\n> API similar to what we do for other ErrorData fields:\n> \n> ereport(NOTICE,\n> (errmsg(\"My log message\")),\n> (errtag(\"EMITTER\", \"MYEXTENSION\")),\n> (errtag(\"MSG-ID\", \"%d\", error_message_id))\n> );\n\nWhat are some more examples of where this could be used? The extension \nname could be added more or less automatically to ereport() calls. I \ndon't know what the MSG-ID is supposed to be. Are there other use cases?\n\n\n\n", "msg_date": "Wed, 1 Sep 2021 09:36:50 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "Le mercredi 1 septembre 2021, 09:36:50 CEST Peter Eisentraut a écrit :\n> On 13.08.21 15:23, Ronan Dunklau wrote:\n> > The logging system already captures a lot of information in the ErrorData.\n> > But at present there is no way for a log message authors to include more\n> > metadata about the log outside of the log message itself. For example,\n> > including the extension name which can be useful for filtering /\n> > dispatching log messages. This can be done in the log message itself, but\n> > that requires specialized parsing in the log output.\n> > \n> > Even though among the available loggers in core, only the csv logger would\n> > be able to make sense of it, I feel it would be beneficial to add a\n> > tagging system to logs, by adding different (tag, value) combinations to\n> > a log entry, with an API similar to what we do for other ErrorData\n> > fields:\n> > \n> > ereport(NOTICE,\n> > \n> > (errmsg(\"My log message\")),\n> > (errtag(\"EMITTER\", \"MYEXTENSION\")),\n> > (errtag(\"MSG-ID\", \"%d\", error_message_id))\n> > \n> > );\n> \n> What are some more examples of where this could be used? The extension\n> name could be added more or less automatically to ereport() calls. I\n> don't know what the MSG-ID is supposed to be. Are there other use cases?\n\nAdding it automatically would be nice, but how would you go about that ?\n\nIn-core it would open up the possibility to split log messages into different \nfields, for example the different statistics reported in the logs by VACUUM / \nANALYZE VERBOSE and make it easier to consume the output without having to \nparse the message. Parsing the message also means that any tool parsing it \nneeds to either be aware of the locale, or to force the user to use a specific \none.\n\nOut-of-core, the same things could be done for extensions like pg_audit which \nlogs structured information into the message itself, leaving the message \nformat to be parsed at a later time.\n\n-- \nRonan Dunklau\n\n\n\n\n", "msg_date": "Wed, 01 Sep 2021 10:00:28 +0200", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": true, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "On 01.09.21 10:00, Ronan Dunklau wrote:\n> In-core it would open up the possibility to split log messages into different\n> fields, for example the different statistics reported in the logs by VACUUM /\n> ANALYZE VERBOSE and make it easier to consume the output without having to\n> parse the message. Parsing the message also means that any tool parsing it\n> needs to either be aware of the locale, or to force the user to use a specific\n> one.\n\nI think those messages would themselves have substructure. For example, \nthe current message\n\n \"I/O timings: read: %.3f ms, write: %.3f ms\\n\"\n\nmight be\n\n {\"I/O timings\": {\"read\": ..., \"write\": ...}}\n\nand that in turn is already part of a larger message.\n\nSo just having a single level of tags wouldn't really work for this.\n\n\n", "msg_date": "Wed, 8 Sep 2021 11:51:31 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "Le mercredi 8 septembre 2021, 11:51:31 CEST Peter Eisentraut a écrit :\n> On 01.09.21 10:00, Ronan Dunklau wrote:\n> > In-core it would open up the possibility to split log messages into\n> > different fields, for example the different statistics reported in the\n> > logs by VACUUM / ANALYZE VERBOSE and make it easier to consume the output\n> > without having to parse the message. Parsing the message also means that\n> > any tool parsing it needs to either be aware of the locale, or to force\n> > the user to use a specific one.\n> \n> I think those messages would themselves have substructure. For example,\n> the current message\n> \n> \"I/O timings: read: %.3f ms, write: %.3f ms\\n\"\n> \n> might be\n> \n> {\"I/O timings\": {\"read\": ..., \"write\": ...}}\n> \n> and that in turn is already part of a larger message.\n> \n> So just having a single level of tags wouldn't really work for this.\n\nI agree having a nested structure may feel more natural, but I don't think it \nwould matter too much if we standardize on ini-style property names (ie, \niotimings.read, iotimings.write and so on...)\n\nRegards,\n\n-- \nRonan Dunklau\n\n\n\n\n", "msg_date": "Thu, 09 Sep 2021 11:15:36 +0200", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": true, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "> Subject: [PATCH v3 2/3] Add test module for the new tag functionality.\n...\n> +test_logging(PG_FUNCTION_ARGS)\n> +{\n...\n> +\t (errmsg(\"%s\", message),\n> +\t ({\n> +\t\tforboth(lk, keys, lv, values)\n> +\t\t{\n> +\t\t\t(errtag(lfirst(lk), \"%s\", (char *) lfirst(lv)));\n> +\t\t}})\n> +\t));\n\nThe windows build fails with that syntax.\nhttp://cfbot.cputube.org/ronan-dunklau.html\nhttps://ci.appveyor.com/project/postgresql-cfbot/postgresql/build/1.0.157923\n\n> Subject: [PATCH v3 3/3] Output error tags in CSV logs\n> +++ b/doc/src/sgml/config.sgml\n> @@ -7370,6 +7371,7 @@ CREATE TABLE postgres_log\n> backend_type text,\n> leader_pid integer,\n> query_id bigint,\n> + tags jsonb\n> PRIMARY KEY (session_id, session_line_num)\n> );\n> </programlisting>\n\nThat's invalid sql due to missing a trailing \",\".\n\nYou should also update file-fdw.sgml - which I only think of since we forgot in\nto update it before e568ed0eb and 0830d21f5. config.sgml should have a comment\nas a reminder to do that.\n\n-- \nJustin\n\n\n", "msg_date": "Wed, 29 Dec 2021 07:59:16 -0600", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "Le mercredi 29 décembre 2021, 14:59:16 CET Justin Pryzby a écrit :\n> > Subject: [PATCH v3 2/3] Add test module for the new tag functionality.\n> \n> ...\n> \n> > +test_logging(PG_FUNCTION_ARGS)\n> > +{\n> \n> ...\n> \n> > +\t (errmsg(\"%s\", message),\n> > +\t ({\n> > +\t\tforboth(lk, keys, lv, values)\n> > +\t\t{\n> > +\t\t\t(errtag(lfirst(lk), \"%s\", (char *) \nlfirst(lv)));\n> > +\t\t}})\n> > +\t));\n> \n> The windows build fails with that syntax.\n> http://cfbot.cputube.org/ronan-dunklau.html\n> https://ci.appveyor.com/project/postgresql-cfbot/postgresql/build/1.0.157923\n\nThank you. I switched to an explicit sequence of errstart / errfinish to avoid \nputting too much things in nested macro calls. As I don't have any Windows \nknowledge, I am very grateful for the new cirrus-ci integration which allowed \nme to build on Windows without hassle.\n\n> > Subject: [PATCH v3 3/3] Output error tags in CSV logs\n> > +++ b/doc/src/sgml/config.sgml\n> > @@ -7370,6 +7371,7 @@ CREATE TABLE postgres_log\n> > \n> > backend_type text,\n> > leader_pid integer,\n> > query_id bigint,\n> > \n> > + tags jsonb\n> > \n> > PRIMARY KEY (session_id, session_line_num)\n> > \n> > );\n> > </programlisting>\n> \n> That's invalid sql due to missing a trailing \",\".\n\nThanks, fixed.\n\n> \n> You should also update file-fdw.sgml - which I only think of since we forgot\n> in to update it before e568ed0eb and 0830d21f5. config.sgml should have a\n> comment as a reminder to do that.\n\nDone, and I added anoher commit per your suggestion to add this comment.\n\nThank you for this review.\n\nRegards,\n\n-- \nRonan Dunklau", "msg_date": "Tue, 11 Jan 2022 11:05:26 +0100", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": true, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "Hi,\n\nOn Tue, Jan 11, 2022 at 11:05:26AM +0100, Ronan Dunklau wrote:\n> \n> Done, and I added anoher commit per your suggestion to add this comment.\n\nThe cfbot reports that the patchset doesn't apply anymore:\n\nhttp://cfbot.cputube.org/patch_36_3293.log\n=== Applying patches on top of PostgreSQL commit ID 43c2175121c829c8591fc5117b725f1f22bfb670 ===\n[...]\n=== applying patch ./v4-0003-Output-error-tags-in-CSV-logs.patch\n[...]\npatching file src/backend/utils/error/elog.c\nHunk #2 FAILED at 3014.\n1 out of 2 hunks FAILED -- saving rejects to file src/backend/utils/error/elog.c.rej\n\nCould you send a rebased version? In the meantime I will switch the cf entry\nto Waiting on Author.\n\n\n", "msg_date": "Sat, 15 Jan 2022 14:09:59 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "Le samedi 15 janvier 2022, 07:09:59 CET Julien Rouhaud a écrit :\n> Hi,\n> \n> On Tue, Jan 11, 2022 at 11:05:26AM +0100, Ronan Dunklau wrote:\n> > Done, and I added anoher commit per your suggestion to add this comment.\n> \n> The cfbot reports that the patchset doesn't apply anymore:\n> \n> http://cfbot.cputube.org/patch_36_3293.log\n> === Applying patches on top of PostgreSQL commit ID\n> 43c2175121c829c8591fc5117b725f1f22bfb670 === [...]\n> === applying patch ./v4-0003-Output-error-tags-in-CSV-logs.patch\n> [...]\n> patching file src/backend/utils/error/elog.c\n> Hunk #2 FAILED at 3014.\n> 1 out of 2 hunks FAILED -- saving rejects to file\n> src/backend/utils/error/elog.c.rej\n> \n> Could you send a rebased version? In the meantime I will switch the cf\n> entry to Waiting on Author.\n\nThank you for this notification !\n\nThe csvlog has been refactored since I wrote the patch, and the new jsonlog \ndestination has been introduced. I rebased to fix the first patch, and added a \nnew patch to add support for tags in jsonlog output.\n\nBest regards,\n\n-- \nRonan Dunklau", "msg_date": "Mon, 17 Jan 2022 09:18:04 +0100", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": true, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "Le lundi 17 janvier 2022, 09:18:04 CET Ronan Dunklau a écrit :\n> Le samedi 15 janvier 2022, 07:09:59 CET Julien Rouhaud a écrit :\n> > Hi,\n> > \n> > On Tue, Jan 11, 2022 at 11:05:26AM +0100, Ronan Dunklau wrote:\n> > > Done, and I added anoher commit per your suggestion to add this comment.\n> > \n> > The cfbot reports that the patchset doesn't apply anymore:\n> > \n> > http://cfbot.cputube.org/patch_36_3293.log\n> > === Applying patches on top of PostgreSQL commit ID\n> > 43c2175121c829c8591fc5117b725f1f22bfb670 === [...]\n> > === applying patch ./v4-0003-Output-error-tags-in-CSV-logs.patch\n> > [...]\n> > patching file src/backend/utils/error/elog.c\n> > Hunk #2 FAILED at 3014.\n> > 1 out of 2 hunks FAILED -- saving rejects to file\n> > src/backend/utils/error/elog.c.rej\n> > \n> > Could you send a rebased version? In the meantime I will switch the cf\n> > entry to Waiting on Author.\n> \n> Thank you for this notification !\n> \n> The csvlog has been refactored since I wrote the patch, and the new jsonlog\n> destination has been introduced. I rebased to fix the first patch, and added\n> a new patch to add support for tags in jsonlog output.\n> \n> Best regards,\n\nHum, there was a missing import in csvlog.c from the fix above. Sorry about \nthat. \n\n\n-- \nRonan Dunklau", "msg_date": "Tue, 18 Jan 2022 06:46:03 +0100", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": true, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "On Tue, Jan 18, 2022 at 06:46:03AM +0100, Ronan Dunklau wrote:\n> Hum, there was a missing import in csvlog.c from the fix above. Sorry about \n> that. \n\n+<!-- Don't forget to also update file_fdw.sgml if you change this\ntable definition -->\n <programlisting>\n\nYou are also forgetting that the table listing all the jsonlog fields\nneeds a refresh with this new key called \"tags\", and that it has a\nJSON object underneath.\n\nIf you want to test all the formats supported by logging_destination,\nwouldn't this stuff be better if tested through TAP with\nlogging_destination set with csvlog, jsonlog and stderr? This is\nlacking coverage for csvlog.c and jsonlog.c, paths touched by your\npatch.\n--\nMichael", "msg_date": "Thu, 27 Jan 2022 16:15:01 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "Le jeudi 27 janvier 2022, 08:15:01 CET Michael Paquier a écrit :\n> On Tue, Jan 18, 2022 at 06:46:03AM +0100, Ronan Dunklau wrote:\n> > Hum, there was a missing import in csvlog.c from the fix above. Sorry\n> > about\n> > that.\n> \n> +<!-- Don't forget to also update file_fdw.sgml if you change this\n> table definition -->\n> <programlisting>\n> \n> You are also forgetting that the table listing all the jsonlog fields\n> needs a refresh with this new key called \"tags\", and that it has a\n> JSON object underneath.\n\nDone.\n\n> \n> If you want to test all the formats supported by logging_destination,\n> wouldn't this stuff be better if tested through TAP with\n> logging_destination set with csvlog, jsonlog and stderr? This is\n> lacking coverage for csvlog.c and jsonlog.c, paths touched by your\n> patch.\n\nDone, I also added coverage for log_verbosity = verbose while I was at it, \nand fixed a bug I introduced in csvlog while rebasing... \n\n-- \nRonan Dunklau", "msg_date": "Thu, 27 Jan 2022 14:58:37 +0100", "msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>", "msg_from_op": true, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "1) I would like an interface which more or less guarantees that\n*every* parameter of the log message is included in the structured\ndata. Ideally there should be no actual need to generate the formatted\nmessages for destinations like elastic search, just record the message\nid and the parameters.\n\nTo that end I would thing something like:\n\nereport(DEBUG2,\n(errmsg(\"table \\\"%s\\\": removed %lld dead item identifiers in %u pages\",\nvacrel->relname, (long long) index, vacuumed_pages)));\n\nWould end up like:\n\nereport(DEBUG2,\n(errmsg(\"table \\\"%s\\\": removed %lld dead item identifiers in %u pages\",\n errtag(\"relname\", vacrel->relname),\n errtag(\"dead_item_pointers\", (long long) index),\n errtag(\"vacuumed_pages\", vacuumed_pages))));\n\nAnd any untagged parameters could be included in the structured data\nwith unknown tag names. (Or perhaps some macro magic involving # but\nI'm not sure that would be possible with va_args.)\n\n2) I was kind of hoping we could have some sort of list of known tag\nlabels that could be used. So instead of an arbitrary string for the\nlabel name you just referenced the known labels. Then we could\ndocument that whenever \"relid\" appears as a tag id it's the oid of a\nrelation, for example.\n\nThis would help with things like \"search elastic search for all log\nentries for relid x, block p\". Which wouldn't work if block is\nsometimes \"page\" and sometimes \"blocknum\" and sometimes \"block\"....\n\nSo I was imagining something like\n\nerrtag(TAG_RELID, relid)\n\n\n3) When it comes to things like queryid it would be helpful to be able\nto inject tags from higher in the call stack so that invididual\nereport sites don't need to include it and we can decide to add new\nthings like it in the future. This will be useful for things like\ndistributed tracing tools who need to inject a span id into the every\nlog message.\n\nI imagine it could also be useful more generally. Application\ndevelopers might want to inject things like a pipeline identifier from\ntheir CI tools and then pull any logs with that identifier into their\nCI reports.\n\nYes, they could be added as new columns in CSV and top level json\nattributes but we may well have new tags that are not always there or\nare even created on user request. Or we may have cases where there can\nbe more than one active at a time.\n\n4) As far as code ... this is probably premature microoptimization but\nI do find the tags all being individually palloced and all going\nthrough string formatting seems like a lot of overhead. Like the\nactual number of errtag() calls in the ereport is always going to be\nthe same and the values are probably always going to be a single\nparameter, not really using the formatting functionality.\n\nI don't necessarily have a better alternative though. The only thing I\ncan think of isn't really any better:\n\nerrtag_str(RELNAME, relname)\nerrtag_int(RELID, relid)\n\n(possibly with some magic where there's an errtag() function that\nlooks up which data type to expect for a given tag id).\n\nIt looks strange to me that the errorTag struct has a \"const char\n*tagname\" but a \"char *tagvalue\". I think this is a side effect of the\ncode and not actually a sensible way to define the struct. Surely they\nshould both be const?\n\n\n", "msg_date": "Mon, 31 Jan 2022 17:46:29 -0500", "msg_from": "Greg Stark <stark@mit.edu>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" }, { "msg_contents": "On Mon, Jan 31, 2022 at 05:46:29PM -0500, Greg Stark wrote:\n> It looks strange to me that the errorTag struct has a \"const char\n> *tagname\" but a \"char *tagvalue\". I think this is a side effect of the\n> code and not actually a sensible way to define the struct. Surely they\n> should both be const?\n\nThis review has not been answered, and it was around for two months\nnow. I am marking this patch as returned with feedback.\n--\nMichael", "msg_date": "Thu, 7 Apr 2022 15:44:26 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Proposal: More structured logging" } ]
[ { "msg_contents": "Both bugs #16676[1] and #17141[2] illustrate that the combination of SKIP\nLOCKED and FETCH FIRST\nWITH TIES break expectations when it comes to rows returned to other\nsessions accessing the same\nrow. Since this situation is detectable from the syntax and hard to fix\notherwise, forbid for now,\nwith the potential to fix in the future.\n\n[1]\nhttps://www.postgresql.org/message-id/16676-fd62c3c835880da6%40postgresql.org\n[2]\nhttps://www.postgresql.org/message-id/17141-913d78b9675aac8e%40postgresql.org\n\nProposed backpatch to 13.", "msg_date": "Fri, 13 Aug 2021 11:16:18 -0500", "msg_from": "David Christensen <david.christensen@crunchydata.com>", "msg_from_op": true, "msg_subject": "[PATCH] Error out if SKIP LOCKED and WITH TIES are both specified" }, { "msg_contents": "On 2021-Aug-13, David Christensen wrote:\n\n> Both bugs #16676[1] and #17141[2] illustrate that the combination of\n> SKIP LOCKED and FETCH FIRST WITH TIES break expectations when it comes\n> to rows returned to other sessions accessing the same row. Since this\n> situation is detectable from the syntax and hard to fix otherwise,\n> forbid for now, with the potential to fix in the future.\n\nI think we should do this, given that it has show potential to bite\npeople. We should also add a small mentioned to this in the docs, as in\nthe attached.\n\nWhat do others think?\n\n-- \nÁlvaro Herrera Valdivia, Chile — https://www.EnterpriseDB.com/\n\"Escucha y olvidarás; ve y recordarás; haz y entenderás\" (Confucio)", "msg_date": "Mon, 30 Aug 2021 16:51:27 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Error out if SKIP LOCKED and WITH TIES are both specified" }, { "msg_contents": "On Mon, Aug 30, 2021 at 3:51 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>\n> On 2021-Aug-13, David Christensen wrote:\n>\n> > Both bugs #16676[1] and #17141[2] illustrate that the combination of\n> > SKIP LOCKED and FETCH FIRST WITH TIES break expectations when it comes\n> > to rows returned to other sessions accessing the same row. Since this\n> > situation is detectable from the syntax and hard to fix otherwise,\n> > forbid for now, with the potential to fix in the future.\n>\n> I think we should do this, given that it has show potential to bite\n> people. We should also add a small mentioned to this in the docs, as in\n> the attached.\n>\n> What do others think?\n\nThe patch I included had a doc mention in roughly the same place (at\nleast the same file), but I'm not tied to the wording I used (and I\nmay have missed more than one spot that might be appropriate). In any\ncase, +1.\n\nDavid\n\n\n", "msg_date": "Mon, 30 Aug 2021 15:55:10 -0500", "msg_from": "David Christensen <david.christensen@crunchydata.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Error out if SKIP LOCKED and WITH TIES are both specified" }, { "msg_contents": "On Mon, Aug 30, 2021 at 03:55:10PM -0500, David Christensen wrote:\n> On Mon, Aug 30, 2021 at 3:51 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>> I think we should do this, given that it has show potential to bite\n>> people. We should also add a small mentioned to this in the docs, as in\n>> the attached.\n>>\n>> What do others think?\n\nThere is a CF entry for this patch:\nhttps://commitfest.postgresql.org/34/3286/\n\nAlvaro, are you planning to wrap that?\n--\nMichael", "msg_date": "Fri, 1 Oct 2021 15:47:43 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Error out if SKIP LOCKED and WITH TIES are both specified" }, { "msg_contents": "On 2021-Oct-01, Michael Paquier wrote:\n\n> On Mon, Aug 30, 2021 at 03:55:10PM -0500, David Christensen wrote:\n> > On Mon, Aug 30, 2021 at 3:51 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> >> I think we should do this, given that it has show potential to bite\n> >> people. We should also add a small mentioned to this in the docs, as in\n> >> the attached.\n> >>\n> >> What do others think?\n> \n> There is a CF entry for this patch:\n> https://commitfest.postgresql.org/34/3286/\n> \n> Alvaro, are you planning to wrap that?\n\nI've had mixed feelings about this whole idea, but I think it's the\nright thing to do. I'll try to get it pushed today.\n\n-- \nÁlvaro Herrera Valdivia, Chile — https://www.EnterpriseDB.com/\n\"I can't go to a restaurant and order food because I keep looking at the\nfonts on the menu. Five minutes later I realize that it's also talking\nabout food\" (Donald Knuth)\n\n\n", "msg_date": "Fri, 1 Oct 2021 09:55:02 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Error out if SKIP LOCKED and WITH TIES are both specified" }, { "msg_contents": "On 2021-Aug-13, David Christensen wrote:\n\n> Both bugs #16676[1] and #17141[2] illustrate that the combination of\n> SKIP LOCKED and FETCH FIRST WITH TIES break expectations when it comes\n> to rows returned to other sessions accessing the same row. Since this\n> situation is detectable from the syntax and hard to fix otherwise,\n> forbid for now, with the potential to fix in the future.\n\nThank you, pushed with minimal adjustment.\n\n-- \nÁlvaro Herrera 39°49'30\"S 73°17'W — https://www.EnterpriseDB.com/\n\"Digital and video cameras have this adjustment and film cameras don't for the\nsame reason dogs and cats lick themselves: because they can.\" (Ken Rockwell)\n\n\n", "msg_date": "Fri, 1 Oct 2021 18:33:01 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Error out if SKIP LOCKED and WITH TIES are both specified" }, { "msg_contents": "On Fri, Oct 01, 2021 at 06:33:01PM -0300, Alvaro Herrera wrote:\n> On 2021-Aug-13, David Christensen wrote:\n> \n> > Both bugs #16676[1] and #17141[2] illustrate that the combination of\n> > SKIP LOCKED and FETCH FIRST WITH TIES break expectations when it comes\n> > to rows returned to other sessions accessing the same row. Since this\n> > situation is detectable from the syntax and hard to fix otherwise,\n> > forbid for now, with the potential to fix in the future.\n> \n> Thank you, pushed with minimal adjustment.\n> \n\nBTW, I just marked this one as committed in CF app\n\n-- \nJaime Casanova\nDirector de Servicios Profesionales\nSystemGuards - Consultores de PostgreSQL\n\n\n", "msg_date": "Sat, 2 Oct 2021 12:24:18 -0500", "msg_from": "Jaime Casanova <jcasanov@systemguards.com.ec>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Error out if SKIP LOCKED and WITH TIES are both specified" } ]
[ { "msg_contents": "created pg_buffercache extension:\nCREATE EXTENSION pg_buffercache;\n\nrestarted server and updated statistic for table :\nVACUUM ANALYZE public.my_table;\n\nthen just tried to cache table in buffer:\nSELECT * FROM public.my_table;\n\nand then tried to get table total page quantity and how much pages are\ncached in buffer for this table:\nSELECT\n(SELECT relpages FROM pg_class where oid = 'public.my_table'::regclass::oid\n) AS table_pages_quantity_total,\n(SELECT COUNT(DISTINCT relblocknumber) FROM pg_buffercache WHERE\nrelfilenode = (\nSELECT relfilenode FROM pg_class WHERE oid =\n'public.my_table'::regclass::oid -- (SELECT rel_oid FROM my_cte)\n) ) AS table_pages_quantity_in_cache;\n\n\n This shows that table have only one page, while second column shows 3\nunique pages in buffer cache. Seems I'm measuring those numbers\nincorrectly(?) can you please help, which column is incorrect (or may be\nboth) ?\n\ncreated pg_buffercache extension:CREATE EXTENSION pg_buffercache;restarted server and updated statistic for table :VACUUM ANALYZE public.my_table;then just tried to cache table in buffer:SELECT * FROM public.my_table;and then tried to get table total page quantity and how much pages are cached in buffer for this table:SELECT (SELECT relpages FROM pg_class where oid = 'public.my_table'::regclass::oid ) AS table_pages_quantity_total,(SELECT COUNT(DISTINCT relblocknumber) FROM pg_buffercache WHERE relfilenode = (\tSELECT relfilenode FROM pg_class WHERE oid = 'public.my_table'::regclass::oid -- (SELECT rel_oid FROM my_cte) ) ) AS table_pages_quantity_in_cache; This shows that table have only one page, while second column shows 3 unique pages in buffer cache. Seems I'm measuring those numbers incorrectly(?) can you please help, which column is incorrect (or may be both) ?", "msg_date": "Sun, 15 Aug 2021 15:41:31 +0400", "msg_from": "otar shavadze <oshavadze@gmail.com>", "msg_from_op": true, "msg_subject": "Get table total page quantity and cached page quantity" }, { "msg_contents": "On Sun, 15 Aug 2021 at 23:41, otar shavadze <oshavadze@gmail.com> wrote:\n> SELECT\n> (SELECT relpages FROM pg_class where oid = 'public.my_table'::regclass::oid ) AS table_pages_quantity_total,\n> (SELECT COUNT(DISTINCT relblocknumber) FROM pg_buffercache WHERE relfilenode = (\n> SELECT relfilenode FROM pg_class WHERE oid = 'public.my_table'::regclass::oid -- (SELECT rel_oid FROM my_cte)\n> ) ) AS table_pages_quantity_in_cache;\n>\n> This shows that table have only one page, while second column shows 3 unique pages in buffer cache. Seems I'm measuring those numbers incorrectly(?) can you please help, which column is incorrect (or may be both) ?\n\nThis question likely is more suited to the pgsql-general mailing list.\nMy answer in [1] likely will clear this up for you.\n\nIf you need further information, please ask on that thread.\n\nDavid\n\n[1] https://www.postgresql.org/message-id/CAApHDvpHddfoZOviYXiz2dCr9emrrbnJ7n3HkS8KNsD9W1wscA@mail.gmail.com\n\n\n", "msg_date": "Mon, 16 Aug 2021 08:31:37 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Get table total page quantity and cached page quantity" }, { "msg_contents": "Answer is pretty clear, thank you David.\n\nOn Mon, Aug 16, 2021 at 12:31 AM David Rowley <dgrowleyml@gmail.com> wrote:\n\n> On Sun, 15 Aug 2021 at 23:41, otar shavadze <oshavadze@gmail.com> wrote:\n> > SELECT\n> > (SELECT relpages FROM pg_class where oid =\n> 'public.my_table'::regclass::oid ) AS table_pages_quantity_total,\n> > (SELECT COUNT(DISTINCT relblocknumber) FROM pg_buffercache WHERE\n> relfilenode = (\n> > SELECT relfilenode FROM pg_class WHERE oid =\n> 'public.my_table'::regclass::oid -- (SELECT rel_oid FROM my_cte)\n> > ) ) AS table_pages_quantity_in_cache;\n> >\n> > This shows that table have only one page, while second column shows 3\n> unique pages in buffer cache. Seems I'm measuring those numbers\n> incorrectly(?) can you please help, which column is incorrect (or may be\n> both) ?\n>\n> This question likely is more suited to the pgsql-general mailing list.\n> My answer in [1] likely will clear this up for you.\n>\n> If you need further information, please ask on that thread.\n>\n> David\n>\n> [1]\n> https://www.postgresql.org/message-id/CAApHDvpHddfoZOviYXiz2dCr9emrrbnJ7n3HkS8KNsD9W1wscA@mail.gmail.com\n>\n\nAnswer is pretty clear, thank you David.On Mon, Aug 16, 2021 at 12:31 AM David Rowley <dgrowleyml@gmail.com> wrote:On Sun, 15 Aug 2021 at 23:41, otar shavadze <oshavadze@gmail.com> wrote:\n> SELECT\n> (SELECT relpages FROM pg_class where oid = 'public.my_table'::regclass::oid ) AS table_pages_quantity_total,\n> (SELECT COUNT(DISTINCT relblocknumber) FROM pg_buffercache WHERE relfilenode = (\n> SELECT relfilenode FROM pg_class WHERE oid = 'public.my_table'::regclass::oid -- (SELECT rel_oid FROM my_cte)\n> ) ) AS table_pages_quantity_in_cache;\n>\n>  This shows that table have only one page, while second column shows 3 unique pages in buffer cache. Seems I'm measuring those numbers incorrectly(?) can you please help, which column is incorrect (or may be both) ?\n\nThis question likely is more suited to the pgsql-general mailing list.\nMy answer in [1] likely will clear this up for you.\n\nIf you need further information, please ask on that thread.\n\nDavid\n\n[1] https://www.postgresql.org/message-id/CAApHDvpHddfoZOviYXiz2dCr9emrrbnJ7n3HkS8KNsD9W1wscA@mail.gmail.com", "msg_date": "Mon, 16 Aug 2021 00:52:45 +0400", "msg_from": "otar shavadze <oshavadze@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Get table total page quantity and cached page quantity" } ]
[ { "msg_contents": "During some development on encoding-related parts of postgres I stumbled over the new length-checking-code in common/hex.c/pg_hex_encode.\n\nDifferently when comparing it to all versions before the output-buffer-length is checked during encoding of every individual source byte.\n\nThis may impose quite a regression when using pg_dump on databases with many/big bytea or lo columns.\n\nBecause all criteria to check buffer-length are known in advance of encoding (srclen and destlen) I propose doing the check only once before starting the while-loop.\n\nPlease find the attached patch for pg14 and master, older versions did not have this behavior.\n\nTested on pg14-beta3, but applies also on master.\n\nPS: This is my very first patch, I am in no way an experienced C-developer and don't have a smoothly running development environment or experience yet. (originally mostly dealing with postgres on Windows).\n\nIf it seems useful somebody could enter it as an open item / resolved item for pg14 after beta 3.\n\nThanks for looking!\n\nHans Buschmann", "msg_date": "Sun, 15 Aug 2021 14:58:59 +0000", "msg_from": "Hans Buschmann <buschmann@nidsa.net>", "msg_from_op": true, "msg_subject": "PG14: Avoid checking output-buffer-length for every encoded byte\n during pg_hex_encode" }, { "msg_contents": "Welcome.\nEm seg., 16 de ago. de 2021 às 05:46, Hans Buschmann <buschmann@nidsa.net>\nescreveu:\n\n> During some development on encoding-related parts of postgres I stumbled\n> over the new length-checking-code in common/hex.c/pg_hex_encode.\n>\n> Differently when comparing it to all versions before the\n> output-buffer-length is checked during encoding of every individual source\n> byte.\n>\nIs always good to remove immutables from loops, if safe and secure.\n\n\n> This may impose quite a regression when using pg_dump on databases with\n> many/big bytea or lo columns.\n>\nDecode has regression too.\n\n\n> Because all criteria to check buffer-length are known in advance of\n> encoding (srclen and destlen) I propose doing the check only once before\n> starting the while-loop.\n>\nGood.\n\n\n>\n> Please find the attached patch for pg14 and master, older versions did not\n> have this behavior.\n>\nI think that we can take one more step here.\npg_hex_decode can be improved too.\nWe can remove limitations from all functions that use hex functions.\nbyteaout from (varlena.c) has an artificial limitation to handle only\nMaxAllocSize length, but\nnothing prevents her from being prepared for that limitation to be removed\none day.\n\n\n> Tested on pg14-beta3, but applies also on master.\n>\n> PS: This is my very first patch, I am in no way an experienced C-developer\n> and don't have a smoothly running development environment or experience\n> yet. (originally mostly dealing with postgres on Windows).\n>\nIt seems good to me.\n\nPlease, take a look at the new version attached.\nIf possible can you review the tests if there is an overflow at\npg_hex_encode and pg_hex_decode functions?\n\nregards,\nRanier Vilela", "msg_date": "Mon, 16 Aug 2021 12:04:54 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: PG14: Avoid checking output-buffer-length for every encoded byte\n during pg_hex_encode" }, { "msg_contents": "________________________________\nVon: Ranier Vilela <ranier.vf@gmail.com>\nGesendet: Montag, 16. August 2021 17:04\nAn: Hans Buschmann\nCc: pgsql-hackers@postgresql.org\nBetreff: Re: PG14: Avoid checking output-buffer-length for every encoded byte during pg_hex_encode\n\nHello Ranier,\n\nThank you for your quick response.\n\n>Is always good to remove immutables from loops, if safe and secure.\n\nI think it's worse because a loop changed variable is involved in the test, so it seems to be not immutable.\n\n>Decode has regression too.\n\ngood catch, I overlooked it.\n\n>I think that we can take one more step here.\n>pg_hex_decode can be improved too.\n\n+1\n\nBy looking a bit more precisely I detected the same checks in common/base64.c also involving loop-changed variables. Could you please make the same changes to base64.c?\n\n\n>We can remove limitations from all functions that use hex functions.\n>byteaout from (varlena.c) has an artificial limitation to handle only MaxAllocSize length, but\n>nothing prevents her from being prepared for that limitation to be removed one day.\n\n+1, but I don't know all implications of the type change to size_t\n\n>Please, take a look at the new version attached.\n\nTwo remarks for decoding (by eyeball inspection of patch file only because of still struggling with git etc.):\n\n1. The odd-number-of-digits-check for decoding is still part of the loop. It should be before the loop and called only once (by testing for an even number of srclen)\nSo we can eliminate the block if (s == srcend)? {} inside the loop!\n\n2. I noticed that the error messages for hex_decode should be changed as\n\ns/encoding/decoding/\n\n(as in pg_log_fatal(\"overflow of destination buffer in hex encoding\");)\n\n>If possible can you review the tests if there is an overflow at\n>pg_hex_encode and pg_hex_decode functions?\n\nI would prefer to wait for another patch version from you (my development troubles), perhaps also dealing with base64.c\n\nI don't know how and where any call to the encoding/decoding functions creates an overflow situation in normal operation.\n\nI will nonceless try the tests but I don't have any experience with it.\n\nBTW the root cause for my work is an attempt to vastly accelerate these functions (hex and base64 encode/decode), but this is left for another day (not finished yet) and certainly only on master/new development.\n\nLateron support on this topic would be highly appreciated...\n\nBest regards,\nHans Buschmann\n\n\n\n\n\n\n\n\n\n\n\n\nVon: Ranier Vilela <ranier.vf@gmail.com>\nGesendet: Montag, 16. August 2021 17:04\nAn: Hans Buschmann\nCc: pgsql-hackers@postgresql.org\nBetreff: Re: PG14: Avoid checking output-buffer-length for every encoded byte during pg_hex_encode\n \n\nHello Ranier,\n\n\n\nThank you for your quick response.\n\n\n\n\n\n\n\n\n>Is always good to remove immutables from loops, if safe and secure.\n\n\n\n\n\nI think it's  worse because a loop changed variable is involved in the test, so it seems to be not immutable.\n\n\n\n>Decode has regression too.\n\n\ngood catch, I overlooked it.\n\n\n\n\n\n>I think that we can take one more step here.\n>pg_hex_decode can be improved too.\n\n\n\n+1\n\n\n\n\n\nBy looking a bit more precisely I detected the same checks in common/base64.c also involving loop-changed variables. Could you please make the same changes to base64.c?\n\n\n\n\n\n\n>We can remove limitations from all functions that use hex functions.\n>byteaout from (varlena.c) has an artificial limitation to handle only MaxAllocSize length, but\n>nothing prevents her from being prepared for that limitation to be removed one day.\n\n\n+1, but I don't know all implications of the type change to size_t\n\n\n\n\n>Please, take a look at the new version attached.\n\n\n\nTwo remarks for decoding (by eyeball inspection of patch file only because of still struggling\n with git etc.):\n\n\n1. The odd-number-of-digits-check for decoding is still part of the loop. It should be before the loop and called only once (by testing for an even number of srclen)\nSo we can eliminate the block if (s == srcend)​ {} inside the loop!\n\n\n\n\n2. I noticed that the error messages for hex_decode should be changed as \n\n\ns/encoding/decoding/\n\n\n(as in pg_log_fatal(\"overflow of destination buffer in hex encoding\");)\n\n\n\n>If possible can you review the tests if there is an overflow at\n>pg_hex_encode and pg_hex_decode functions?\n\n\nI would prefer to wait for another patch version from you (my development troubles), perhaps also dealing with base64.c\n\n\n\nI don't know how and where any call to the encoding/decoding functions creates an overflow situation in normal operation.\n\n\n\nI  will nonceless try the tests but I don't have any experience with it.\n\n\n\nBTW the root cause for my work is an attempt to vastly accelerate these functions (hex and base64 encode/decode), but this is left for another day (not finished yet) and certainly only on master/new development.\n\n\n\nLateron support on this topic would be highly appreciated...\n\n\n\nBest regards,\nHans Buschmann", "msg_date": "Mon, 16 Aug 2021 16:19:39 +0000", "msg_from": "Hans Buschmann <buschmann@nidsa.net>", "msg_from_op": true, "msg_subject": "AW: PG14: Avoid checking output-buffer-length for every encoded byte\n during pg_hex_encode" }, { "msg_contents": "Em seg., 16 de ago. de 2021 às 13:19, Hans Buschmann <buschmann@nidsa.net>\nescreveu:\n\n> ------------------------------\n> *Von:* Ranier Vilela <ranier.vf@gmail.com>\n> *Gesendet:* Montag, 16. August 2021 17:04\n> *An:* Hans Buschmann\n> *Cc:* pgsql-hackers@postgresql.org\n> *Betreff:* Re: PG14: Avoid checking output-buffer-length for every\n> encoded byte during pg_hex_encode\n>\n> Hello Ranier,\n>\n> Thank you for your quick response.\n>\n> >Is always good to remove immutables from loops, if safe and secure.\n>\n> I think it's worse because a loop changed variable is involved in the\n> test, so it seems to be not immutable.\n>\n> >Decode has regression too.\n>\n> good catch, I overlooked it.\n>\n> >I think that we can take one more step here.\n> >pg_hex_decode can be improved too.\n>\n> +1\n>\n> By looking a bit more precisely I detected the same checks in\n> common/base64.c also involving loop-changed variables. Could you please\n> make the same changes to base64.c?\n>\nI will take a look.\n\n\n>\n> >We can remove limitations from all functions that use hex functions.\n> >byteaout from (varlena.c) has an artificial limitation to handle only\n> MaxAllocSize length, but\n> >nothing prevents her from being prepared for that limitation to be\n> removed one day.\n>\n> +1, but I don't know all implications of the type change to size_t\n>\nuint64 and size_t in 64 bits are equivalents.\nuint64 and size_t in 32 bits can be weird, but anyway size_t at 32 bits can\nhandle 1GB.\n\n\n>\n> >Please, take a look at the new version attached.\n>\n> Two remarks for decoding (by eyeball inspection of patch file only\n> because of still struggling with git etc.):\n>\n> 1. The odd-number-of-digits-check for decoding is still part of the loop.\n> It should be before the loop and called only once (by testing for an even\n> number of srclen)\n> So we can eliminate the block if (s == srcend) {} inside the loop!\n>\nI'm afraid that is not possible.\nI tested some variations for this test and regress fails at strings tests.\nAnyway for test purposes, I changed it temporarily in this version, but I'm\nafraid we'll have to go back.\n\n\n> 2. I noticed that the error messages for hex_decode should be changed as\n>\n> s/encoding/decoding/\n>\n> (as in pg_log_fatal(\"overflow of destination buffer in hex encoding\");)\n>\nOk. Changed.\n\n\n> >If possible can you review the tests if there is an overflow at\n> >pg_hex_encode and pg_hex_decode functions?\n>\n> I would prefer to wait for another patch version from you (my development\n> troubles), perhaps also dealing with base64.c\n>\nbase64.c can be made in another patch.\n\n\n> I don't know how and where any call to the encoding/decoding functions\n> creates an overflow situation in normal operation.\n>\n\n> I will nonceless try the tests but I don't have any experience with it.\n>\nThanks.\n\n\n> BTW the root cause for my work is an attempt to vastly accelerate these\n> functions (hex and base64 encode/decode), but this is left for another day\n> (not finished yet) and certainly only on master/new development.\n>\nI think this can speed up a little.\n\n\n> Lateron support on this topic would be highly appreciated...\n>\nIf I can help, count on me.\n\nregards,\nRanier Vilela", "msg_date": "Mon, 16 Aug 2021 14:06:31 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: PG14: Avoid checking output-buffer-length for every encoded byte\n during pg_hex_encode" }, { "msg_contents": "On Sun, Aug 15, 2021 at 02:58:59PM +0000, Hans Buschmann wrote:\n> If it seems useful somebody could enter it as an open item /\n> resolved item for pg14 after beta 3.\n\nHmm. Using SQLs like the following to stress pg_hex_encode(), I can\nsee a measurable difference easily, so no need of pg_dump or an\ninstance with many LOs:\nset work_mem = '1GB';\nwith hex_values as materialized\n (select repeat(i::text, N)::bytea as i\n from generate_series(1, M) t(i))\n SELECT count(encode(i, 'hex')) from hex_values;\n\nWith N = 1000, M = 100000, perf shows a 34.88% use of pg_hex_encode().\nOn REL_13_STABLE, I get down ~27% for hex_encode(), the same backend\nroutine.\n\nThe runtime numbers are more interesting, HEAD gets up to 1600ms.\nWith the latest version of the patch, we get down to 1550ms. Now, a\nsimple revert of ccf4e277 and aef8948 brings me down to the same\nruntimes as ~13, closer to 1450ms. There seem to be some noise in the\ntests, but the difference is clear.\n\nConsidering that commit aef8948 also involved a cleanup of\nsrc/common/hex_decode.c, I think that it would be saner to also revert\nc3826f83, so as we have a clean state of the code to work on should\nthe work on the data encryption patch set move on in the future. It\nis not decided that this would actually use any of the hex\ndecode/encode code, either.\n\nHonestly, I don't like much messing with this stuff after beta3, and\none of the motives of moving the hex handling code to src/common/ was\nfor the data encryption code whose state is not known as of late.\nThis does not prevent working on such refactorings in the future, of\ncourse, keeping the performance impact in mind.\n\nIn short, I am planning to address this regression with the attached,\nfor a combined revert of 0d70d30, 5c33ba5 and 92436a7.\n--\nMichael", "msg_date": "Tue, 17 Aug 2021 11:00:47 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: PG14: Avoid checking output-buffer-length for every encoded byte\n during pg_hex_encode" }, { "msg_contents": "On Mon, Aug 16, 2021 at 02:06:31PM -0300, Ranier Vilela wrote:\n> uint64 and size_t in 64 bits are equivalents.\n> uint64 and size_t in 32 bits can be weird, but anyway size_t at 32 bits can\n> handle 1GB.\n\nThere is usually a reason why things are done as they are, so before\nsuggesting changing something I would advise to read the threads that\ncreated those changes more carefully because they could be mentioned.\nIn this case, we are talking about aef8948, and this part of its\nrelated thread:\nhttps://www.postgresql.org/message-id/20210105034739.GG7432@momjian.us\n\n> base64.c can be made in another patch.\n\nThis file is a set of code paths used by authentication and SCRAM, it\nwill never get as hot as the code paths that Hans has reported as\nthese are one-time operations. Please note as well cfc40d3 for the\nreasons why things are handled this way. We absolutely have to use\nsafe routines here.\n--\nMichael", "msg_date": "Tue, 17 Aug 2021 12:43:13 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: PG14: Avoid checking output-buffer-length for every encoded byte\n during pg_hex_encode" }, { "msg_contents": "Em ter., 17 de ago. de 2021 às 00:43, Michael Paquier <michael@paquier.xyz>\nescreveu:\n\n> On Mon, Aug 16, 2021 at 02:06:31PM -0300, Ranier Vilela wrote:\n> > uint64 and size_t in 64 bits are equivalents.\n> > uint64 and size_t in 32 bits can be weird, but anyway size_t at 32 bits\n> can\n> > handle 1GB.\n>\n> There is usually a reason why things are done as they are, so before\n> suggesting changing something I would advise to read the threads that\n> created those changes more carefully because they could be mentioned.\n> In this case, we are talking about aef8948, and this part of its\n> related thread:\n> https://www.postgresql.org/message-id/20210105034739.GG7432@momjian.us\n\nBecause things have always been done a certain way doesn't mean it's right.\nUsing int to address strings is an mistake.\nEven with an artificial limitation to only deal with 1GB, the correct one\nto use would be size_t.\n\n\n>\n> > base64.c can be made in another patch.\n>\n> This file is a set of code paths used by authentication and SCRAM, it\n> will never get as hot as the code paths that Hans has reported as\n> these are one-time operations. Please note as well cfc40d3 for the\n> reasons why things are handled this way. We absolutely have to use\n> safe routines here.\n>\nI have no plans to touch base64.c\n\nregards,\nRanier Vilela\n\nEm ter., 17 de ago. de 2021 às 00:43, Michael Paquier <michael@paquier.xyz> escreveu:On Mon, Aug 16, 2021 at 02:06:31PM -0300, Ranier Vilela wrote:\n> uint64 and size_t in 64 bits are equivalents.\n> uint64 and size_t in 32 bits can be weird, but anyway size_t at 32 bits can\n> handle 1GB.\n\nThere is usually a reason why things are done as they are, so before\nsuggesting changing something I would advise to read the threads that\ncreated those changes more carefully because they could be mentioned.\nIn this case, we are talking about aef8948, and this part of its\nrelated thread:\nhttps://www.postgresql.org/message-id/20210105034739.GG7432@momjian.usBecause things have always been done a certain way doesn't mean it's right.Using int to address strings is an mistake.Even with an artificial limitation to only deal with 1GB, the correct one to use would be size_t.\n\n> base64.c can be made in another patch.\n\nThis file is a set of code paths used by authentication and SCRAM, it\nwill never get as hot as the code paths that Hans has reported as\nthese are one-time operations.  Please note as well cfc40d3 for the\nreasons why things are handled this way.  We absolutely have to use\nsafe routines here.I have no plans to touch base64.c regards,Ranier Vilela", "msg_date": "Tue, 17 Aug 2021 08:00:08 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: PG14: Avoid checking output-buffer-length for every encoded byte\n during pg_hex_encode" }, { "msg_contents": "Michael Paquier <michael@paquier.xyz> writes:\n> In short, I am planning to address this regression with the attached,\n> for a combined revert of 0d70d30, 5c33ba5 and 92436a7.\n\nOK, but the commit message should explain why they're getting reverted.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 17 Aug 2021 09:39:30 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: PG14: Avoid checking output-buffer-length for every encoded byte\n during pg_hex_encode" }, { "msg_contents": "On Tue, Aug 17, 2021 at 09:39:30AM -0400, Tom Lane wrote:\n> Michael Paquier <michael@paquier.xyz> writes:\n> > In short, I am planning to address this regression with the attached,\n> > for a combined revert of 0d70d30, 5c33ba5 and 92436a7.\n> \n> OK, but the commit message should explain why they're getting reverted.\n\nUh, I don't see those commits, e.g.:\n\n\t$ git diff 0d70d30\n\tfatal: ambiguous argument '0d70d30': unknown revision or path not in the working tree.\n\tUse '--' to separate paths from revisions, like this:\n\t'git <command> [<revision>...] -- [<file>...]'\n\n\t$ git diff 5c33ba5\n\tfatal: ambiguous argument '5c33ba5': unknown revision or path not in the working tree.\n\tUse '--' to separate paths from revisions, like this:\n\t'git <command> [<revision>...] -- [<file>...]'\n\t\n\t$ git diff 92436a7\n\tfatal: ambiguous argument '92436a7': unknown revision or path not in the working tree.\n\tUse '--' to separate paths from revisions, like this:\n\t'git <command> [<revision>...] -- [<file>...]'\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Tue, 17 Aug 2021 11:26:29 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: PG14: Avoid checking output-buffer-length for every encoded byte\n during pg_hex_encode" }, { "msg_contents": "On Tue, Aug 17, 2021 at 11:26 PM Bruce Momjian <bruce@momjian.us> wrote:\n>\n> On Tue, Aug 17, 2021 at 09:39:30AM -0400, Tom Lane wrote:\n> > Michael Paquier <michael@paquier.xyz> writes:\n> > > In short, I am planning to address this regression with the attached,\n> > > for a combined revert of 0d70d30, 5c33ba5 and 92436a7.\n> >\n> > OK, but the commit message should explain why they're getting reverted.\n>\n> Uh, I don't see those commits, e.g.:\n>\n> $ git diff 0d70d30\n> fatal: ambiguous argument '0d70d30': unknown revision or path not in the working tree.\n> Use '--' to separate paths from revisions, like this:\n> 'git <command> [<revision>...] -- [<file>...]'\n>\n> $ git diff 5c33ba5\n> fatal: ambiguous argument '5c33ba5': unknown revision or path not in the working tree.\n> Use '--' to separate paths from revisions, like this:\n> 'git <command> [<revision>...] -- [<file>...]'\n>\n> $ git diff 92436a7\n> fatal: ambiguous argument '92436a7': unknown revision or path not in the working tree.\n> Use '--' to separate paths from revisions, like this:\n> 'git <command> [<revision>...] -- [<file>...]'\n\nSame here. I'm assuming that the real commits are the one mentioned\nin the patch, which are c3826f8, aef8948 and ccf4e27.\n\n\n", "msg_date": "Wed, 18 Aug 2021 00:34:45 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: PG14: Avoid checking output-buffer-length for every encoded byte\n during pg_hex_encode" }, { "msg_contents": "On Wed, Aug 18, 2021 at 12:34:45AM +0800, Julien Rouhaud wrote:\n> On Tue, Aug 17, 2021 at 11:26 PM Bruce Momjian <bruce@momjian.us> wrote:\n>> Uh, I don't see those commits, e.g.:\n>>\n>> $ git diff 0d70d30\n>> fatal: ambiguous argument '0d70d30': unknown revision or path not in the working tree.\n>> Use '--' to separate paths from revisions, like this:\n>> 'git <command> [<revision>...] -- [<file>...]'\n>>\n>> $ git diff 5c33ba5\n>> fatal: ambiguous argument '5c33ba5': unknown revision or path not in the working tree.\n>> Use '--' to separate paths from revisions, like this:\n>> 'git <command> [<revision>...] -- [<file>...]'\n>>\n>> $ git diff 92436a7\n>> fatal: ambiguous argument '92436a7': unknown revision or path not in the working tree.\n>> Use '--' to separate paths from revisions, like this:\n>> 'git <command> [<revision>...] -- [<file>...]'\n> \n> Same here. I'm assuming that the real commits are the one mentioned\n> in the patch, which are c3826f8, aef8948 and ccf4e27.\n\nOops, incorrect copy-paste from my side. Yes, the commits impacted\nhere are aef8948, ccf4e27 and c3826f8. The small-ish commit message\nof the patch got thet right.\n--\nMichael", "msg_date": "Wed, 18 Aug 2021 09:10:16 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: PG14: Avoid checking output-buffer-length for every encoded byte\n during pg_hex_encode" }, { "msg_contents": "On Tue, Aug 17, 2021 at 09:39:30AM -0400, Tom Lane wrote:\n> OK, but the commit message should explain why they're getting reverted.\n\nSure. aef8948 gets down because of the performance impact. ccf4e27\nwas a cleanup following up aef8948, that loses its meaning. And\nc3826f8 cannot be let alone because of the reasons why aef8948 was\nintroduced, as it has no safety net for out-of-bound handling in the\nresult buffer allocated.\n--\nMichael", "msg_date": "Wed, 18 Aug 2021 09:14:14 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: PG14: Avoid checking output-buffer-length for every encoded byte\n during pg_hex_encode" }, { "msg_contents": "On Wed, Aug 18, 2021 at 09:14:14AM +0900, Michael Paquier wrote:\n> Sure. aef8948 gets down because of the performance impact. ccf4e27\n> was a cleanup following up aef8948, that loses its meaning. And\n> c3826f8 cannot be let alone because of the reasons why aef8948 was\n> introduced, as it has no safety net for out-of-bound handling in the\n> result buffer allocated.\n\nAnd done, with such a description in the commit log.\n--\nMichael", "msg_date": "Thu, 19 Aug 2021 12:29:44 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: PG14: Avoid checking output-buffer-length for every encoded byte\n during pg_hex_encode" } ]
[ { "msg_contents": "The following bug has been logged on the website:\n\nBug reference: 17144\nLogged by: alex kozhemyakin\nEmail address: a.kozhemyakin@postgrespro.ru\nPostgreSQL version: 14beta1\nOperating system: ubuntu 20.04\nDescription: \n\nWhen trying to upgrade PostgreSQL 13 cluster with the earthdistance\nextension installed to PostgreSQL 14, I get the following error:\r\npsql:./update_extensions.sql:2: ERROR: type earth is already a member of\nextension \"earthdistance\"\r\n\r\nThe reproducing script:\r\nPGBIN_OLD=/home/test/rel13\r\nPGBIN_NEW=/home/test/rel14\r\nPGDATA_OLD=/home/test/data_old\r\nPGDATA_NEW=/home/test/data_new\r\n\r\ngit clone https://github.com/postgres/postgres.git postgres &&\r\ncd ./postgres &&\r\ngit checkout REL_13_STABLE && git reset --hard HEAD && git rebase\r\n./configure --prefix=$PGBIN_OLD\r\nmake -j2 > /dev/null && make -j2 -C contrib > /dev/null &&.\r\nmake install > /dev/null && make install -C contrib > /dev/null &&\r\ngit checkout REL_14_STABLE && rm -rf * && git reset --hard HEAD && git\nrebase\r\n./configure --prefix=$PGBIN_NEW\r\nmake -j2 > /dev/null && make -j2 -C contrib > /dev/null &&.\r\nmake install > /dev/null && make install -C contrib > /dev/null &&\r\ncd ..\r\n$PGBIN_OLD/bin/initdb -D $PGDATA_OLD &&.\r\n$PGBIN_OLD/bin/pg_ctl -w -D $PGDATA_OLD -l logfile_old start &&\r\n$PGBIN_OLD/bin/psql -c 'create extension earthdistance cascade;' postgres\n&&\r\n$PGBIN_OLD/bin/pg_ctl -w -D $PGDATA_OLD stop &&\r\n$PGBIN_NEW/bin/initdb -D $PGDATA_NEW &&.\r\n$PGBIN_NEW/bin/pg_upgrade -b $PGBIN_OLD/bin -d $PGDATA_OLD -B $PGBIN_NEW/bin\n-D $PGDATA_NEW &&\r\n$PGBIN_NEW/bin/pg_ctl -w -D $PGDATA_NEW -l logfile_new start &&\r\n$PGBIN_NEW/bin/psql -f ./update_extensions.sql postgres\r\n\r\nRemoving the earthdistance extension in PG 13 before the upgrade resolves\nthe issue.", "msg_date": "Sun, 15 Aug 2021 17:23:58 +0000", "msg_from": "PG Bug reporting form <noreply@postgresql.org>", "msg_from_op": true, "msg_subject": "BUG #17144: Upgrade from v13 to v14 with the cube extension failed" }, { "msg_contents": "PG Bug reporting form <noreply@postgresql.org> writes:\n> When trying to upgrade PostgreSQL 13 cluster with the earthdistance\n> extension installed to PostgreSQL 14, I get the following error:\n> psql:./update_extensions.sql:2: ERROR: type earth is already a member of\n> extension \"earthdistance\"\n\nHm, thanks. This does not seem to be a problem with pg_upgrade per se;\nyou can reproduce it with\n\nregression=# CREATE EXTENSION cube VERSION '1.4';\nCREATE EXTENSION\nregression=# CREATE EXTENSION earthdistance;\nCREATE EXTENSION\nregression=# ALTER EXTENSION \"cube\" UPDATE;\nERROR: type earth is already a member of extension \"earthdistance\"\n\nThe failure happens during this command in cube--1.4--1.5.sql:\n\nALTER TYPE cube SET ( RECEIVE = cube_recv, SEND = cube_send );\n\nwith stack trace\n\n#0 errfinish (filename=0x9c15e3 \"pg_depend.c\", lineno=210, \n funcname=0x9c1660 <__func__.16045> \"recordDependencyOnCurrentExtension\")\n at elog.c:515\n#1 0x000000000049886f in recordDependencyOnCurrentExtension (\n object=object@entry=0x7ffe09f2b778, isReplace=isReplace@entry=true)\n at pg_depend.c:206\n#2 0x00000000005f65ce in GenerateTypeDependencies (\n typeTuple=typeTuple@entry=0x2fa8f70, \n typeCatalog=typeCatalog@entry=0x7fc882ee5970, \n defaultExpr=defaultExpr@entry=0x0, typacl=typacl@entry=0x0, \n relationKind=relationKind@entry=0 '\\000', \n isImplicitArray=isImplicitArray@entry=false, isDependentType=false, \n rebuild=true) at pg_type.c:614\n#3 0x000000000069519e in AlterTypeRecurse (typeOid=37834, \n isImplicitArray=<optimized out>, tup=<optimized out>, \n catalog=0x7fc882ee5970, atparams=0x7ffe09f2bba0) at typecmds.c:4411\n#4 0x0000000000695265 in AlterTypeRecurse (typeOid=37745, \n isImplicitArray=<optimized out>, tup=<optimized out>, \n catalog=0x7fc882ee5970, atparams=0x7ffe09f2bba0) at typecmds.c:4488\n#5 0x00000000006997f6 in AlterType (stmt=stmt@entry=0x2fb01f0)\n at typecmds.c:4313\n#6 0x00000000008340be in ProcessUtilitySlow (pstate=0x2ee2900, \n pstmt=0x2ee2b88, \n queryString=0x2f067b8 \"/* contrib/cube/cube--1.4--1.5.sql */\\n\\n-- complain if script is sourced in psql, rather than via ALTER EXTENSION\\n\\n\\n-- Remove @ and ~\\nDROP OPERATOR @ (cube, cube);\\nDROP OPERATOR ~ (cube, cube);\\n\\n-- Add\"..., context=PROCESS_UTILITY_QUERY, params=0x0, queryEnv=0x0, qc=0x0, \n\nSo apparently the dependency-updating logic is a few bricks shy\nof a load. The object being passed to recordDependencyOnCurrentExtension\nis\n\n(gdb) p *object\n$1 = {classId = 1247, objectId = 37834, objectSubId = 0}\n\nwhich sure enough is type \"earth\". So apparently, this code is\ntrying to absorb EVERYTHING that depends on type cube into the\ncube extension.\n\n[ experiments a bit more ] It might just be directly-dependent types.\nIf I create a table column of type cube, then nothing strange happens\nduring the upgrade. But if I create a domain over cube, then do the\nupdate, the domain gets absorbed into the extension. That'd be kind\nof annoying :-(\n\nHaven't discovered exactly where it's going off the rails, though.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 16 Aug 2021 12:05:53 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: BUG #17144: Upgrade from v13 to v14 with the cube extension\n failed" }, { "msg_contents": "I wrote:\n> Hm, thanks. This does not seem to be a problem with pg_upgrade per se;\n> you can reproduce it with\n\n> regression=# CREATE EXTENSION cube VERSION '1.4';\n> CREATE EXTENSION\n> regression=# CREATE EXTENSION earthdistance;\n> CREATE EXTENSION\n> regression=# ALTER EXTENSION \"cube\" UPDATE;\n> ERROR: type earth is already a member of extension \"earthdistance\"\n\n> [ experiments a bit more ] It might just be directly-dependent types.\n> If I create a table column of type cube, then nothing strange happens\n> during the upgrade. But if I create a domain over cube, then do the\n> update, the domain gets absorbed into the extension. That'd be kind\n> of annoying :-(\n\nSo the problem is that ALTER TYPE SET recurses to dependent domains,\nas it must, but it is not careful about what that implies for extension\nmembership. It looks like we need to extend GenerateTypeDependencies\nso that it knows not to mess with extension dependencies when doing\nan ALTER.\n\nThere's a policy question here, which is when does an operation on\na pre-existing object within an extension script cause the object\nto be absorbed into the extension? You might naively say \"never\",\nbut that's not our historical behavior, and I think it'd clearly\nbe the wrong thing in some cases. For example, consider\n\nCREATE TYPE cube; -- make a shell type\n-- do something that requires type cube to exist\nCREATE EXTENSION cube;\n\nWe don't want this to fail, because it might be necessary to do\nthings that way to get out of circular dependencies. On the other\nhand, the formerly-shell type had certainly better wind up owned\nby the extension.\n\nThe general policy as the code stands seems to be that CREATE OR\nREPLACE-style operations will absorb any replaced object into\nthe extension. IMO extension scripts generally shouldn't use\nCREATE OR REPLACE unless they're sure they already have such an\nobject; but if one does use such a command, I think this behavior\nis reasonable.\n\nThe situation is a lot less clear-cut for ALTER commands, though.\nAgain, it's dubious that an extension should ever apply ALTER to\nan object that it doesn't know it already owns; but if it does,\nshould that result in absorbing the object? I'm inclined to think\nnot, so the attached patch just causes AlterTypeRecurse and\nAlterDomainDefault to never change the object's extension membership.\nThat's more behavioral change than is strictly needed to fix the\nbug at hand, but I think it's a consistent definition.\n\nI looked around for other places that might have similar issues,\nand the only one I could find (accepting that CREATE OR REPLACE\nshould work this way) is that ALTER OPERATOR ... SET applies\nmakeOperatorDependencies, which has the same sort of behavior as\nGenerateTypeDependencies does. I'm inclined to think that for\nconsistency, we should make that case likewise not change extension\nmembership; but I've not done anything about it in the attached.\n\nAnother point that perhaps deserves discussion is whether it's\nokay to change the signature of GenerateTypeDependencies in\nstable branches (we need to fix this in v13 not only v14/HEAD).\nI can't see a good reason for extensions to be calling that,\nand codesearch.debian.net knows of no outside callers, so I'm\ninclined to just change it. If anyone thinks that's too risky,\nwe could do something with a wrapper function in v13.\n\nComments?\n\n\t\t\tregards, tom lane", "msg_date": "Mon, 16 Aug 2021 15:36:59 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "ALTER TYPE vs extension membership (was Re: BUG #17144: Upgrade from\n v13 to v14 with the cube extension failed)" }, { "msg_contents": "Hi,\n\nOn 2021-08-16 15:36:59 -0400, Tom Lane wrote:\n> There's a policy question here, which is when does an operation on\n> a pre-existing object within an extension script cause the object\n> to be absorbed into the extension? You might naively say \"never\",\n> but that's not our historical behavior, and I think it'd clearly\n> be the wrong thing in some cases. For example, consider\n> \n> CREATE TYPE cube; -- make a shell type\n> -- do something that requires type cube to exist\n> CREATE EXTENSION cube;\n> \n> We don't want this to fail, because it might be necessary to do\n> things that way to get out of circular dependencies.\n\nIn what scenario would that be a good way to address a circular\ndependency? ISTM that whatever depends on $ext should be using shell\ntypes or such to avoid the circular dependency, then create $ext. Rather\nthan creating shell types for object in $ext and then create $ext.\n\n\n> Another point that perhaps deserves discussion is whether it's\n> okay to change the signature of GenerateTypeDependencies in\n> stable branches (we need to fix this in v13 not only v14/HEAD).\n> I can't see a good reason for extensions to be calling that,\n> and codesearch.debian.net knows of no outside callers, so I'm\n> inclined to just change it. If anyone thinks that's too risky,\n> we could do something with a wrapper function in v13.\n\nSeems OK to not bother with a wrapper to me - I can't see a reason\neither.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 17 Aug 2021 04:22:33 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: ALTER TYPE vs extension membership (was Re: BUG #17144: Upgrade\n from v13 to v14 with the cube extension failed)" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2021-08-16 15:36:59 -0400, Tom Lane wrote:\n>> There's a policy question here, which is when does an operation on\n>> a pre-existing object within an extension script cause the object\n>> to be absorbed into the extension? You might naively say \"never\",\n>> but that's not our historical behavior, and I think it'd clearly\n>> be the wrong thing in some cases. For example, consider\n>> \n>> CREATE TYPE cube; -- make a shell type\n>> -- do something that requires type cube to exist\n>> CREATE EXTENSION cube;\n>> \n>> We don't want this to fail, because it might be necessary to do\n>> things that way to get out of circular dependencies.\n\n> In what scenario would that be a good way to address a circular\n> dependency? ISTM that whatever depends on $ext should be using shell\n> types or such to avoid the circular dependency, then create $ext. Rather\n> than creating shell types for object in $ext and then create $ext.\n\nPerhaps. But that does work today (I tested), and it's been the\nintentional behavior ever since we invented extensions, to judge\nby the fact that the existing comments on GenerateTypeDependencies\ndescribe the current behavior explicitly. (Admitted, that's only\ntalking about types not other sorts of objects, which is why I moved\nthat comment in the proposed patch.) So I'm loath to get rid of it\nin a back-patched bug fix.\n\nMaybe there is a case for becoming stricter in HEAD, but I'm not\nreally clear on what would be an improvement. I do not think that\n\"don't adopt the object into the extension\" could be sane. The only\nother alternative is \"throw an error\", which goes against the clear\nintention and definition of CREATE OR REPLACE.\n\nThe fact that you don't need to say CREATE OR REPLACE TYPE to replace\na shell type muddies the waters here a bit, but I think we should still\nconsider that behavior to be an instance of CREATE OR REPLACE.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 17 Aug 2021 09:35:50 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: ALTER TYPE vs extension membership (was Re: BUG #17144: Upgrade\n from v13 to v14 with the cube extension failed)" } ]
[ { "msg_contents": "While trying to improve the code-coverage report for backend/regex/,\nI found that there are portions of copyins() and copyouts() that are\njust plain unreachable, because those functions are over-engineered.\nIn point of fact, the only uses of copyins() and copyouts() are in\nplaces where the target state is brand new and cannot have any\npre-existing in-arcs (resp. out-arcs). This means that all the\ntrouble we're going to to de-duplicate the copied arcs is entirely\nwasted; we could just copy the source arcs without extra checking.\n\nA fairly significant fraction, though by no means all, of the calls\nof moveins() and moveouts() are likewise working with new target\nstates, and so don't really need to do any de-duplication.\n\nHence I propose 0001 attached, which creates simplified functions\ncopyinstonew() and so on, for use when the target state is known not\nto have any existing arcs. I'd thought that this might show a useful\nimprovement in regexp compilation speed, but it's pretty hard to\nmeasure any noticeable change on typical regexps such as Jacobson's\nweb corpus. (I do see maybe a 1% improvement on that, but that's\nbelow the noise threshold so I don't take it too seriously.) It is\npossible to demonstrate noticeable improvement on handpicked regexes,\nfor example on HEAD:\n\nregression=# SELECT regexp_matches('foo', 'abcdefghijklmnopq((\\y|.?)+)+','');\n regexp_matches \n----------------\n(0 rows)\n\nTime: 6.297 ms\n\nversus with patch:\n\nregression=# SELECT regexp_matches('foo', 'abcdefghijklmnopq((\\y|.?)+)+','');\n regexp_matches \n----------------\n(0 rows)\n\nTime: 5.506 ms\n\nSo this isn't entirely a waste of time, but it is marginal. Improving\nthe code-coverage numbers is probably a better argument. (0001 also\nadds some test cases that exercise nearly everything that's reachable\nwithout OOM conditions or cancels in regc_nfa.c.)\n\n0002 below is some additional test cases to improve code coverage in\nregc_locale.c and regc_pg_locale.c. (regc_pg_locale.c is still not\ngreat, but that's mostly because much of the code is only reachable\nfor particular choices of database encoding, so any one coverage\nrun hits just some of it.)\n\nBarring objections, I plan to push this in a day or two; I don't\nthink it needs much review.\n\n\t\t\tregards, tom lane", "msg_date": "Sun, 15 Aug 2021 17:47:43 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Minor regexp hacking: code coverage, moveins() and friends" } ]
[ { "msg_contents": "Hi all,\n\ntopminnow has just failed in a weird fashion:\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=topminnow&dt=2021-08-15%2013%3A24%3A58\n# SELECT pid != FROM pg_stat_replication WHERE application_name = 'tap_sub';\n# expecting this output:\n# t\n# last actual query output:\n#\n# with stderr:\n# ERROR: syntax error at or near \"FROM\"\n# LINE 1: SELECT pid != FROM pg_stat_replication WHERE application_na...\n\nLooking at the logs, it seems like the problem boils down to an active\nslot when using ALTER SUBSCRIPTION tap_sub CONNECTION:\n2021-08-15 18:44:38.027 CEST [16473:2] ERROR: could not start WAL\nstreaming: ERROR: replication slot \"tap_sub\" is active for PID 16336\n\nThere is only one place in 001_rep_changes.pl where this is used.\n\nThoughts?\n--\nMichael", "msg_date": "Mon, 16 Aug 2021 12:52:55 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Failure of subscription tests with topminnow" }, { "msg_contents": "On Mon, Aug 16, 2021 at 9:24 AM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> Hi all,\n>\n> topminnow has just failed in a weird fashion:\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=topminnow&dt=2021-08-15%2013%3A24%3A58\n> # SELECT pid != FROM pg_stat_replication WHERE application_name = 'tap_sub';\n> # expecting this output:\n> # t\n> # last actual query output:\n> #\n> # with stderr:\n> # ERROR: syntax error at or near \"FROM\"\n> # LINE 1: SELECT pid != FROM pg_stat_replication WHERE application_na...\n>\n> Looking at the logs, it seems like the problem boils down to an active\n> slot when using ALTER SUBSCRIPTION tap_sub CONNECTION:\n> 2021-08-15 18:44:38.027 CEST [16473:2] ERROR: could not start WAL\n> streaming: ERROR: replication slot \"tap_sub\" is active for PID 16336\n>\n\nThe \"ALTER SUBSCRIPTION tap_sub CONNECTION\" would lead to restart the\nwalsender process. Now, here the problem seems to be that the previous\nwalsender process (16336) didn't exit and the new process started to\nuse the slot which leads to the error shown in the log. This is\nevident from the below part of log where we can see that 16336 has\nexited after new process started to use the slot.\n\n2021-08-15 18:44:38.027 CEST [16475:6] tap_sub LOG: received\nreplication command: START_REPLICATION SLOT \"tap_sub\" LOGICAL\n0/16BEEB0 (proto_version '1', publication_names\n'\"tap_pub\",\"tap_pub_ins_only\"')\n2021-08-15 18:44:38.027 CEST [16475:7] tap_sub STATEMENT:\nSTART_REPLICATION SLOT \"tap_sub\" LOGICAL 0/16BEEB0 (proto_version '1',\npublication_names '\"tap_pub\",\"tap_pub_ins_only\"')\n2021-08-15 18:44:38.027 CEST [16475:8] tap_sub ERROR: replication\nslot \"tap_sub\" is active for PID 16336\n2021-08-15 18:44:38.027 CEST [16475:9] tap_sub STATEMENT:\nSTART_REPLICATION SLOT \"tap_sub\" LOGICAL 0/16BEEB0 (proto_version '1',\npublication_names '\"tap_pub\",\"tap_pub_ins_only\"')\n2021-08-15 18:44:38.041 CEST [16475:10] tap_sub LOG: disconnection:\nsession time: 0:00:00.036 user=nm database=postgres host=[local]\n2021-08-15 18:44:38.043 CEST [16336:14] tap_sub LOG: disconnection:\nsession time: 0:00:06.367 user=nm database=postgres host=[local]\n\nOne idea to solve this is to first disable the subscription, wait for\nthe walsender process to exit, and then change the connection string\nand re-enable the subscription.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Mon, 16 Aug 2021 14:02:47 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Mon, Aug 16, 2021 at 6:33 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> The \"ALTER SUBSCRIPTION tap_sub CONNECTION\" would lead to restart the\n> walsender process. Now, here the problem seems to be that the previous\n> walsender process (16336) didn't exit and the new process started to\n> use the slot which leads to the error shown in the log. This is\n> evident from the below part of log where we can see that 16336 has\n> exited after new process started to use the slot.\n>\n> 2021-08-15 18:44:38.027 CEST [16475:6] tap_sub LOG: received\n> replication command: START_REPLICATION SLOT \"tap_sub\" LOGICAL\n> 0/16BEEB0 (proto_version '1', publication_names\n> '\"tap_pub\",\"tap_pub_ins_only\"')\n> 2021-08-15 18:44:38.027 CEST [16475:7] tap_sub STATEMENT:\n> START_REPLICATION SLOT \"tap_sub\" LOGICAL 0/16BEEB0 (proto_version '1',\n> publication_names '\"tap_pub\",\"tap_pub_ins_only\"')\n> 2021-08-15 18:44:38.027 CEST [16475:8] tap_sub ERROR: replication\n> slot \"tap_sub\" is active for PID 16336\n> 2021-08-15 18:44:38.027 CEST [16475:9] tap_sub STATEMENT:\n> START_REPLICATION SLOT \"tap_sub\" LOGICAL 0/16BEEB0 (proto_version '1',\n> publication_names '\"tap_pub\",\"tap_pub_ins_only\"')\n> 2021-08-15 18:44:38.041 CEST [16475:10] tap_sub LOG: disconnection:\n> session time: 0:00:00.036 user=nm database=postgres host=[local]\n> 2021-08-15 18:44:38.043 CEST [16336:14] tap_sub LOG: disconnection:\n> session time: 0:00:06.367 user=nm database=postgres host=[local]\n>\n> One idea to solve this is to first disable the subscription, wait for\n> the walsender process to exit, and then change the connection string\n> and re-enable the subscription.\n\nI tried to simulate this by putting delays prior to the exit of the\nwalsender. Even though I see the same error\nin the logs that the replication slot is active for the previous PID,\nthe test case does not fail in the way seen in this case here..\n\nThe new walsender tries to acquire the slot but seeing that there is\nanother PID that is active on the slot, it\nerrors and exits. At no point does this new failed walsender update\nits pid for the slot. As a result, the below polled query\nwould not return a true value\n\n$node_publisher->poll_query_until('postgres',\n \"SELECT pid != $oldpid FROM pg_stat_replication WHERE\napplication_name = 'tap_sub';\"\n) or die \"Timed out while waiting for apply to restart\";\n\nIn my runs I see that this query is repeated until a new walsender is\nable to successfully acquire the slot.\nI am not able to explain why this query returned true in the topminnow\ntap test. This would imply that a walsender\nwas able to acquire the slot and update its pid but I don't see how.\nWe also know that if this polled query returns\na true (implying a pid other than $oldpid), then the next query in the\ntest is to try and identify the pid:\n\nSELECT pid FROM pg_stat_replication WHERE application_name = 'tap_sub';\n\n From the topminnow logs we know that this query returned a \"NULL\", as\nthe value extracted from this is used\nto formulate the next query which errored out and eventually caused\nthe test case to fail.\n\n [16482:3] 001_rep_changes.pl ERROR: syntax error at or near \"FROM\"\nat character 16\n [16482:4] 001_rep_changes.pl STATEMENT: SELECT pid != FROM\npg_stat_replication WHERE application_name = 'tap_sub';\n\nI am not an expert in perl but I looked at the perl function used in\nthe tap test poll_query_until(), this would poll until the query\nreturns a 'true' (unless specified otherwise).\nI don't see in my tests that the polled function exits if the query\nreturns a NULL. I don't know if differences in the installed perl can\ncause this difference in\nbehaviour. Can a NULL set be construed as a true and cause the poll to exit?\n\n Any suggestions?\n\nregards,\nAjin Cherian\nFujitsu Australia\n\n\n", "msg_date": "Tue, 24 Aug 2021 15:34:40 +1000", "msg_from": "Ajin Cherian <itsajin@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Tue, Aug 24, 2021 at 11:04 AM Ajin Cherian <itsajin@gmail.com> wrote:\n>\n> On Mon, Aug 16, 2021 at 6:33 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> > The \"ALTER SUBSCRIPTION tap_sub CONNECTION\" would lead to restart the\n> > walsender process. Now, here the problem seems to be that the previous\n> > walsender process (16336) didn't exit and the new process started to\n> > use the slot which leads to the error shown in the log. This is\n> > evident from the below part of log where we can see that 16336 has\n> > exited after new process started to use the slot.\n> >\n> > 2021-08-15 18:44:38.027 CEST [16475:6] tap_sub LOG: received\n> > replication command: START_REPLICATION SLOT \"tap_sub\" LOGICAL\n> > 0/16BEEB0 (proto_version '1', publication_names\n> > '\"tap_pub\",\"tap_pub_ins_only\"')\n> > 2021-08-15 18:44:38.027 CEST [16475:7] tap_sub STATEMENT:\n> > START_REPLICATION SLOT \"tap_sub\" LOGICAL 0/16BEEB0 (proto_version '1',\n> > publication_names '\"tap_pub\",\"tap_pub_ins_only\"')\n> > 2021-08-15 18:44:38.027 CEST [16475:8] tap_sub ERROR: replication\n> > slot \"tap_sub\" is active for PID 16336\n> > 2021-08-15 18:44:38.027 CEST [16475:9] tap_sub STATEMENT:\n> > START_REPLICATION SLOT \"tap_sub\" LOGICAL 0/16BEEB0 (proto_version '1',\n> > publication_names '\"tap_pub\",\"tap_pub_ins_only\"')\n> > 2021-08-15 18:44:38.041 CEST [16475:10] tap_sub LOG: disconnection:\n> > session time: 0:00:00.036 user=nm database=postgres host=[local]\n> > 2021-08-15 18:44:38.043 CEST [16336:14] tap_sub LOG: disconnection:\n> > session time: 0:00:06.367 user=nm database=postgres host=[local]\n> >\n> > One idea to solve this is to first disable the subscription, wait for\n> > the walsender process to exit, and then change the connection string\n> > and re-enable the subscription.\n>\n> I tried to simulate this by putting delays prior to the exit of the\n> walsender. Even though I see the same error\n> in the logs that the replication slot is active for the previous PID,\n> the test case does not fail in the way seen in this case here..\n>\n> The new walsender tries to acquire the slot but seeing that there is\n> another PID that is active on the slot, it\n> errors and exits. At no point does this new failed walsender update\n> its pid for the slot. As a result, the below polled query\n> would not return a true value\n>\n> $node_publisher->poll_query_until('postgres',\n> \"SELECT pid != $oldpid FROM pg_stat_replication WHERE\n> application_name = 'tap_sub';\"\n> ) or die \"Timed out while waiting for apply to restart\";\n>\n> In my runs I see that this query is repeated until a new walsender is\n> able to successfully acquire the slot.\n>\n\nWhat happens when there is neither a new walsender nor an old\nwalsender is present? It means to run the above statement when a new\nwalsender is exited due to error \"... slot is active ...\" and before a\nnew walsender could start. Also, allow old walsender (due to which the\nerror occurs) to exit before executing the statement.\n\nAlso, it seems this failure happens on REL_11_STABLE branch, not sure\nif that matters, but it is better to use the same branch if you are\nusing a different branch to reproduce the issue.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 24 Aug 2021 16:38:20 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Tue, Aug 24, 2021 at 9:08 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> What happens when there is neither a new walsender nor an old\n> walsender is present? It means to run the above statement when a new\n> walsender is exited due to error \"... slot is active ...\" and before a\n> new walsender could start. Also, allow old walsender (due to which the\n> error occurs) to exit before executing the statement.\n>\nI tried this, then the query returns a null instead of 'false' because\nthere is no entry for that application_name.\n\npostgres=# select pid != 31876 from pg_stat_replication where\napplication_name = 'sub';\n ?column?\n----------\n(0 rows)\n\n\n> Also, it seems this failure happens on REL_11_STABLE branch, not sure\n> if that matters, but it is better to use the same branch if you are\n> using a different branch to reproduce the issue.\n>\n\nOk, I didn't realise this. I will try this.\n\nregards,\nAjin Cherian\nFujitsu Australia\n\n\n", "msg_date": "Tue, 24 Aug 2021 22:58:35 +1000", "msg_from": "Ajin Cherian <itsajin@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Tue, Aug 24, 2021 at 6:28 PM Ajin Cherian <itsajin@gmail.com> wrote:\n>\n> On Tue, Aug 24, 2021 at 9:08 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> > What happens when there is neither a new walsender nor an old\n> > walsender is present? It means to run the above statement when a new\n> > walsender is exited due to error \"... slot is active ...\" and before a\n> > new walsender could start. Also, allow old walsender (due to which the\n> > error occurs) to exit before executing the statement.\n> >\n> I tried this, then the query returns a null instead of 'false' because\n> there is no entry for that application_name.\n>\n> postgres=# select pid != 31876 from pg_stat_replication where\n> application_name = 'sub';\n> ?column?\n> ----------\n> (0 rows)\n>\n\nBut will poll function still poll or exit? Have you tried that?\nBecause it is not clear from your explanation how in the first\nstatement it returns a valid value which leads poll to exit and then\nin second statement it returns NULL or maybe nothing. Can you share\nthe log also when you are getting \"replication slot \"tap_sub\" is\nactive for ...\"? If you see in the below log [1], the STATEMENT is\nprinted twice, I want to see if you also get prints in a similar way\nor is it something different? Do you know why it is printed twice?\n\n[1]\n2021-08-15 18:44:38.027 CEST [16475:6] tap_sub LOG: received\nreplication command: START_REPLICATION SLOT \"tap_sub\" LOGICAL\n0/16BEEB0 (proto_version '1', publication_names\n'\"tap_pub\",\"tap_pub_ins_only\"')\n2021-08-15 18:44:38.027 CEST [16475:7] tap_sub STATEMENT:\nSTART_REPLICATION SLOT \"tap_sub\" LOGICAL 0/16BEEB0 (proto_version '1',\npublication_names '\"tap_pub\",\"tap_pub_ins_only\"')\n2021-08-15 18:44:38.027 CEST [16475:8] tap_sub ERROR: replication\nslot \"tap_sub\" is active for PID 16336\n2021-08-15 18:44:38.027 CEST [16475:9] tap_sub STATEMENT:\nSTART_REPLICATION SLOT \"tap_sub\" LOGICAL 0/16BEEB0 (proto_version '1',\npublication_names '\"tap_pub\",\"tap_pub_ins_only\"')\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 24 Aug 2021 18:41:49 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Tue, Aug 24, 2021 at 11:12 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> But will poll function still poll or exit? Have you tried that?\n\nI have forced that condition with a changed query and found that the\npoll will not exit in case of a NULL return.\n\n> Because it is not clear from your explanation how in the first\n> statement it returns a valid value which leads poll to exit and then\n> in second statement it returns NULL or maybe nothing. Can you share\n\nI don't have an explanation for it either. Maybe things are different\nin REL_11_STABLE\n\n> the log also when you are getting \"replication slot \"tap_sub\" is\n> active for ...\"? If you see in the below log [1], the STATEMENT is\n> printed twice, I want to see if you also get prints in a similar way\n> or is it something different? Do you know why it is printed twice?\n>\n\nYes, I get the same. For every \"LOG or ERROR\" message, there is the\nassociated STATEMENT message with it.\nFirst there is a LOG \"received replication command\" followed by the\nSTATEMENT and then the ERROR \"replication slot .. is active..\"\nfollowed by the STATEMENT.\n\nI will try with REL_11_STABLE and see if the behaviour is different.\n\nregards,\nAjin Cherian\nFujitsu Australia\n\n\n", "msg_date": "Wed, 25 Aug 2021 12:30:28 +1000", "msg_from": "Ajin Cherian <itsajin@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Wed, Aug 25, 2021 at 8:00 AM Ajin Cherian <itsajin@gmail.com> wrote:\n>\n> On Tue, Aug 24, 2021 at 11:12 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> > But will poll function still poll or exit? Have you tried that?\n>\n> I have forced that condition with a changed query and found that the\n> poll will not exit in case of a NULL return.\n>\n\nWhat if the query in a poll is fired just before we get an error\n\"tap_sub ERROR: replication slot \"tap_sub\" is active for PID 16336\"?\nWon't at that stage both old and new walsender's are present, so the\nquery might return true. You can check that via debugger by stopping\njust before this error occurs and then check pg_stat_replication view.\n\n>\n> I will try with REL_11_STABLE and see if the behaviour is different.\n>\n\nOkay, but I still suspect some timing issue here.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Wed, 25 Aug 2021 11:52:04 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Wed, Aug 25, 2021 at 4:22 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Wed, Aug 25, 2021 at 8:00 AM Ajin Cherian <itsajin@gmail.com> wrote:\n> >\n> > On Tue, Aug 24, 2021 at 11:12 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > > But will poll function still poll or exit? Have you tried that?\n> >\n> > I have forced that condition with a changed query and found that the\n> > poll will not exit in case of a NULL return.\n> >\n>\n> What if the query in a poll is fired just before we get an error\n> \"tap_sub ERROR: replication slot \"tap_sub\" is active for PID 16336\"?\n> Won't at that stage both old and new walsender's are present, so the\n> query might return true. You can check that via debugger by stopping\n> just before this error occurs and then check pg_stat_replication view.\n\nIf this error happens then the PID is NOT updated as the pid in the\nReplication slot. I have checked this\nand explained this in my first email itself\n\nregards,\nAjin Cherian\nFujitsu Australia\n\n\n", "msg_date": "Wed, 25 Aug 2021 17:43:15 +1000", "msg_from": "Ajin Cherian <itsajin@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Wed, Aug 25, 2021 at 5:43 PM Ajin Cherian <itsajin@gmail.com> wrote:\n>\n> On Wed, Aug 25, 2021 at 4:22 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > On Wed, Aug 25, 2021 at 8:00 AM Ajin Cherian <itsajin@gmail.com> wrote:\n> > >\n> > > On Tue, Aug 24, 2021 at 11:12 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > >\n> > > > But will poll function still poll or exit? Have you tried that?\n> > >\n> > > I have forced that condition with a changed query and found that the\n> > > poll will not exit in case of a NULL return.\n> > >\n> >\n> > What if the query in a poll is fired just before we get an error\n> > \"tap_sub ERROR: replication slot \"tap_sub\" is active for PID 16336\"?\n> > Won't at that stage both old and new walsender's are present, so the\n> > query might return true. You can check that via debugger by stopping\n> > just before this error occurs and then check pg_stat_replication view.\n>\n> If this error happens then the PID is NOT updated as the pid in the\n> Replication slot. I have checked this\n> and explained this in my first email itself\n>\n\nSorry about the above email, I misunderstood. I was looking at\npg_stat_replication_slot rather than pg_stat_replication hence the confusion.\nAmit is correct, just prior to the walsender erroring out, it briefly\nappears in the\npg_stat_replication, and that is why this error happens. Sorry for the\nconfusion.\nI just confirmed it, got both the walsenders stopped in the debugger:\n\npostgres=# select pid from pg_stat_replication where application_name = 'sub';\n pid\n------\n 7899\n 7993\n(2 rows)\n\n\najin 7896 3326 0 05:22 pts/2 00:00:00 psql -p 6972 postgres\najin 7897 7882 0 05:22 ? 00:00:00 postgres: ajin\npostgres [local] idle\najin 7899 7882 0 05:22 ? 00:00:00 postgres: walsender\najin ::1(37719) START_REPLICATION\najin 7992 3647 0 05:24 ? 00:00:00 postgres: logical\nreplication worker for subscription 16426\najin 7993 7882 0 05:24 ? 00:00:00 postgres: walsender\najin ::1(37720) START_REPLICATION\n\nregards,\nAjin Cherian\nFujitsu Australia\n\n\n", "msg_date": "Wed, 25 Aug 2021 19:53:01 +1000", "msg_from": "Ajin Cherian <itsajin@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Wed, Aug 25, 2021 at 6:53 PM Ajin Cherian <itsajin@gmail.com> wrote:\n>\n> On Wed, Aug 25, 2021 at 5:43 PM Ajin Cherian <itsajin@gmail.com> wrote:\n> >\n> > On Wed, Aug 25, 2021 at 4:22 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > >\n> > > On Wed, Aug 25, 2021 at 8:00 AM Ajin Cherian <itsajin@gmail.com> wrote:\n> > > >\n> > > > On Tue, Aug 24, 2021 at 11:12 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > > >\n> > > > > But will poll function still poll or exit? Have you tried that?\n> > > >\n> > > > I have forced that condition with a changed query and found that the\n> > > > poll will not exit in case of a NULL return.\n> > > >\n> > >\n> > > What if the query in a poll is fired just before we get an error\n> > > \"tap_sub ERROR: replication slot \"tap_sub\" is active for PID 16336\"?\n> > > Won't at that stage both old and new walsender's are present, so the\n> > > query might return true. You can check that via debugger by stopping\n> > > just before this error occurs and then check pg_stat_replication view.\n> >\n> > If this error happens then the PID is NOT updated as the pid in the\n> > Replication slot. I have checked this\n> > and explained this in my first email itself\n> >\n>\n> Sorry about the above email, I misunderstood. I was looking at\n> pg_stat_replication_slot rather than pg_stat_replication hence the confusion.\n> Amit is correct, just prior to the walsender erroring out, it briefly\n> appears in the\n> pg_stat_replication, and that is why this error happens. Sorry for the\n> confusion.\n> I just confirmed it, got both the walsenders stopped in the debugger:\n>\n> postgres=# select pid from pg_stat_replication where application_name = 'sub';\n> pid\n> ------\n> 7899\n> 7993\n> (2 rows)\n\nIIUC the query[1] used for polling returns two rows in this case: {t,\nf} or {f, t}. But did poll_query_until() returned OK in this case even\nif we expected one row of 't'? My guess of how this issue happened is:\n\n1. the first polling query after \"ATLER SUBSCRIPTION CONNECTION\"\npassed (for some reason).\n2. all wal senders exited.\n3. get the pid of wal sender with application_name 'tap_sub' but got nothing.\n4. the second polling query resulted in a syntax error since $oldpid is null.\n\nIf the fact that two walsender with the same application_name could\npresent in pg_stat_replication view was the cause of this issue,\npoll_query_until() should return OK even if we expected just 't'. I\nmight be missing something, though.\n\n[1] \"SELECT pid != $oldpid FROM pg_stat_replication WHERE\napplication_name = '$appname';\"\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Wed, 25 Aug 2021 20:32:01 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Wed, Aug 25, 2021 at 5:02 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Wed, Aug 25, 2021 at 6:53 PM Ajin Cherian <itsajin@gmail.com> wrote:\n> >\n> > On Wed, Aug 25, 2021 at 5:43 PM Ajin Cherian <itsajin@gmail.com> wrote:\n> > >\n> > > On Wed, Aug 25, 2021 at 4:22 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > > >\n> > > > On Wed, Aug 25, 2021 at 8:00 AM Ajin Cherian <itsajin@gmail.com> wrote:\n> > > > >\n> > > > > On Tue, Aug 24, 2021 at 11:12 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > > > >\n> > > > > > But will poll function still poll or exit? Have you tried that?\n> > > > >\n> > > > > I have forced that condition with a changed query and found that the\n> > > > > poll will not exit in case of a NULL return.\n> > > > >\n> > > >\n> > > > What if the query in a poll is fired just before we get an error\n> > > > \"tap_sub ERROR: replication slot \"tap_sub\" is active for PID 16336\"?\n> > > > Won't at that stage both old and new walsender's are present, so the\n> > > > query might return true. You can check that via debugger by stopping\n> > > > just before this error occurs and then check pg_stat_replication view.\n> > >\n> > > If this error happens then the PID is NOT updated as the pid in the\n> > > Replication slot. I have checked this\n> > > and explained this in my first email itself\n> > >\n> >\n> > Sorry about the above email, I misunderstood. I was looking at\n> > pg_stat_replication_slot rather than pg_stat_replication hence the confusion.\n> > Amit is correct, just prior to the walsender erroring out, it briefly\n> > appears in the\n> > pg_stat_replication, and that is why this error happens. Sorry for the\n> > confusion.\n> > I just confirmed it, got both the walsenders stopped in the debugger:\n> >\n> > postgres=# select pid from pg_stat_replication where application_name = 'sub';\n> > pid\n> > ------\n> > 7899\n> > 7993\n> > (2 rows)\n>\n> IIUC the query[1] used for polling returns two rows in this case: {t,\n> f} or {f, t}. But did poll_query_until() returned OK in this case even\n> if we expected one row of 't'? My guess of how this issue happened is:\n>\n\nYeah, we can check this but I guess as soon as it gets 't', the poll\nquery will exit.\n\n> 1. the first polling query after \"ATLER SUBSCRIPTION CONNECTION\"\n> passed (for some reason).\n>\n\nI think the reason for exit is that we get two rows with the same\napplication_name in pg_stat_replication.\n\n> 2. all wal senders exited.\n> 3. get the pid of wal sender with application_name 'tap_sub' but got nothing.\n> 4. the second polling query resulted in a syntax error since $oldpid is null.\n>\n\nYour understanding of steps is the same as mine.\n\n\n--\nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Wed, 25 Aug 2021 17:53:31 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Wed, Aug 25, 2021 at 9:32 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n\n>\n> IIUC the query[1] used for polling returns two rows in this case: {t,\n> f} or {f, t}. But did poll_query_until() returned OK in this case even\n> if we expected one row of 't'? My guess of how this issue happened is:\n>\n> 1. the first polling query after \"ATLER SUBSCRIPTION CONNECTION\"\n> passed (for some reason).\n> 2. all wal senders exited.\n> 3. get the pid of wal sender with application_name 'tap_sub' but got nothing.\n> 4. the second polling query resulted in a syntax error since $oldpid is null.\n>\n> If the fact that two walsender with the same application_name could\n> present in pg_stat_replication view was the cause of this issue,\n> poll_query_until() should return OK even if we expected just 't'. I\n> might be missing something, though.\n>\n> [1] \"SELECT pid != $oldpid FROM pg_stat_replication WHERE\n> application_name = '$appname';\"\n\nYes, the query [1] returns OK with a {f,t} or {t,f}\n\n[1] - \"SELECT pid != $oldpid FROM pg_stat_replication WHERE\napplication_name = '$appname';\"\n\nregards,\nAjin Cherian\nFujitsu Australia\n\n\n", "msg_date": "Wed, 25 Aug 2021 22:24:06 +1000", "msg_from": "Ajin Cherian <itsajin@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Wed, Aug 25, 2021 at 9:23 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Wed, Aug 25, 2021 at 5:02 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > On Wed, Aug 25, 2021 at 6:53 PM Ajin Cherian <itsajin@gmail.com> wrote:\n> > >\n> > > On Wed, Aug 25, 2021 at 5:43 PM Ajin Cherian <itsajin@gmail.com> wrote:\n> > > >\n> > > > On Wed, Aug 25, 2021 at 4:22 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > > > >\n> > > > > On Wed, Aug 25, 2021 at 8:00 AM Ajin Cherian <itsajin@gmail.com> wrote:\n> > > > > >\n> > > > > > On Tue, Aug 24, 2021 at 11:12 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > > > > >\n> > > > > > > But will poll function still poll or exit? Have you tried that?\n> > > > > >\n> > > > > > I have forced that condition with a changed query and found that the\n> > > > > > poll will not exit in case of a NULL return.\n> > > > > >\n> > > > >\n> > > > > What if the query in a poll is fired just before we get an error\n> > > > > \"tap_sub ERROR: replication slot \"tap_sub\" is active for PID 16336\"?\n> > > > > Won't at that stage both old and new walsender's are present, so the\n> > > > > query might return true. You can check that via debugger by stopping\n> > > > > just before this error occurs and then check pg_stat_replication view.\n> > > >\n> > > > If this error happens then the PID is NOT updated as the pid in the\n> > > > Replication slot. I have checked this\n> > > > and explained this in my first email itself\n> > > >\n> > >\n> > > Sorry about the above email, I misunderstood. I was looking at\n> > > pg_stat_replication_slot rather than pg_stat_replication hence the confusion.\n> > > Amit is correct, just prior to the walsender erroring out, it briefly\n> > > appears in the\n> > > pg_stat_replication, and that is why this error happens. Sorry for the\n> > > confusion.\n> > > I just confirmed it, got both the walsenders stopped in the debugger:\n> > >\n> > > postgres=# select pid from pg_stat_replication where application_name = 'sub';\n> > > pid\n> > > ------\n> > > 7899\n> > > 7993\n> > > (2 rows)\n> >\n> > IIUC the query[1] used for polling returns two rows in this case: {t,\n> > f} or {f, t}. But did poll_query_until() returned OK in this case even\n> > if we expected one row of 't'? My guess of how this issue happened is:\n> >\n>\n> Yeah, we can check this but I guess as soon as it gets 't', the poll\n> query will exit.\n\nI did a quick check with the following tap test code:\n\n$node_publisher->poll_query_until('postgres',\n qq(\nselect 1 != foo.column1 from (values(0), (1)) as foo;\n));\n\nThe query returns {t, f} but poll_query_until() never finished. The\nsame is true when the query returns {f, t}.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Wed, 25 Aug 2021 21:40:12 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Wed, Aug 25, 2021 at 5:54 PM Ajin Cherian <itsajin@gmail.com> wrote:\n>\n> On Wed, Aug 25, 2021 at 9:32 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> >\n> > IIUC the query[1] used for polling returns two rows in this case: {t,\n> > f} or {f, t}. But did poll_query_until() returned OK in this case even\n> > if we expected one row of 't'? My guess of how this issue happened is:\n> >\n> > 1. the first polling query after \"ATLER SUBSCRIPTION CONNECTION\"\n> > passed (for some reason).\n> > 2. all wal senders exited.\n> > 3. get the pid of wal sender with application_name 'tap_sub' but got nothing.\n> > 4. the second polling query resulted in a syntax error since $oldpid is null.\n> >\n> > If the fact that two walsender with the same application_name could\n> > present in pg_stat_replication view was the cause of this issue,\n> > poll_query_until() should return OK even if we expected just 't'. I\n> > might be missing something, though.\n> >\n> > [1] \"SELECT pid != $oldpid FROM pg_stat_replication WHERE\n> > application_name = '$appname';\"\n>\n> Yes, the query [1] returns OK with a {f,t} or {t,f}\n>\n> [1] - \"SELECT pid != $oldpid FROM pg_stat_replication WHERE\n> application_name = '$appname';\"\n>\n\nCan you additionally check the value of 'state' from\npg_stat_replication for both the old and new walsender sessions?\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Wed, 25 Aug 2021 18:43:49 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Wed, Aug 25, 2021 at 6:10 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> I did a quick check with the following tap test code:\n>\n> $node_publisher->poll_query_until('postgres',\n> qq(\n> select 1 != foo.column1 from (values(0), (1)) as foo;\n> ));\n>\n> The query returns {t, f} but poll_query_until() never finished. The\n> same is true when the query returns {f, t}.\n>\n\nThis means something different is going on in Ajin's setup. Ajin, can\nyou please share how did you confirm your findings about poll_query?\n\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Wed, 25 Aug 2021 18:47:05 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Wed, Aug 25, 2021 at 11:17 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Wed, Aug 25, 2021 at 6:10 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > I did a quick check with the following tap test code:\n> >\n> > $node_publisher->poll_query_until('postgres',\n> > qq(\n> > select 1 != foo.column1 from (values(0), (1)) as foo;\n> > ));\n> >\n> > The query returns {t, f} but poll_query_until() never finished. The\n> > same is true when the query returns {f, t}.\n> >\n\nYes, this is true, I also see the same behaviour.\n\n>\n> This means something different is going on in Ajin's setup. Ajin, can\n> you please share how did you confirm your findings about poll_query?\n\nRelooking at my logs, I think what happens is this:\n\n1. First walsender 'a' is running.\n2. Second walsender 'b' starts and attempts at acquiring the slot\nfinds that the slot is active for pid a.\n3. Now both walsenders are active, the query does not return.\n4. First walsender 'a' times out and exits.\n5. Now only the second walsender is active and the query returns OK\nbecause pid != a.\n6. Second walsender exits with error.\n7. Another query attempts to get the pid of the running walsender for\ntap_sub but returns null because both walsender exits.\n8. This null return value results in the next query erroring out and\nthe test failing.\n\n>Can you additionally check the value of 'state' from\n>pg_stat_replication for both the old and new walsender sessions?\n\nYes, will try this and post a patch tomorrow.\n\nregards,\nAjin Cherian\nFujitsu Australia\n\n\n", "msg_date": "Thu, 26 Aug 2021 00:04:23 +1000", "msg_from": "Ajin Cherian <itsajin@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Wed, Aug 25, 2021 at 11:04 PM Ajin Cherian <itsajin@gmail.com> wrote:\n>\n> On Wed, Aug 25, 2021 at 11:17 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > On Wed, Aug 25, 2021 at 6:10 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> > >\n> > > I did a quick check with the following tap test code:\n> > >\n> > > $node_publisher->poll_query_until('postgres',\n> > > qq(\n> > > select 1 != foo.column1 from (values(0), (1)) as foo;\n> > > ));\n> > >\n> > > The query returns {t, f} but poll_query_until() never finished. The\n> > > same is true when the query returns {f, t}.\n> > >\n>\n> Yes, this is true, I also see the same behaviour.\n>\n> >\n> > This means something different is going on in Ajin's setup. Ajin, can\n> > you please share how did you confirm your findings about poll_query?\n>\n> Relooking at my logs, I think what happens is this:\n>\n> 1. First walsender 'a' is running.\n> 2. Second walsender 'b' starts and attempts at acquiring the slot\n> finds that the slot is active for pid a.\n> 3. Now both walsenders are active, the query does not return.\n> 4. First walsender 'a' times out and exits.\n> 5. Now only the second walsender is active and the query returns OK\n> because pid != a.\n> 6. Second walsender exits with error.\n> 7. Another query attempts to get the pid of the running walsender for\n> tap_sub but returns null because both walsender exits.\n> 8. This null return value results in the next query erroring out and\n> the test failing.\n\nSo this is slightly different than what we can see in the topminnow\nlogs? According to the server logs, step #5 happened (at 18:44:38.016)\nbefore step #4 happened (at 18:44:38.043).\n\n>\n> >Can you additionally check the value of 'state' from\n> >pg_stat_replication for both the old and new walsender sessions?\n>\n> Yes, will try this and post a patch tomorrow.\n\nThanks. I guess the state of the new walsender should be \"startup\"\nwhereas the old one should be \"streaming\".\n\nRegards,\n\n--\nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Thu, 26 Aug 2021 10:01:56 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Thu, Aug 26, 2021 at 11:02 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Wed, Aug 25, 2021 at 11:04 PM Ajin Cherian <itsajin@gmail.com> wrote:\n> >\n> > On Wed, Aug 25, 2021 at 11:17 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > >\n> > > On Wed, Aug 25, 2021 at 6:10 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> > > >\n> > > > I did a quick check with the following tap test code:\n> > > >\n> > > > $node_publisher->poll_query_until('postgres',\n> > > > qq(\n> > > > select 1 != foo.column1 from (values(0), (1)) as foo;\n> > > > ));\n> > > >\n> > > > The query returns {t, f} but poll_query_until() never finished. The\n> > > > same is true when the query returns {f, t}.\n> > > >\n> >\n> > Yes, this is true, I also see the same behaviour.\n> >\n> > >\n> > > This means something different is going on in Ajin's setup. Ajin, can\n> > > you please share how did you confirm your findings about poll_query?\n> >\n> > Relooking at my logs, I think what happens is this:\n> >\n> > 1. First walsender 'a' is running.\n> > 2. Second walsender 'b' starts and attempts at acquiring the slot\n> > finds that the slot is active for pid a.\n> > 3. Now both walsenders are active, the query does not return.\n> > 4. First walsender 'a' times out and exits.\n> > 5. Now only the second walsender is active and the query returns OK\n> > because pid != a.\n> > 6. Second walsender exits with error.\n> > 7. Another query attempts to get the pid of the running walsender for\n> > tap_sub but returns null because both walsender exits.\n> > 8. This null return value results in the next query erroring out and\n> > the test failing.\n>\n> So this is slightly different than what we can see in the topminnow\n> logs? According to the server logs, step #5 happened (at 18:44:38.016)\n> before step #4 happened (at 18:44:38.043).\n>\n\nLuckily these logs have the disconnection times of the tap test client\nsessions as well. (not sure why I don't see these when I run these\ntests).\n\nStep 5 could have happened anywhere between 18:44:38.016 and 18:44:38.063\n18:44:38.016 CEST [16474:3] 001_rep_changes.pl LOG: statement: SELECT\npid != 16336 FROM pg_stat_replication WHERE application_name =\n'tap_sub';\n:\n:\n18:44:38.063 CEST [16474:4] 001_rep_changes.pl LOG: disconnection:\nsession time: 0:00:00.063 user=nm database=postgres host=[local]\n\nWhen the query starts both walsenders are present but when the query\ncompletes both walsenders are gone, the actual query evaluation could\nhave happened any time in between. This is the rare timing window that\ncauses this problem.\n\nregards,\nAjin Cherian\nFujitsu Australia\n\n\n", "msg_date": "Thu, 26 Aug 2021 12:07:53 +1000", "msg_from": "Ajin Cherian <itsajin@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Thu, Aug 26, 2021 at 7:38 AM Ajin Cherian <itsajin@gmail.com> wrote:\n>\n> On Thu, Aug 26, 2021 at 11:02 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n>\n> Luckily these logs have the disconnection times of the tap test client\n> sessions as well. (not sure why I don't see these when I run these\n> tests).\n>\n> Step 5 could have happened anywhere between 18:44:38.016 and 18:44:38.063\n> 18:44:38.016 CEST [16474:3] 001_rep_changes.pl LOG: statement: SELECT\n> pid != 16336 FROM pg_stat_replication WHERE application_name =\n> 'tap_sub';\n> :\n> :\n> 18:44:38.063 CEST [16474:4] 001_rep_changes.pl LOG: disconnection:\n> session time: 0:00:00.063 user=nm database=postgres host=[local]\n>\n> When the query starts both walsenders are present but when the query\n> completes both walsenders are gone, the actual query evaluation could\n> have happened any time in between. This is the rare timing window that\n> causes this problem.\n>\n\nYou have a point but if we see the below logs, it seems the second\nwalsender (#step6) seemed to exited before the first walsender\n(#step4).\n\n2021-08-15 18:44:38.041 CEST [16475:10] tap_sub LOG: disconnection:\nsession time: 0:00:00.036 user=nm database=postgres host=[local]\n2021-08-15 18:44:38.043 CEST [16336:14] tap_sub LOG: disconnection:\nsession time: 0:00:06.367 user=nm database=postgres host=[local]\n\nIsn't it possible that pid is cleared in the other order due to which\nwe are seeing this problem?\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Thu, 26 Aug 2021 08:36:24 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Thu, Aug 26, 2021 at 1:06 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n>\n> You have a point but if we see the below logs, it seems the second\n> walsender (#step6) seemed to exited before the first walsender\n> (#step4).\n>\n> 2021-08-15 18:44:38.041 CEST [16475:10] tap_sub LOG: disconnection:\n> session time: 0:00:00.036 user=nm database=postgres host=[local]\n> 2021-08-15 18:44:38.043 CEST [16336:14] tap_sub LOG: disconnection:\n> session time: 0:00:06.367 user=nm database=postgres host=[local]\n>\n> Isn't it possible that pid is cleared in the other order due to which\n> we are seeing this problem?\n\nIf the pid is cleared in the other order, wouldn't the query [1] return a false?\n\n[1] - \" SELECT pid != 16336 FROM pg_stat_replication WHERE\napplication_name = 'tap_sub';\"\n\nregards,\nAjin Cherian\nFujitsu Australia\n\n\n", "msg_date": "Thu, 26 Aug 2021 13:51:06 +1000", "msg_from": "Ajin Cherian <itsajin@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Thu, Aug 26, 2021 at 9:21 AM Ajin Cherian <itsajin@gmail.com> wrote:\n>\n> On Thu, Aug 26, 2021 at 1:06 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> >\n> > You have a point but if we see the below logs, it seems the second\n> > walsender (#step6) seemed to exited before the first walsender\n> > (#step4).\n> >\n> > 2021-08-15 18:44:38.041 CEST [16475:10] tap_sub LOG: disconnection:\n> > session time: 0:00:00.036 user=nm database=postgres host=[local]\n> > 2021-08-15 18:44:38.043 CEST [16336:14] tap_sub LOG: disconnection:\n> > session time: 0:00:06.367 user=nm database=postgres host=[local]\n> >\n> > Isn't it possible that pid is cleared in the other order due to which\n> > we are seeing this problem?\n>\n> If the pid is cleared in the other order, wouldn't the query [1] return a false?\n>\n> [1] - \" SELECT pid != 16336 FROM pg_stat_replication WHERE\n> application_name = 'tap_sub';\"\n>\n\nI think it should return true because pid for 16336 is cleared first\nand the remaining one will be 16475.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Thu, 26 Aug 2021 09:24:08 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Thu, Aug 26, 2021 at 1:54 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Thu, Aug 26, 2021 at 9:21 AM Ajin Cherian <itsajin@gmail.com> wrote:\n> >\n> > On Thu, Aug 26, 2021 at 1:06 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > >\n> > > You have a point but if we see the below logs, it seems the second\n> > > walsender (#step6) seemed to exited before the first walsender\n> > > (#step4).\n> > >\n> > > 2021-08-15 18:44:38.041 CEST [16475:10] tap_sub LOG: disconnection:\n> > > session time: 0:00:00.036 user=nm database=postgres host=[local]\n> > > 2021-08-15 18:44:38.043 CEST [16336:14] tap_sub LOG: disconnection:\n> > > session time: 0:00:06.367 user=nm database=postgres host=[local]\n> > >\n> > > Isn't it possible that pid is cleared in the other order due to which\n> > > we are seeing this problem?\n> >\n> > If the pid is cleared in the other order, wouldn't the query [1] return a false?\n> >\n> > [1] - \" SELECT pid != 16336 FROM pg_stat_replication WHERE\n> > application_name = 'tap_sub';\"\n> >\n>\n> I think it should return true because pid for 16336 is cleared first\n> and the remaining one will be 16475.\n\nYes, that was what I explained as well. 16336 is PID 'a' (first\nwalsender) in my explanation. The first walsender should\nbe cleared first for this theory to work.\n\nregards,\nAjin Cherian\nFujitsu Australia\n\n\n", "msg_date": "Thu, 26 Aug 2021 13:59:22 +1000", "msg_from": "Ajin Cherian <itsajin@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Thu, Aug 26, 2021 at 12:59 PM Ajin Cherian <itsajin@gmail.com> wrote:\n>\n> On Thu, Aug 26, 2021 at 1:54 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > On Thu, Aug 26, 2021 at 9:21 AM Ajin Cherian <itsajin@gmail.com> wrote:\n> > >\n> > > On Thu, Aug 26, 2021 at 1:06 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > >\n> > > >\n> > > > You have a point but if we see the below logs, it seems the second\n> > > > walsender (#step6) seemed to exited before the first walsender\n> > > > (#step4).\n> > > >\n> > > > 2021-08-15 18:44:38.041 CEST [16475:10] tap_sub LOG: disconnection:\n> > > > session time: 0:00:00.036 user=nm database=postgres host=[local]\n> > > > 2021-08-15 18:44:38.043 CEST [16336:14] tap_sub LOG: disconnection:\n> > > > session time: 0:00:06.367 user=nm database=postgres host=[local]\n> > > >\n> > > > Isn't it possible that pid is cleared in the other order due to which\n> > > > we are seeing this problem?\n> > >\n> > > If the pid is cleared in the other order, wouldn't the query [1] return a false?\n> > >\n> > > [1] - \" SELECT pid != 16336 FROM pg_stat_replication WHERE\n> > > application_name = 'tap_sub';\"\n> > >\n> >\n> > I think it should return true because pid for 16336 is cleared first\n> > and the remaining one will be 16475.\n>\n> Yes, that was what I explained as well. 16336 is PID 'a' (first\n> walsender) in my explanation. The first walsender should\n> be cleared first for this theory to work.\n\nI think that it’s possible that the orders of the process writing\ndisconnections logs and setting 0 to walsender's pid are mismatched.\nWe set 0 to walsender's pid in WalSndKill() that is called during\non_shmem_exit callback. Once we set 0, pg_stat_replication doesn't\nshow the entry. On the other hand, disconnections logs are written by\nlog_disconnections() that is called during on_proc_exit callback. That\nis, the following sequence could happen:\n\n1. the second walsender (pid = 16475) raises an error as the slot is\nalready active (held by the first walsender).\n2. the first walsender (pid = 16336) clears its pid on the shmem.\n3. the polling query checks the walsender’s pid, and returns true\n(since there is only the second walsender now).\n4. the second walsender clears its pid on the shmem.\n5. the second walsender writes disconnection log.\n6. the first walsender writes disconneciton log.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Thu, 26 Aug 2021 13:45:21 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Thu, Aug 26, 2021 at 2:45 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n\n> I think that it’s possible that the orders of the process writing\n> disconnections logs and setting 0 to walsender's pid are mismatched.\n> We set 0 to walsender's pid in WalSndKill() that is called during\n> on_shmem_exit callback. Once we set 0, pg_stat_replication doesn't\n> show the entry. On the other hand, disconnections logs are written by\n> log_disconnections() that is called during on_proc_exit callback. That\n> is, the following sequence could happen:\n>\n> 1. the second walsender (pid = 16475) raises an error as the slot is\n> already active (held by the first walsender).\n> 2. the first walsender (pid = 16336) clears its pid on the shmem.\n> 3. the polling query checks the walsender’s pid, and returns true\n> (since there is only the second walsender now).\n> 4. the second walsender clears its pid on the shmem.\n> 5. the second walsender writes disconnection log.\n> 6. the first walsender writes disconneciton log.\n\nI agree with this.\n\nAttaching a patch on head that modifies this particular script to also\nconsider the state of the walsender.\n\nregards,\nAjin Cherian\nFujitsu Australia", "msg_date": "Thu, 26 Aug 2021 20:58:40 +1000", "msg_from": "Ajin Cherian <itsajin@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Thu, Aug 26, 2021 at 4:28 PM Ajin Cherian <itsajin@gmail.com> wrote:\n>\n> On Thu, Aug 26, 2021 at 2:45 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> Attaching a patch on head that modifies this particular script to also\n> consider the state of the walsender.\n>\n\nI think the fix is correct but similar changes are required in\n022_twophase_cascade.pl as well (search for $oldpid in tests). I am\nnot completely sure but I think it is better to make this test change\nin back branches as well to make it stable and reduce such random\nbuild farm failures.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Fri, 27 Aug 2021 10:59:40 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Fri, Aug 27, 2021 at 3:29 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n>\n> I think the fix is correct but similar changes are required in\n> 022_twophase_cascade.pl as well (search for $oldpid in tests). I am\n> not completely sure but I think it is better to make this test change\n> in back branches as well to make it stable and reduce such random\n> build farm failures.\n\nI have made the changes in 022_twophase_cascade.pl for HEAD as well as\npatches for older branches.\n\nregards,\nAjin Cherian\nFujitsu Australia", "msg_date": "Fri, 27 Aug 2021 21:03:17 +1000", "msg_from": "Ajin Cherian <itsajin@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Fri, Aug 27, 2021 at 4:33 PM Ajin Cherian <itsajin@gmail.com> wrote:\n>\n> On Fri, Aug 27, 2021 at 3:29 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> >\n> > I think the fix is correct but similar changes are required in\n> > 022_twophase_cascade.pl as well (search for $oldpid in tests). I am\n> > not completely sure but I think it is better to make this test change\n> > in back branches as well to make it stable and reduce such random\n> > build farm failures.\n>\n> I have made the changes in 022_twophase_cascade.pl for HEAD as well as\n> patches for older branches.\n>\n\nIsn't it better to check the streaming state when we are fetching\noldpid? If we don't add, then I suspect that the next time someone\nadding tests on similar lines might get confused about where to check\nthe state and where not. Also, if you agree, add some comments before\nthe test on why it is important to check states.\n\nFor ex., in below queries, the queries used for $oldpid.\nmy $oldpid = $node_publisher->safe_psql('postgres',\n \"SELECT pid FROM pg_stat_replication WHERE application_name =\n'tap_sub';\"\n);\n$node_subscriber->safe_psql('postgres',\n \"ALTER SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr\nsslmode=disable'\"\n);\n$node_publisher->poll_query_until('postgres',\n \"SELECT pid != $oldpid FROM pg_stat_replication WHERE\napplication_name = 'tap_sub' AND state = 'streaming';\"\n) or die \"Timed out while waiting for apply to restart\";\n\n$oldpid = $node_publisher->safe_psql('postgres',\n \"SELECT pid FROM pg_stat_replication WHERE application_name =\n'tap_sub';\"\n);\n$node_subscriber->safe_psql('postgres',\n \"ALTER SUBSCRIPTION tap_sub SET PUBLICATION tap_pub_ins_only\nWITH (copy_data = false)\"\n);\n$node_publisher->poll_query_until('postgres',\n \"SELECT pid != $oldpid FROM pg_stat_replication WHERE\napplication_name = 'tap_sub' AND state = 'streaming';\"\n\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Mon, 30 Aug 2021 15:22:46 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Mon, Aug 30, 2021 at 7:52 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> Isn't it better to check the streaming state when we are fetching\n> oldpid? If we don't add, then I suspect that the next time someone\n> adding tests on similar lines might get confused about where to check\n> the state and where not. Also, if you agree, add some comments before\n> the test on why it is important to check states.\n>\n> For ex., in below queries, the queries used for $oldpid.\n> my $oldpid = $node_publisher->safe_psql('postgres',\n> \"SELECT pid FROM pg_stat_replication WHERE application_name =\n> 'tap_sub';\"\n> );\n> $node_subscriber->safe_psql('postgres',\n> \"ALTER SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr\n> sslmode=disable'\"\n> );\n> $node_publisher->poll_query_until('postgres',\n> \"SELECT pid != $oldpid FROM pg_stat_replication WHERE\n> application_name = 'tap_sub' AND state = 'streaming';\"\n> ) or die \"Timed out while waiting for apply to restart\";\n>\n> $oldpid = $node_publisher->safe_psql('postgres',\n> \"SELECT pid FROM pg_stat_replication WHERE application_name =\n> 'tap_sub';\"\n> );\n> $node_subscriber->safe_psql('postgres',\n> \"ALTER SUBSCRIPTION tap_sub SET PUBLICATION tap_pub_ins_only\n> WITH (copy_data = false)\"\n> );\n> $node_publisher->poll_query_until('postgres',\n> \"SELECT pid != $oldpid FROM pg_stat_replication WHERE\n> application_name = 'tap_sub' AND state = 'streaming';\"\n>\n\nI have made the above changes on HEAD.\n\nregards,\nAjin Cherian\nFujitsu Australia", "msg_date": "Mon, 30 Aug 2021 22:18:06 +1000", "msg_from": "Ajin Cherian <itsajin@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Mon, Aug 30, 2021 at 5:48 PM Ajin Cherian <itsajin@gmail.com> wrote:\n>\n> On Mon, Aug 30, 2021 at 7:52 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> I have made the above changes on HEAD.\n>\n\nThanks, this looks mostly good to me. I'll push and backpatch this\ntomorrow unless you or someone else thinks otherwise.\n\nMinor comments\n==============\n1.\n $oldpid = $node_publisher->safe_psql('postgres',\n- \"SELECT pid FROM pg_stat_replication WHERE application_name = 'tap_sub';\"\n+ \"SELECT pid FROM pg_stat_replication WHERE application_name =\n'tap_sub' AND state = 'streaming';;\"\n );\n\nAn extra semicolon at the end of the statement.\n\n2.\n+# restart of subscription workers. We check the state along with\napplication_name\n+# to ensure that the walsender is (re)started.\n\nIt is better to keep application_name in an above comment in the\nsecond line as that will make this line looks a bit more consistent\nwith other comments.\n\n3. In commit message, the text: \"The reason was that the test was\nassuming the walsender started before it reaches the 'streaming' state\nand The check to test whether the subscription workers were restarting\nafter a change in the subscription was failing.\" seems to be\nrepeated/redundant.\n\n4. Kindly submit the patches for back-branches.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Tue, 31 Aug 2021 08:41:41 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Tue, Aug 31, 2021 at 12:11 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Mon, Aug 30, 2021 at 5:48 PM Ajin Cherian <itsajin@gmail.com> wrote:\n> >\n> > On Mon, Aug 30, 2021 at 7:52 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > I have made the above changes on HEAD.\n> >\n>\n> Thanks, this looks mostly good to me. I'll push and backpatch this\n> tomorrow unless you or someone else thinks otherwise.\n>\n> Minor comments\n> ==============\n> 1.\n> $oldpid = $node_publisher->safe_psql('postgres',\n> - \"SELECT pid FROM pg_stat_replication WHERE application_name = 'tap_sub';\"\n> + \"SELECT pid FROM pg_stat_replication WHERE application_name =\n> 'tap_sub' AND state = 'streaming';;\"\n> );\n>\n> An extra semicolon at the end of the statement.\n>\n> 2.\n> +# restart of subscription workers. We check the state along with\n> application_name\n> +# to ensure that the walsender is (re)started.\n>\n> It is better to keep application_name in an above comment in the\n> second line as that will make this line looks a bit more consistent\n> with other comments.\n>\n> 3. In commit message, the text: \"The reason was that the test was\n> assuming the walsender started before it reaches the 'streaming' state\n> and The check to test whether the subscription workers were restarting\n> after a change in the subscription was failing.\" seems to be\n> repeated/redundant.\n>\n> 4. Kindly submit the patches for back-branches.\n\nThe patch with the above comments looks good to me. One minor\nsuggestion is to change the two messages of \"die\" to make the\ninvestigation a bit easier. For example,\n\n$node_publisher->poll_query_until('postgres',\n \"SELECT pid != $oldpid FROM pg_stat_replication WHERE\napplication_name = 'tap_sub' AND state = 'streaming';\"\n) or die \"Timed out while waiting for apply to restart after changing\nCONNECTION\";\n\nand\n\n$node_publisher->poll_query_until('postgres',\n \"SELECT pid != $oldpid FROM pg_stat_replication WHERE\napplication_name = 'tap_sub' AND state = 'streaming';\"\n) or die \"Timed out while waiting for apply to restart after changing\nPUBLICATION\";\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Tue, 31 Aug 2021 14:47:10 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Tue, Aug 31, 2021 at 3:47 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Tue, Aug 31, 2021 at 12:11 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > On Mon, Aug 30, 2021 at 5:48 PM Ajin Cherian <itsajin@gmail.com> wrote:\n> > >\n> > > On Mon, Aug 30, 2021 at 7:52 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > >\n> > > I have made the above changes on HEAD.\n> > >\n> >\n> > Thanks, this looks mostly good to me. I'll push and backpatch this\n> > tomorrow unless you or someone else thinks otherwise.\n> >\n> > Minor comments\n> > ==============\n> > 1.\n> > $oldpid = $node_publisher->safe_psql('postgres',\n> > - \"SELECT pid FROM pg_stat_replication WHERE application_name = 'tap_sub';\"\n> > + \"SELECT pid FROM pg_stat_replication WHERE application_name =\n> > 'tap_sub' AND state = 'streaming';;\"\n> > );\n> >\n> > An extra semicolon at the end of the statement.\n> >\n> > 2.\n> > +# restart of subscription workers. We check the state along with\n> > application_name\n> > +# to ensure that the walsender is (re)started.\n> >\n> > It is better to keep application_name in an above comment in the\n> > second line as that will make this line looks a bit more consistent\n> > with other comments.\n> >\n> > 3. In commit message, the text: \"The reason was that the test was\n> > assuming the walsender started before it reaches the 'streaming' state\n> > and The check to test whether the subscription workers were restarting\n> > after a change in the subscription was failing.\" seems to be\n> > repeated/redundant.\n> >\n> > 4. Kindly submit the patches for back-branches.\n>\n> The patch with the above comments looks good to me. One minor\n> suggestion is to change the two messages of \"die\" to make the\n> investigation a bit easier. For example,\n>\n> $node_publisher->poll_query_until('postgres',\n> \"SELECT pid != $oldpid FROM pg_stat_replication WHERE\n> application_name = 'tap_sub' AND state = 'streaming';\"\n> ) or die \"Timed out while waiting for apply to restart after changing\n> CONNECTION\";\n>\n> and\n>\n> $node_publisher->poll_query_until('postgres',\n> \"SELECT pid != $oldpid FROM pg_stat_replication WHERE\n> application_name = 'tap_sub' AND state = 'streaming';\"\n> ) or die \"Timed out while waiting for apply to restart after changing\n> PUBLICATION\";\n>\n> Regards,\n>\n\nThanks Masahiko-san. I have included this change and made a new patch-set.\n\nHi Amit,\n\nI have included your comments as well and also attached the patches\nfor the back-branches.\n\nregards,\nAjin Cherian\nFujitsu Australia", "msg_date": "Tue, 31 Aug 2021 22:43:45 +1000", "msg_from": "Ajin Cherian <itsajin@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" }, { "msg_contents": "On Tue, Aug 31, 2021 at 6:13 PM Ajin Cherian <itsajin@gmail.com> wrote:\n>\n> On Tue, Aug 31, 2021 at 3:47 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> Thanks Masahiko-san. I have included this change and made a new patch-set.\n>\n> Hi Amit,\n>\n> I have included your comments as well and also attached the patches\n> for the back-branches.\n>\n\nYou forgot to make changes in 022_twophase_cascade.pl in the head\nversion patch. I have made the required changes and pushed it. Thanks\nto you and Sawada-San for diagnosing and fixing this problem.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n", "msg_date": "Wed, 1 Sep 2021 13:54:00 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Failure of subscription tests with topminnow" } ]
[ { "msg_contents": "Hi Hackers,\n\nRecently, a issue has been bothering me, This is about conditional push-down in SQL.\nI use cases from regression testing as an example.\nI found that the conditions (B =1) can be pushed down into the subquery, However, it cannot be pushed down to sublink/subplan.\nIf a sublink/subplan clause contains a partition table, it can be useful to get the conditions for pruning.\nSo, is it worth pushing conditions to sublink/subplan?\nAnybody have any ideas?\n\n\nregards,\nWenjing\n\n\nexample:\ncreate table p (a int, b int, c int) partition by list (a);\ncreate table p1 partition of p for values in (1);\ncreate table p2 partition of p for values in (2);\ncreate table q (a int, b int, c int) partition by list (a);\ncreate table q1 partition of q for values in (1) partition by list (b);\ncreate table q11 partition of q1 for values in (1) partition by list (c);\ncreate table q111 partition of q11 for values in (1);\ncreate table q2 partition of q for values in (2) partition by list (b);\ncreate table q21 partition of q2 for values in (1);\ncreate table q22 partition of q2 for values in (2);\ninsert into q22 values (2, 2, 3);\n\n\npostgres-# explain (costs off)\npostgres-# select temp.b from \npostgres-# (\npostgres(# select a,b from ab x where x.a = 1\npostgres(# union all \npostgres(# (values(1,1)) \npostgres(# ) temp,\npostgres-# ab y\npostgres-# where y.b = temp.b and y.a = 1 and y.b=1;\n QUERY PLAN \n---------------------------------------------------\n Nested Loop\n -> Seq Scan on ab_a1_b1 y\n Filter: ((b = 1) AND (a = 1))\n -> Append\n -> Subquery Scan on \"*SELECT* 1\"\n -> Seq Scan on ab_a1_b1 x\n Filter: ((a = 1) AND (b = 1))\n -> Result\n(8 rows)\n\nThe conditions (B =1) can be pushed down into the subquery.\n\npostgres=# explain (costs off)\npostgres-# select\npostgres-# y.a,\npostgres-# (Select x.b from ab x where y.a =x.a and y.b=x.b) as b\npostgres-# from ab y where a = 1 and b = 1;\n QUERY PLAN \n---------------------------------------------------\n Seq Scan on ab_a1_b1 y\n Filter: ((a = 1) AND (b = 1))\n SubPlan 1\n -> Append\n -> Seq Scan on ab_a1_b1 x_1\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a1_b2 x_2\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a1_b3 x_3\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a2_b1 x_4\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a2_b2 x_5\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a2_b3 x_6\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a3_b1 x_7\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a3_b2 x_8\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a3_b3 x_9\n Filter: ((y.a = a) AND (y.b = b))\n(22 rows)\n\nThe conditions (B = 1 and A = 1) cannot be pushed down to sublink/subplan in targetlist.\n\npostgres=# explain (costs off)\npostgres-# select y.a\npostgres-# from ab y \npostgres-# where\npostgres-# (select x.a > x.b from ab x where y.a =x.a and y.b=x.b) and\npostgres-# y.a = 1 and y.b = 1;\n QUERY PLAN \n---------------------------------------------------\n Seq Scan on ab_a1_b1 y\n Filter: ((a = 1) AND (b = 1) AND (SubPlan 1))\n SubPlan 1\n -> Append\n -> Seq Scan on ab_a1_b1 x_1\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a1_b2 x_2\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a1_b3 x_3\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a2_b1 x_4\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a2_b2 x_5\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a2_b3 x_6\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a3_b1 x_7\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a3_b2 x_8\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a3_b3 x_9\n Filter: ((y.a = a) AND (y.b = b))\n(22 rows)\n\nThe conditions (B=1 and A=1) cannot be pushed down to sublink/subplan in where clause.", "msg_date": "Mon, 16 Aug 2021 17:15:05 +0800", "msg_from": "Wenjing <wenjing.zwj@alibaba-inc.com>", "msg_from_op": true, "msg_subject": "Is it worth pushing conditions to sublink/subplan?" }, { "msg_contents": "> 2021年8月16日 17:15,Wenjing <wenjing.zwj@alibaba-inc.com> 写道:\n> \n> Hi Hackers,\n> \n> Recently, a issue has been bothering me, This is about conditional push-down in SQL.\n> I use cases from regression testing as an example.\n> I found that the conditions (B =1) can be pushed down into the subquery, However, it cannot be pushed down to sublink/subplan.\n> If a sublink/subplan clause contains a partition table, it can be useful to get the conditions for pruning.\n> So, is it worth pushing conditions to sublink/subplan?\n> Anybody have any ideas?\n> \n> \n> regards,\n> Wenjing\n> \n> \n> example:\n> create table p (a int, b int, c int) partition by list (a);\n> create table p1 partition of p for values in (1);\n> create table p2 partition of p for values in (2);\n> create table q (a int, b int, c int) partition by list (a);\n> create table q1 partition of q for values in (1) partition by list (b);\n> create table q11 partition of q1 for values in (1) partition by list (c);\n> create table q111 partition of q11 for values in (1);\n> create table q2 partition of q for values in (2) partition by list (b);\n> create table q21 partition of q2 for values in (1);\n> create table q22 partition of q2 for values in (2);\n> insert into q22 values (2, 2, 3);\nSorry, I messed up the structure of the table.\nIt is should be:\ncreate table ab (a int not null, b int not null) partition by list (a);\ncreate table ab_a2 partition of ab for values in(2) partition by list (b);\ncreate table ab_a2_b1 partition of ab_a2 for values in (1);\ncreate table ab_a2_b2 partition of ab_a2 for values in (2);\ncreate table ab_a2_b3 partition of ab_a2 for values in (3);\ncreate table ab_a1 partition of ab for values in(1) partition by list (b);\ncreate table ab_a1_b1 partition of ab_a1 for values in (1);\ncreate table ab_a1_b2 partition of ab_a1 for values in (2);\ncreate table ab_a1_b3 partition of ab_a1 for values in (3);\ncreate table ab_a3 partition of ab for values in(3) partition by list (b);\ncreate table ab_a3_b1 partition of ab_a3 for values in (1);\ncreate table ab_a3_b2 partition of ab_a3 for values in (2);\ncreate table ab_a3_b3 partition of ab_a3 for values in (3);\n\n\n> \n> \n> postgres-# explain (costs off)\n> postgres-# select temp.b from \n> postgres-# (\n> postgres(# select a,b from ab x where x.a = 1\n> postgres(# union all \n> postgres(# (values(1,1)) \n> postgres(# ) temp,\n> postgres-# ab y\n> postgres-# where y.b = temp.b and y.a = 1 and y.b=1;\n> QUERY PLAN \n> ---------------------------------------------------\n> Nested Loop\n> -> Seq Scan on ab_a1_b1 y\n> Filter: ((b = 1) AND (a = 1))\n> -> Append\n> -> Subquery Scan on \"*SELECT* 1\"\n> -> Seq Scan on ab_a1_b1 x\n> Filter: ((a = 1) AND (b = 1))\n> -> Result\n> (8 rows)\n> \n> The conditions (B =1) can be pushed down into the subquery.\n> \n> postgres=# explain (costs off)\n> postgres-# select\n> postgres-# y.a,\n> postgres-# (Select x.b from ab x where y.a =x.a and y.b=x.b) as b\n> postgres-# from ab y where a = 1 and b = 1;\n> QUERY PLAN \n> ---------------------------------------------------\n> Seq Scan on ab_a1_b1 y\n> Filter: ((a = 1) AND (b = 1))\n> SubPlan 1\n> -> Append\n> -> Seq Scan on ab_a1_b1 x_1\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a1_b2 x_2\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a1_b3 x_3\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b1 x_4\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b2 x_5\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b3 x_6\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b1 x_7\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b2 x_8\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b3 x_9\n> Filter: ((y.a = a) AND (y.b = b))\n> (22 rows)\n> \n> The conditions (B = 1 and A = 1) cannot be pushed down to sublink/subplan in targetlist.\n> \n> postgres=# explain (costs off)\n> postgres-# select y.a\n> postgres-# from ab y \n> postgres-# where\n> postgres-# (select x.a > x.b from ab x where y.a =x.a and y.b=x.b) and\n> postgres-# y.a = 1 and y.b = 1;\n> QUERY PLAN \n> ---------------------------------------------------\n> Seq Scan on ab_a1_b1 y\n> Filter: ((a = 1) AND (b = 1) AND (SubPlan 1))\n> SubPlan 1\n> -> Append\n> -> Seq Scan on ab_a1_b1 x_1\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a1_b2 x_2\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a1_b3 x_3\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b1 x_4\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b2 x_5\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b3 x_6\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b1 x_7\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b2 x_8\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b3 x_9\n> Filter: ((y.a = a) AND (y.b = b))\n> (22 rows)\n> \n> The conditions (B=1 and A=1) cannot be pushed down to sublink/subplan in where clause.\n> \n> \n>", "msg_date": "Tue, 17 Aug 2021 10:30:41 +0800", "msg_from": "Wenjing <wenjing.zwj@alibaba-inc.com>", "msg_from_op": true, "msg_subject": "Re: Is it worth pushing conditions to sublink/subplan?" }, { "msg_contents": "Indeed, this may be useful for partition pruning.\nI am also curious about why this has not been achieved.\n\nWenjing <wenjing.zwj@alibaba-inc.com> 于2021年8月23日周一 上午10:46写道:\n\n> Hi Hackers,\n>\n> Recently, a issue has been bothering me, This is about conditional\n> push-down in SQL.\n> I use cases from regression testing as an example.\n> I found that the conditions (B =1) can be pushed down into the\n> subquery, However, it cannot be pushed down to sublink/subplan.\n> If a sublink/subplan clause contains a partition table, it can be useful\n> to get the conditions for pruning.\n> So, is it worth pushing conditions to sublink/subplan?\n> Anybody have any ideas?\n>\n>\n> regards,\n> Wenjing\n>\n>\n> example:\n> create table p (a int, b int, c int) partition by list (a);\n> create table p1 partition of p for values in (1);\n> create table p2 partition of p for values in (2);\n> create table q (a int, b int, c int) partition by list (a);\n> create table q1 partition of q for values in (1) partition by list (b);\n> create table q11 partition of q1 for values in (1) partition by list (c);\n> create table q111 partition of q11 for values in (1);\n> create table q2 partition of q for values in (2) partition by list (b);\n> create table q21 partition of q2 for values in (1);\n> create table q22 partition of q2 for values in (2);\n> insert into q22 values (2, 2, 3);\n>\n>\n> postgres-# explain (costs off)\n> postgres-# select temp.b from\n> postgres-# (\n> postgres(# select a,b from ab x where x.a = 1\n> postgres(# union all\n> postgres(# (values(1,1))\n> postgres(# ) temp,\n> postgres-# ab y\n> postgres-# where y.b = temp.b and y.a = 1 and y.b=1;\n> QUERY PLAN\n> ---------------------------------------------------\n> Nested Loop\n> -> Seq Scan on ab_a1_b1 y\n> Filter: ((b = 1) AND (a = 1))\n> -> Append\n> -> Subquery Scan on \"*SELECT* 1\"\n> -> Seq Scan on ab_a1_b1 x\n> Filter: ((a = 1) AND (b = 1))\n> -> Result\n> (8 rows)\n>\n> The conditions (B =1) can be pushed down into the subquery.\n>\n> postgres=# explain (costs off)\n> postgres-# select\n> postgres-# y.a,\n> postgres-# (Select x.b from ab x where y.a =x.a and y.b=x.b) as b\n> postgres-# from ab y where a = 1 and b = 1;\n> QUERY PLAN\n> ---------------------------------------------------\n> Seq Scan on ab_a1_b1 y\n> Filter: ((a = 1) AND (b = 1))\n> SubPlan 1\n> -> Append\n> -> Seq Scan on ab_a1_b1 x_1\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a1_b2 x_2\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a1_b3 x_3\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b1 x_4\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b2 x_5\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b3 x_6\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b1 x_7\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b2 x_8\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b3 x_9\n> Filter: ((y.a = a) AND (y.b = b))\n> (22 rows)\n>\n> The conditions (B = 1 and A = 1) cannot be pushed down to sublink/subplan\n> in targetlist.\n>\n> postgres=# explain (costs off)\n> postgres-# select y.a\n> postgres-# from ab y\n> postgres-# where\n> postgres-# (select x.a > x.b from ab x where y.a =x.a and y.b=x.b) and\n> postgres-# y.a = 1 and y.b = 1;\n> QUERY PLAN\n> ---------------------------------------------------\n> Seq Scan on ab_a1_b1 y\n> Filter: ((a = 1) AND (b = 1) AND (SubPlan 1))\n> SubPlan 1\n> -> Append\n> -> Seq Scan on ab_a1_b1 x_1\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a1_b2 x_2\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a1_b3 x_3\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b1 x_4\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b2 x_5\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b3 x_6\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b1 x_7\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b2 x_8\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b3 x_9\n> Filter: ((y.a = a) AND (y.b = b))\n> (22 rows)\n>\n> The conditions (B=1 and A=1) cannot be pushed down to sublink/subplan in\n> where clause.\n>\n>\n>\n>\n\nIndeed, this may be useful for partition pruning.I am also curious about why this has not been achieved.Wenjing <wenjing.zwj@alibaba-inc.com> 于2021年8月23日周一 上午10:46写道:Hi Hackers,Recently, a issue has been bothering me, This is about conditional push-down in SQL.I use cases from regression testing as an example.I found that the conditions  (B =1)  can be pushed down into the subquery, However, it cannot be pushed down to sublink/subplan.If a sublink/subplan clause contains a partition table, it can be useful to get the conditions for pruning.So, is it worth pushing conditions to sublink/subplan?Anybody have any ideas?regards,Wenjingexample:create table p (a int, b int, c int) partition by list (a);create table p1 partition of p for values in (1);create table p2 partition of p for values in (2);create table q (a int, b int, c int) partition by list (a);create table q1 partition of q for values in (1) partition by list (b);create table q11 partition of q1 for values in (1) partition by list (c);create table q111 partition of q11 for values in (1);create table q2 partition of q for values in (2) partition by list (b);create table q21 partition of q2 for values in (1);create table q22 partition of q2 for values in (2);insert into q22 values (2, 2, 3);postgres-# explain (costs off)postgres-# select temp.b  from postgres-# (postgres(# select a,b from ab x where x.a = 1postgres(# union all postgres(# (values(1,1)) postgres(# ) temp,postgres-# ab ypostgres-# where  y.b = temp.b and y.a = 1 and y.b=1;                    QUERY PLAN                     --------------------------------------------------- Nested Loop   ->  Seq Scan on ab_a1_b1 y         Filter: ((b = 1) AND (a = 1))   ->  Append         ->  Subquery Scan on \"*SELECT* 1\"               ->  Seq Scan on ab_a1_b1 x                     Filter: ((a = 1) AND (b = 1))         ->  Result(8 rows)The conditions  (B =1)  can be pushed down into the subquery.postgres=# explain (costs off)postgres-# selectpostgres-# y.a,postgres-# (Select x.b from ab x where y.a =x.a and y.b=x.b) as bpostgres-# from ab y where a = 1 and b = 1;                    QUERY PLAN                     --------------------------------------------------- Seq Scan on ab_a1_b1 y   Filter: ((a = 1) AND (b = 1))   SubPlan 1     ->  Append           ->  Seq Scan on ab_a1_b1 x_1                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a1_b2 x_2                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a1_b3 x_3                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a2_b1 x_4                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a2_b2 x_5                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a2_b3 x_6                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a3_b1 x_7                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a3_b2 x_8                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a3_b3 x_9                 Filter: ((y.a = a) AND (y.b = b))(22 rows)The conditions (B = 1 and A = 1) cannot be pushed down to sublink/subplan in targetlist.postgres=# explain (costs off)postgres-# select y.apostgres-# from ab y postgres-# wherepostgres-# (select x.a > x.b from ab x where y.a =x.a and y.b=x.b) andpostgres-# y.a = 1 and y.b = 1;                    QUERY PLAN                     --------------------------------------------------- Seq Scan on ab_a1_b1 y   Filter: ((a = 1) AND (b = 1) AND (SubPlan 1))   SubPlan 1     ->  Append           ->  Seq Scan on ab_a1_b1 x_1                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a1_b2 x_2                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a1_b3 x_3                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a2_b1 x_4                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a2_b2 x_5                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a2_b3 x_6                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a3_b1 x_7                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a3_b2 x_8                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a3_b3 x_9                 Filter: ((y.a = a) AND (y.b = b))(22 rows)The conditions  (B=1 and A=1)  cannot be pushed down to sublink/subplan in where clause.", "msg_date": "Mon, 23 Aug 2021 10:49:36 +0800", "msg_from": "li jie <ggysxcq@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Is it worth pushing conditions to sublink/subplan?" }, { "msg_contents": "I tested it the way you said and increased the number of sub-tables.\nI created a hash partition table of 1000 sub-tables.\nTest according to your first SQL, the optimizer cuts the unnecessary\nsub-tables well.\nYou can see the plan:\n\npostgres=# explain analyze\n\npostgres-# select temp.p1 from\n\npostgres-# (\n\npostgres(# select p1,p2 from test1.test1hashtable x where x.p1 = '1'\n\npostgres(# union all\n\npostgres(# (values('1','1'))\n\npostgres(# ) temp,\n\npostgres-# test1.test1hashtable y\n\npostgres-# where y.p2 = temp.p2 and y.p1 = '1' and y.p1='1';\n\n QUERY PLAN\n\n\n---------------------------------------------------------------------------------------------------------------------\n\n Nested Loop (cost=0.00..25.55 rows=1 width=32) (actual time=0.004..0.004\nrows=0 loops=1)\n\n Join Filter: (x.p2 = y.p2)\n\n -> Seq Scan on test1hashtable826 y (cost=0.00..12.75 rows=1 width=32)\n(actual time=0.002..0.002 rows=0 loops=1)\n\n Filter: (p1 = '1'::text)\n\n -> Append (cost=0.00..12.78 rows=2 width=64) (never executed)\n\n -> Seq Scan on test1hashtable826 x (cost=0.00..12.75 rows=1\nwidth=64) (never executed)\n\n Filter: (p1 = '1'::text)\n\n -> Result (cost=0.00..0.01 rows=1 width=64) (never executed)\n\n Planning Time: 0.158 ms\n\n Execution Time: 0.022 ms\n\n(10 rows)\n\n\nBut when the second one runs, the planning time reaches 13.942ms.\nThe plan:\n\npostgres=# explain analyze\n\npostgres-# select\n\npostgres-# y.p1,\n\npostgres-# (Select x.p2 from test1.test1hashtable x where y.p1 =x.p1 and\ny.p2=x.p2) as b\n\npostgres-# from test1.test1hashtable y where p1 = '1' and p2 = '1';\n\n QUERY PLAN\n\n\n------------------------------------------------------------------------------------------------------------------\n\n Seq Scan on test1hashtable826 y (cost=0.00..13318.30 rows=1 width=64)\n(actual time=0.004..0.047 rows=0 loops=1)\n\n Filter: ((p1 = '1'::text) AND (p2 = '1'::text))\n\n SubPlan 1\n\n -> Append (cost=0.00..13305.00 rows=1000 width=32) (never executed)\n\n -> Seq Scan on test1hashtable1 x_1 (cost=0.00..13.30 rows=1\nwidth=32) (never executed)\n\n Filter: ((y.p1 = p1) AND (y.p2 = p2))\n\n -> Seq Scan on test1hashtable1000 x_1000 (cost=0.00..13.30\nrows=1 width=32) (never executed)\n\n Filter: ((y.p1 = p1) AND (y.p2 = p2))\n\n Planning Time: 13.942 ms\n\n Execution Time: 4.899 ms\n\n(2006 rows)\n\n\nThis is a very worthwhile thing to do. In a relatively large business\nsystem, a large number of partition tables and high concurrency are often\nused. If the planning time is too long, this will greatly affect the\nbusiness.\n\n\nregards,\n\nShawn.\n\nWenjing <wenjing.zwj@alibaba-inc.com> 于2021年8月17日周二 上午10:31写道:\n\n>\n>\n> 2021年8月16日 17:15,Wenjing <wenjing.zwj@alibaba-inc.com> 写道:\n>\n> Hi Hackers,\n>\n> Recently, a issue has been bothering me, This is about conditional\n> push-down in SQL.\n> I use cases from regression testing as an example.\n> I found that the conditions (B =1) can be pushed down into the\n> subquery, However, it cannot be pushed down to sublink/subplan.\n> If a sublink/subplan clause contains a partition table, it can be useful\n> to get the conditions for pruning.\n> So, is it worth pushing conditions to sublink/subplan?\n> Anybody have any ideas?\n>\n>\n> regards,\n> Wenjing\n>\n>\n> example:\n> create table p (a int, b int, c int) partition by list (a);\n> create table p1 partition of p for values in (1);\n> create table p2 partition of p for values in (2);\n> create table q (a int, b int, c int) partition by list (a);\n> create table q1 partition of q for values in (1) partition by list (b);\n> create table q11 partition of q1 for values in (1) partition by list (c);\n> create table q111 partition of q11 for values in (1);\n> create table q2 partition of q for values in (2) partition by list (b);\n> create table q21 partition of q2 for values in (1);\n> create table q22 partition of q2 for values in (2);\n> insert into q22 values (2, 2, 3);\n>\n> Sorry, I messed up the structure of the table.\n> It is should be:\n> create table ab (a int not null, b int not null) partition by list (a);\n> create table ab_a2 partition of ab for values in(2) partition by list (b);\n> create table ab_a2_b1 partition of ab_a2 for values in (1);\n> create table ab_a2_b2 partition of ab_a2 for values in (2);\n> create table ab_a2_b3 partition of ab_a2 for values in (3);\n> create table ab_a1 partition of ab for values in(1) partition by list (b);\n> create table ab_a1_b1 partition of ab_a1 for values in (1);\n> create table ab_a1_b2 partition of ab_a1 for values in (2);\n> create table ab_a1_b3 partition of ab_a1 for values in (3);\n> create table ab_a3 partition of ab for values in(3) partition by list (b);\n> create table ab_a3_b1 partition of ab_a3 for values in (1);\n> create table ab_a3_b2 partition of ab_a3 for values in (2);\n> create table ab_a3_b3 partition of ab_a3 for values in (3);\n>\n>\n>\n>\n> postgres-# explain (costs off)\n> postgres-# select temp.b from\n> postgres-# (\n> postgres(# select a,b from ab x where x.a = 1\n> postgres(# union all\n> postgres(# (values(1,1))\n> postgres(# ) temp,\n> postgres-# ab y\n> postgres-# where y.b = temp.b and y.a = 1 and y.b=1;\n> QUERY PLAN\n> ---------------------------------------------------\n> Nested Loop\n> -> Seq Scan on ab_a1_b1 y\n> Filter: ((b = 1) AND (a = 1))\n> -> Append\n> -> Subquery Scan on \"*SELECT* 1\"\n> -> Seq Scan on ab_a1_b1 x\n> Filter: ((a = 1) AND (b = 1))\n> -> Result\n> (8 rows)\n>\n> The conditions (B =1) can be pushed down into the subquery.\n>\n> postgres=# explain (costs off)\n> postgres-# select\n> postgres-# y.a,\n> postgres-# (Select x.b from ab x where y.a =x.a and y.b=x.b) as b\n> postgres-# from ab y where a = 1 and b = 1;\n> QUERY PLAN\n> ---------------------------------------------------\n> Seq Scan on ab_a1_b1 y\n> Filter: ((a = 1) AND (b = 1))\n> SubPlan 1\n> -> Append\n> -> Seq Scan on ab_a1_b1 x_1\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a1_b2 x_2\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a1_b3 x_3\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b1 x_4\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b2 x_5\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b3 x_6\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b1 x_7\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b2 x_8\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b3 x_9\n> Filter: ((y.a = a) AND (y.b = b))\n> (22 rows)\n>\n> The conditions (B = 1 and A = 1) cannot be pushed down to sublink/subplan\n> in targetlist.\n>\n> postgres=# explain (costs off)\n> postgres-# select y.a\n> postgres-# from ab y\n> postgres-# where\n> postgres-# (select x.a > x.b from ab x where y.a =x.a and y.b=x.b) and\n> postgres-# y.a = 1 and y.b = 1;\n> QUERY PLAN\n> ---------------------------------------------------\n> Seq Scan on ab_a1_b1 y\n> Filter: ((a = 1) AND (b = 1) AND (SubPlan 1))\n> SubPlan 1\n> -> Append\n> -> Seq Scan on ab_a1_b1 x_1\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a1_b2 x_2\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a1_b3 x_3\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b1 x_4\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b2 x_5\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a2_b3 x_6\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b1 x_7\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b2 x_8\n> Filter: ((y.a = a) AND (y.b = b))\n> -> Seq Scan on ab_a3_b3 x_9\n> Filter: ((y.a = a) AND (y.b = b))\n> (22 rows)\n>\n> The conditions (B=1 and A=1) cannot be pushed down to sublink/subplan in\n> where clause.\n>\n>\n>\n>\n>\n\nI tested it the way you said and increased the number of sub-tables.I created a hash partition table of 1000 sub-tables.Test according to your first SQL, the optimizer cuts the unnecessary sub-tables well.You can see the plan:\npostgres=# explain analyze\npostgres-# select temp.p1  from \npostgres-# (\npostgres(# select p1,p2 from test1.test1hashtable x where x.p1 = '1'\npostgres(# union all \npostgres(# (values('1','1')) \npostgres(# ) temp,\npostgres-# test1.test1hashtable y\npostgres-# where  y.p2 = temp.p2 and y.p1 = '1' and y.p1='1';\n                                                     QUERY PLAN                                                      \n---------------------------------------------------------------------------------------------------------------------\n Nested Loop  (cost=0.00..25.55 rows=1 width=32) (actual time=0.004..0.004 rows=0 loops=1)\n   Join Filter: (x.p2 = y.p2)\n   ->  Seq Scan on test1hashtable826 y  (cost=0.00..12.75 rows=1 width=32) (actual time=0.002..0.002 rows=0 loops=1)\n         Filter: (p1 = '1'::text)\n   ->  Append  (cost=0.00..12.78 rows=2 width=64) (never executed)\n         ->  Seq Scan on test1hashtable826 x  (cost=0.00..12.75 rows=1 width=64) (never executed)\n               Filter: (p1 = '1'::text)\n         ->  Result  (cost=0.00..0.01 rows=1 width=64) (never executed)\n Planning Time: 0.158 ms\n Execution Time: 0.022 ms\n(10 rows)But when the second one runs, the planning time reaches 13.942ms.The plan:\npostgres=# explain analyze\npostgres-# select\npostgres-# y.p1,\npostgres-# (Select x.p2 from test1.test1hashtable x where y.p1 =x.p1 and y.p2=x.p2) as b\npostgres-# from test1.test1hashtable y where p1 = '1' and p2 = '1';\n                                                    QUERY PLAN                                                    \n------------------------------------------------------------------------------------------------------------------\n Seq Scan on test1hashtable826 y  (cost=0.00..13318.30 rows=1 width=64) (actual time=0.004..0.047 rows=0 loops=1)\n   Filter: ((p1 = '1'::text) AND (p2 = '1'::text))\n   SubPlan 1\n     ->  Append  (cost=0.00..13305.00 rows=1000 width=32) (never executed)\n           ->  Seq Scan on test1hashtable1 x_1  (cost=0.00..13.30 rows=1 width=32) (never executed)\n                 Filter: ((y.p1 = p1) AND (y.p2 = p2))\n           ->  Seq Scan on test1hashtable1000 x_1000  (cost=0.00..13.30 rows=1 width=32) (never executed)\n                 Filter: ((y.p1 = p1) AND (y.p2 = p2))\n Planning Time: 13.942 ms\n Execution Time: 4.899 ms\n(2006 rows)This is a very worthwhile thing to do. In a relatively large business system, a large number of partition tables and high concurrency are often used. If the planning time is too long, this will greatly affect the business.regards,Shawn.Wenjing <wenjing.zwj@alibaba-inc.com> 于2021年8月17日周二 上午10:31写道:2021年8月16日 17:15,Wenjing <wenjing.zwj@alibaba-inc.com> 写道:Hi Hackers,Recently, a issue has been bothering me, This is about conditional push-down in SQL.I use cases from regression testing as an example.I found that the conditions  (B =1)  can be pushed down into the subquery, However, it cannot be pushed down to sublink/subplan.If a sublink/subplan clause contains a partition table, it can be useful to get the conditions for pruning.So, is it worth pushing conditions to sublink/subplan?Anybody have any ideas?regards,Wenjingexample:create table p (a int, b int, c int) partition by list (a);create table p1 partition of p for values in (1);create table p2 partition of p for values in (2);create table q (a int, b int, c int) partition by list (a);create table q1 partition of q for values in (1) partition by list (b);create table q11 partition of q1 for values in (1) partition by list (c);create table q111 partition of q11 for values in (1);create table q2 partition of q for values in (2) partition by list (b);create table q21 partition of q2 for values in (1);create table q22 partition of q2 for values in (2);insert into q22 values (2, 2, 3);Sorry, I messed up the structure of the table.It is should be:create table ab (a int not null, b int not null) partition by list (a);create table ab_a2 partition of ab for values in(2) partition by list (b);create table ab_a2_b1 partition of ab_a2 for values in (1);create table ab_a2_b2 partition of ab_a2 for values in (2);create table ab_a2_b3 partition of ab_a2 for values in (3);create table ab_a1 partition of ab for values in(1) partition by list (b);create table ab_a1_b1 partition of ab_a1 for values in (1);create table ab_a1_b2 partition of ab_a1 for values in (2);create table ab_a1_b3 partition of ab_a1 for values in (3);create table ab_a3 partition of ab for values in(3) partition by list (b);create table ab_a3_b1 partition of ab_a3 for values in (1);create table ab_a3_b2 partition of ab_a3 for values in (2);create table ab_a3_b3 partition of ab_a3 for values in (3);postgres-# explain (costs off)postgres-# select temp.b  from postgres-# (postgres(# select a,b from ab x where x.a = 1postgres(# union all postgres(# (values(1,1)) postgres(# ) temp,postgres-# ab ypostgres-# where  y.b = temp.b and y.a = 1 and y.b=1;                    QUERY PLAN                     --------------------------------------------------- Nested Loop   ->  Seq Scan on ab_a1_b1 y         Filter: ((b = 1) AND (a = 1))   ->  Append         ->  Subquery Scan on \"*SELECT* 1\"               ->  Seq Scan on ab_a1_b1 x                     Filter: ((a = 1) AND (b = 1))         ->  Result(8 rows)The conditions  (B =1)  can be pushed down into the subquery.postgres=# explain (costs off)postgres-# selectpostgres-# y.a,postgres-# (Select x.b from ab x where y.a =x.a and y.b=x.b) as bpostgres-# from ab y where a = 1 and b = 1;                    QUERY PLAN                     --------------------------------------------------- Seq Scan on ab_a1_b1 y   Filter: ((a = 1) AND (b = 1))   SubPlan 1     ->  Append           ->  Seq Scan on ab_a1_b1 x_1                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a1_b2 x_2                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a1_b3 x_3                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a2_b1 x_4                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a2_b2 x_5                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a2_b3 x_6                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a3_b1 x_7                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a3_b2 x_8                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a3_b3 x_9                 Filter: ((y.a = a) AND (y.b = b))(22 rows)The conditions (B = 1 and A = 1) cannot be pushed down to sublink/subplan in targetlist.postgres=# explain (costs off)postgres-# select y.apostgres-# from ab y postgres-# wherepostgres-# (select x.a > x.b from ab x where y.a =x.a and y.b=x.b) andpostgres-# y.a = 1 and y.b = 1;                    QUERY PLAN                     --------------------------------------------------- Seq Scan on ab_a1_b1 y   Filter: ((a = 1) AND (b = 1) AND (SubPlan 1))   SubPlan 1     ->  Append           ->  Seq Scan on ab_a1_b1 x_1                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a1_b2 x_2                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a1_b3 x_3                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a2_b1 x_4                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a2_b2 x_5                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a2_b3 x_6                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a3_b1 x_7                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a3_b2 x_8                 Filter: ((y.a = a) AND (y.b = b))           ->  Seq Scan on ab_a3_b3 x_9                 Filter: ((y.a = a) AND (y.b = b))(22 rows)The conditions  (B=1 and A=1)  cannot be pushed down to sublink/subplan in where clause.", "msg_date": "Wed, 1 Sep 2021 10:54:35 +0800", "msg_from": "shawn wang <shawn.wang.pg@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Is it worth pushing conditions to sublink/subplan?" }, { "msg_contents": "Hi Hackers\n\nFor my previous proposal, I developed a prototype and passed regression testing.\nIt works similarly to subquery's qual pushdown. We know that sublink expands\nat the beginning of each level of query. At this stage, The query's conditions and\nequivalence classes are not processed. But after generate_base_implied_equalities\nthe conditions are processed, which is why qual can push down to subquery but sublink not.\n\nMy POC implementation chose to delay the sublink expansion in the SELECT clause (targetList)\nand where clause. Specifically, it is delayed after generate_base_implied_equalities. Thus,\nthe equivalent conditions already established in the Up level query can be easily obtained\nin the sublink expansion process (make_subplan). \n\nFor example, if the up level query has a.id = 10 and the sublink query has a.id = b.id, then\nwe get b.id = 10 and push it down to the sublink quey. If b is a partitioned table and is\npartitioned by id, then a large number of unrelated subpartitions are pruned out, \nThis optimizes a significant amount of Planner and SQL execution time, especially\nif the partitioned table has a large number of subpartitions and is what I want.\n\nCurrently, There were two SQL failures in the regression test, because the expansion\norder of sublink was changed, which did not affect the execution result of SQL.\n\nLook forward to your suggestions on this proposal.\n\nThanks\n\nWenjing\n\n\n\n\n ------------------原始邮件 ------------------\n发件人:shawn wang <shawn.wang.pg@gmail.com>\n发送时间:Wed Sep 1 10:54:50 2021\n收件人:曾文旌(义从) <wenjing.zwj@alibaba-inc.com>\n抄送:PostgreSQL Hackers <pgsql-hackers@postgresql.org>, wjzeng <wjzeng2012@gmail.com>\n主题:Re: Is it worth pushing conditions to sublink/subplan?\n\nI tested it the way you said and increased the number of sub-tables.\nI created a hash partition table of 1000 sub-tables.\nTest according to your first SQL, the optimizer cuts the unnecessary sub-tables well.\nYou can see the plan:\n\npostgres=# explain analyze\npostgres-# select temp.p1 from\npostgres-# (\npostgres(# select p1,p2 from test1.test1hashtable x where x.p1 = '1'\npostgres(# union all\npostgres(# (values('1','1'))\npostgres(# ) temp,\npostgres-# test1.test1hashtable y\npostgres-# where y.p2 = temp.p2 and y.p1 = '1' and y.p1='1';\n QUERY PLAN \n---------------------------------------------------------------------------------------------------------------------\n Nested Loop (cost=0.00..25.55 rows=1 width=32) (actual time=0.004..0.004 rows=0 loops=1)\n Join Filter: (x.p2 = y.p2)\n -> Seq Scan on test1hashtable826 y (cost=0.00..12.75 rows=1 width=32) (actual time=0.002..0.002 rows=0 loops=1)\n Filter: (p1 = '1'::text)\n -> Append (cost=0.00..12.78 rows=2 width=64) (never executed)\n -> Seq Scan on test1hashtable826 x (cost=0.00..12.75 rows=1 width=64) (never executed)\n Filter: (p1 = '1'::text)\n -> Result (cost=0.00..0.01 rows=1 width=64) (never executed)\n Planning Time: 0.158 ms\n Execution Time: 0.022 ms\n(10 rows)\n\nBut when the second one runs, the planning time reaches 13.942ms.\nThe plan:\n\npostgres=# explain analyze\npostgres-# select\npostgres-# y.p1,\npostgres-# (Select x.p2 from test1.test1hashtable x where y.p1 =x.p1 and y.p2=x.p2) as b\npostgres-# from test1.test1hashtable y where p1 = '1' and p2 = '1';\n QUERY PLAN \n------------------------------------------------------------------------------------------------------------------\n Seq Scan on test1hashtable826 y (cost=0.00..13318.30 rows=1 width=64) (actual time=0.004..0.047 rows=0 loops=1)\n Filter: ((p1 = '1'::text) AND (p2 = '1'::text))\n SubPlan 1\n -> Append (cost=0.00..13305.00 rows=1000 width=32) (never executed)\n -> Seq Scan on test1hashtable1 x_1 (cost=0.00..13.30 rows=1 width=32) (never executed)\n Filter: ((y.p1 = p1) AND (y.p2 = p2))\n -> Seq Scan on test1hashtable1000 x_1000 (cost=0.00..13.30 rows=1 width=32) (never executed)\n Filter: ((y.p1 = p1) AND (y.p2 = p2))\n Planning Time: 13.942 ms\n Execution Time: 4.899 ms\n(2006 rows)\n\nThis is a very worthwhile thing to do. In a relatively large business system, a large number of partition tables and high concurrency are often used. If the planning time is too long, this will greatly affect the business.\n\nregards,\nShawn.\nWenjing <wenjing.zwj@alibaba-inc.com> 于2021年8月17日周二 上午10:31写道:\n\n\n\n\n2021年8月16日 17:15,Wenjing <wenjing.zwj@alibaba-inc.com> 写道:\nHi Hackers,\n\nRecently, a issue has been bothering me, This is about conditional push-down in SQL.\nI use cases from regression testing as an example.\nI found that the conditions (B =1) can be pushed down into the subquery, However, it cannot be pushed down to sublink/subplan.\nIf a sublink/subplan clause contains a partition table, it can be useful to get the conditions for pruning.\n\nSo, is it worth pushing conditions to sublink/subplan?\nAnybody have any ideas?\n\n\nregards,\nWenjing\n\n\nexample:\ncreate table p (a int, b int, c int) partition by list (a);\ncreate table p1 partition of p for values in (1);\ncreate table p2 partition of p for values in (2);\ncreate table q (a int, b int, c int) partition by list (a);\ncreate table q1 partition of q for values in (1) partition by list (b);\ncreate table q11 partition of q1 for values in (1) partition by list (c);\ncreate table q111 partition of q11 for values in (1);\ncreate table q2 partition of q for values in (2) partition by list (b);\ncreate table q21 partition of q2 for values in (1);\ncreate table q22 partition of q2 for values in (2);\ninsert into q22 values (2, 2, 3);\nSorry, I messed up the structure of the table.\nIt is should be:\ncreate table ab (a int not null, b int not null) partition by list (a);\ncreate table ab_a2 partition of ab for values in(2) partition by list (b);\ncreate table ab_a2_b1 partition of ab_a2 for values in (1);\ncreate table ab_a2_b2 partition of ab_a2 for values in (2);\ncreate table ab_a2_b3 partition of ab_a2 for values in (3);\ncreate table ab_a1 partition of ab for values in(1) partition by list (b);\ncreate table ab_a1_b1 partition of ab_a1 for values in (1);\ncreate table ab_a1_b2 partition of ab_a1 for values in (2);\ncreate table ab_a1_b3 partition of ab_a1 for values in (3);\ncreate table ab_a3 partition of ab for values in(3) partition by list (b);\ncreate table ab_a3_b1 partition of ab_a3 for values in (1);\ncreate table ab_a3_b2 partition of ab_a3 for values in (2);\ncreate table ab_a3_b3 partition of ab_a3 for values in (3);\n\n\n\n\n\npostgres-# explain (costs off)\npostgres-# select temp.b from \npostgres-# (\npostgres(# select a,b from ab x where x.a = 1\npostgres(# union all \npostgres(# (values(1,1)) \npostgres(# ) temp,\npostgres-# ab y\npostgres-# where y.b = temp.b and y.a = 1 and y.b=1;\n QUERY PLAN \n---------------------------------------------------\n Nested Loop\n -> Seq Scan on ab_a1_b1 y\n Filter: ((b = 1) AND (a = 1))\n -> Append\n -> Subquery Scan on \"*SELECT* 1\"\n -> Seq Scan on ab_a1_b1 x\n Filter: ((a = 1) AND (b = 1))\n -> Result\n(8 rows)\n\nThe conditions (B =1) can be pushed down into the subquery.\n\n\npostgres=# explain (costs off)\npostgres-# select\npostgres-# y.a,\npostgres-# (Select x.b from ab x where y.a =x.a and y.b=x.b) as b\npostgres-# from ab y where a = 1 and b = 1;\n QUERY PLAN \n---------------------------------------------------\n Seq Scan on ab_a1_b1 y\n Filter: ((a = 1) AND (b = 1))\n SubPlan 1\n -> Append\n -> Seq Scan on ab_a1_b1 x_1\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a1_b2 x_2\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a1_b3 x_3\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a2_b1 x_4\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a2_b2 x_5\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a2_b3 x_6\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a3_b1 x_7\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a3_b2 x_8\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a3_b3 x_9\n Filter: ((y.a = a) AND (y.b = b))\n(22 rows)\n\n\nThe conditions (B = 1 and A = 1) cannot be pushed down to sublink/subplan in targetlist.\n\npostgres=# explain (costs off)\npostgres-# select y.a\npostgres-# from ab y \npostgres-# where\npostgres-# (select x.a > x.b from ab x where y.a =x.a and y.b=x.b) and\npostgres-# y.a = 1 and y.b = 1;\n QUERY PLAN \n---------------------------------------------------\n Seq Scan on ab_a1_b1 y\n Filter: ((a = 1) AND (b = 1) AND (SubPlan 1))\n SubPlan 1\n -> Append\n -> Seq Scan on ab_a1_b1 x_1\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a1_b2 x_2\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a1_b3 x_3\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a2_b1 x_4\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a2_b2 x_5\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a2_b3 x_6\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a3_b1 x_7\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a3_b2 x_8\n Filter: ((y.a = a) AND (y.b = b))\n -> Seq Scan on ab_a3_b3 x_9\n Filter: ((y.a = a) AND (y.b = b))\n(22 rows)\n\nThe conditions (B=1 and A=1) cannot be pushed down to sublink/subplan in where clause.", "msg_date": "Tue, 07 Dec 2021 17:44:35 +0800", "msg_from": "\"=?UTF-8?B?5pu+5paH5peMKOS5ieS7jik=?=\" <wenjing.zwj@alibaba-inc.com>", "msg_from_op": false, "msg_subject": "\n =?UTF-8?B?5Zue5aSN77yaUmU6IElzIGl0IHdvcnRoIHB1c2hpbmcgY29uZGl0aW9ucyB0byBzdWJsaW5r?=\n =?UTF-8?B?L3N1YnBsYW4/?=" }, { "msg_contents": "Hi,\n\nOn 12/7/21 10:44, 曾文旌(义从) wrote:\n> Hi Hackers\n> \n> For my previous proposal, I developed a prototype and passed\n> regression testing. It works similarly to subquery's qual pushdown.\n> We know that sublink expands at the beginning of each level of\n> query. At this stage, The query's conditions and equivalence classes\n> are not processed. But after generate_base_implied_equalities the\n> conditions are processed, which is why qual can push down to \n> subquery but sublink not.\n> \n> My POC implementation chose to delay the sublink expansion in the\n> SELECT clause (targetList) and where clause. Specifically, it is\n> delayed after generate_base_implied_equalities. Thus, the equivalent\n> conditions already established in the Up level query can be easily\n> obtained in the sublink expansion process (make_subplan).\n> \n> For example, if the up level query has a.id = 10 and the sublink\n> query has a.id = b.id, then we get b.id = 10 and push it down to the\n> sublink quey. If b is a partitioned table and is partitioned by id,\n> then a large number of unrelated subpartitions are pruned out, This\n> optimizes a significant amount of Planner and SQL execution time, \n> especially if the partitioned table has a large number of\n> subpartitions and is what I want.\n> \n> Currently, There were two SQL failures in the regression test,\n> because the expansion order of sublink was changed, which did not\n> affect the execution result of SQL.\n> \n> Look forward to your suggestions on this proposal.\n> \n\nI took a quick look, and while I don't see / can't think of any problems\nwith delaying it until after generating implied equalities, there seems\nto be a number of gaps.\n\n\n1) Are there any regression tests exercising this modified behavior?\nMaybe there are, but if the only changes are due to change in order of\ntargetlist entries, that doesn't seem like a clear proof.\n\nIt'd be good to add a couple tests exercising both the positive and\nnegative case (i.e. when we can and can't pushdown a qual).\n\n\n2) apparently, contrib/postgres_fdw does crash like this:\n\n #3 0x000000000077b412 in adjust_appendrel_attrs_mutator\n (node=0x13f7ea0, context=0x7fffc3351b30) at appendinfo.c:470\n 470 Assert(!IsA(node, SubLink));\n (gdb) p node\n $1 = (Node *) 0x13f7ea0\n (gdb) p *node\n $2 = {type = T_SubLink}\n\n Backtrace attached.\n\n3) various parts of the patch really need at least some comments, like:\n\n - try_push_outer_qual_to_sublink_query really needs some docs\n\n - new stuff at the end of initsplan.c\n\n\n4) generate_base_implied_equalities\n\n shouldn't this\n\n if (ec->ec_processed)\n ;\n\n really be?\n\n if (ec->ec_processed)\n continue;\n\n5) I'm not sure why we need the new ec_processed flag.\n\n6) So we now have lazy_process_sublink callback? Does that mean we\nexpand sublinks in two places - sometimes lazily, sometimes not?\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Wed, 8 Dec 2021 04:26:28 +0100", "msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>", "msg_from_op": false, "msg_subject": "=?UTF-8?B?UmU6IOWbnuWkje+8mlJlOiBJcyBpdCB3b3J0aCBwdXNoaW5nIGNvbmRp?=\n =?UTF-8?Q?tions_to_sublink/subplan=3f?=" }, { "msg_contents": "------------------原始邮件 ------------------\n发件人:Tomas Vondra <tomas.vondra@enterprisedb.com>\n发送时间:Wed Dec 8 11:26:35 2021\n收件人:曾文旌(义从) <wenjing.zwj@alibaba-inc.com>, shawn wang <shawn.wang.pg@gmail.com>, ggysxcq@gmail.com <ggysxcq@gmail.com>, PostgreSQL Hackers <pgsql-hackers@postgresql.org>\n抄送:wjzeng <wjzeng2012@gmail.com>\n主题:Re: 回复:Re: Is it worth pushing conditions to sublink/subplan?\n\nHi,\n\nOn 12/7/21 10:44, 曾文旌(义从) wrote:\n> Hi Hackers\n> \n> For my previous proposal, I developed a prototype and passed\n> regression testing. It works similarly to subquery's qual pushdown.\n> We know that sublink expands at the beginning of each level of\n> query. At this stage, The query's conditions and equivalence classes\n> are not processed. But after generate_base_implied_equalities the\n> conditions are processed, which is why qual can push down to \n> subquery but sublink not.\n> \n> My POC implementation chose to delay the sublink expansion in the\n> SELECT clause (targetList) and where clause. Specifically, it is\n> delayed after generate_base_implied_equalities. Thus, the equivalent\n> conditions already established in the Up level query can be easily\n> obtained in the sublink expansion process (make_subplan).\n> \n> For example, if the up level query has a.id = 10 and the sublink\n> query has a.id = b.id, then we get b.id = 10 and push it down to the\n> sublink quey. If b is a partitioned table and is partitioned by id,\n> then a large number of unrelated subpartitions are pruned out, This\n> optimizes a significant amount of Planner and SQL execution time, \n> especially if the partitioned table has a large number of\n> subpartitions and is what I want.\n> \n> Currently, There were two SQL failures in the regression test,\n> because the expansion order of sublink was changed, which did not\n> affect the execution result of SQL.\n> \n> Look forward to your suggestions on this proposal.\n> \n\nI took a quick look, and while I don't see / can't think of any problems\nwith delaying it until after generating implied equalities, there seems\nto be a number of gaps.\n\nThank you for your attention.\n\n1) Are there any regression tests exercising this modified behavior?\nMaybe there are, but if the only changes are due to change in order of\ntargetlist entries, that doesn't seem like a clear proof.\n\nIt'd be good to add a couple tests exercising both the positive and\nnegative case (i.e. when we can and can't pushdown a qual).\n\nI added several samples to the regress(qual_pushdown_to_sublink.sql). \nand I used the partition table to show the plan status of qual being pushed down into sublink.\nHopefully this will help you understand the details of this patch. Later, I will add more cases.\n2) apparently, contrib/postgres_fdw does crash like this:\n\n #3 0x000000000077b412 in adjust_appendrel_attrs_mutator\n (node=0x13f7ea0, context=0x7fffc3351b30) at appendinfo.c:470\n 470 Assert(!IsA(node, SubLink));\n (gdb) p node\n $1 = (Node *) 0x13f7ea0\n (gdb) p *node\n $2 = {type = T_SubLink}\n\n Backtrace attached.\n\nFor the patch attached in the last email, I passed all the tests under src/test/regress.\nAs you pointed out, there was a problem with regression under contrib(in contrib/postgres_fdw). \nThis time I fixed it and the current patch (V2) can pass the check-world.\n\n\n3) various parts of the patch really need at least some comments, like:\n\n - try_push_outer_qual_to_sublink_query really needs some docs\n\n - new stuff at the end of initsplan.c\n\nOk, I added some comments and will add more. If you have questions about any details,\nplease point them out directly.\n\n4) generate_base_implied_equalities\n\n shouldn't this\n\n if (ec->ec_processed)\n ;\n\n really be?\n\n if (ec->ec_processed)\n continue;\n\nYou are right. I fixed it.\n\n5) I'm not sure why we need the new ec_processed flag.\n\nI did this to eliminate duplicate equalities from the two generate_base_implied_equalities calls\n1) I need the base equivalent expression generated after generate_base_implied_equalities,\nwhich is used to pushdown qual to sublink(lazy_process_sublinks)\n2) The expansion of sublink may result in an equivalent expression with parameters, such as a = $1,\nwhich needs to deal with the equivalence classes again.\n3) So, I added ec_processed and asked to process it again (generate_base_implied_equalities)\nafter the equivalence class changed (add_eq_member/process_equivalence).\n\nMaybe you have a better suggestion, please let me know.\n\n6) So we now have lazy_process_sublink callback? Does that mean we\nexpand sublinks in two places - sometimes lazily, sometimes not?\n\nYes, not all sublink is delayed. Let me explain this:\n1) I added a GUC switch enable_lazy_process_sublink. If it is turned off, all lazy process sublink will not happen,\nqual pushdown to sublink depend on lazy procee sublink, which means no quals will be pushed down.\n2) Even if enable_lazy_process_sublink = true If Query in this level contains some complex features,\nsublink in this level query will not try do qual pushdown. (see function query_has_sublink_try_pushdown_qual).\nI want to support a minimum subset first. Then consider complex features such as CTE/DML.\n3) Finally, under conditions 1 and 2, all kinds of sublink contained in the SELECT clause or\nWHERE clause will delays expansion and try pushdown qual. The sublink elsewhere in the SQL statement\ndoes not delay process.\n\nThe current status meets my requirements for now. Of course, after this scheme is proved to be feasible, maybe\nwe can discuss that all sublinks are processed by overall delay, just like qual pushdown to subquery.\n\nthanks\n\nWenjing\n\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Sat, 11 Dec 2021 23:30:40 +0800", "msg_from": "\"=?UTF-8?B?5pu+5paH5peMKOS5ieS7jik=?=\" <wenjing.zwj@alibaba-inc.com>", "msg_from_op": false, "msg_subject": "\n =?UTF-8?B?5Zue5aSN77yaUmU6IOWbnuWkje+8mlJlOiBJcyBpdCB3b3J0aCBwdXNoaW5nIGNvbmRpdGlv?=\n =?UTF-8?B?bnMgdG8gc3VibGluay9zdWJwbGFuPw==?=" }, { "msg_contents": "On Sat, Dec 11, 2021 at 7:31 AM 曾文旌(义从) <wenjing.zwj@alibaba-inc.com> wrote:\n\n>\n>\n> ------------------原始邮件 ------------------\n> *发件人:*Tomas Vondra <tomas.vondra@enterprisedb.com>\n> *发送时间:*Wed Dec 8 11:26:35 2021\n> *收件人:*曾文旌(义从) <wenjing.zwj@alibaba-inc.com>, shawn wang <\n> shawn.wang.pg@gmail.com>, ggysxcq@gmail.com <ggysxcq@gmail.com>,\n> PostgreSQL Hackers <pgsql-hackers@postgresql.org>\n> *抄送:*wjzeng <wjzeng2012@gmail.com>\n> *主题:*Re: 回复:Re: Is it worth pushing conditions to sublink/subplan?\n>\n>> Hi,\n>>\n>> On 12/7/21 10:44, 曾文旌(义从) wrote:\n>> > Hi Hackers\n>> >\n>> > For my previous proposal, I developed a prototype and passed\n>> > regression testing. It works similarly to subquery's qual pushdown.\n>> > We know that sublink expands at the beginning of each level of\n>> > query. At this stage, The query's conditions and equivalence classes\n>> > are not processed. But after generate_base_implied_equalities the\n>> > conditions are processed, which is why qual can push down to\n>> > subquery but sublink not.\n>> >\n>> > My POC implementation chose to delay the sublink expansion in the\n>> > SELECT clause (targetList) and where clause. Specifically, it is\n>> > delayed after generate_base_implied_equalities. Thus, the equivalent\n>> > conditions already established in the Up level query can be easily\n>> > obtained in the sublink expansion process (make_subplan).\n>> >\n>> > For example, if the up level query has a.id = 10 and the sublink\n>> > query has a.id = b.id, then we get b.id = 10 and push it down to the\n>> > sublink quey. If b is a partitioned table and is partitioned by id,\n>> > then a large number of unrelated subpartitions are pruned out, This\n>> > optimizes a significant amount of Planner and SQL execution time,\n>> > especially if the partitioned table has a large number of\n>> > subpartitions and is what I want.\n>> >\n>> > Currently, There were two SQL failures in the regression test,\n>> > because the expansion order of sublink was changed, which did not\n>> > affect the execution result of SQL.\n>> >\n>> > Look forward to your suggestions on this proposal.\n>> >\n>>\n>> I took a quick look, and while I don't see / can't think of any problems\n>> with delaying it until after generating implied equalities, there seems\n>> to be a number of gaps.\n>>\n>> *Thank you for your attention.*\n>>\n>> 1) Are there any regression tests exercising this modified behavior?\n>> Maybe there are, but if the only changes are due to change in order of\n>> targetlist entries, that doesn't seem like a clear proof.\n>>\n>> It'd be good to add a couple tests exercising both the positive and\n>> negative case (i.e. when we can and can't pushdown a qual).\n>>\n>> *I added several samples to the regress(qual_pushdown_to_sublink.sql). *\n>> *and I\n>> used the partition table to show the plan status of qual being pushed down into sublink.*\n>>\n>> *Hopefully this will help you understand the details of this patch. Later, I will add more cases.*\n>>\n>> 2) apparently, contrib/postgres_fdw does crash like this:\n>>\n>> #3 0x000000000077b412 in adjust_appendrel_attrs_mutator\n>> (node=0x13f7ea0, context=0x7fffc3351b30) at appendinfo.c:470\n>> 470 Assert(!IsA(node, SubLink));\n>> (gdb) p node\n>> $1 = (Node *) 0x13f7ea0\n>> (gdb) p *node\n>> $2 = {type = T_SubLink}\n>>\n>> Backtrace attached.\n>>\n>> *For the patch attached in the last email, I passed all the tests under\n>> src/test/regress.*\n>> *As you pointed out, there was a problem with regression under contrib(in\n>> contrib/postgres_fdw). *\n>> *This time I fixed it and the current patch (V2) can pass the\n>> check-world.*\n>>\n>> 3) various parts of the patch really need at least some comments, like:\n>>\n>> - try_push_outer_qual_to_sublink_query really needs some docs\n>>\n>> - new stuff at the end of initsplan.c\n>>\n>> *Ok, I added some comments and will\n>> add more. If you have questions about any details,*\n>> *please point them out directly.*\n>>\n>> 4) generate_base_implied_equalities\n>>\n>> shouldn't this\n>>\n>> if (ec->ec_processed)\n>> ;\n>>\n>> really be?\n>>\n>> if (ec->ec_processed)\n>> continue;\n>>\n>> *You are right. I fixed it.*\n>>\n>> 5) I'm not sure why we need the new ec_processed flag.\n>>\n>>\n>> *I did this to eliminate duplicate equalities from the two generate_base_implied_equalities calls*\n>>\n>> *1) I need the base equivalent expression generated after generate_base_implied_equalities,*\n>> *which is used to pushdown qual to sublink(lazy_process_sublinks)*\n>>\n>> *2) The expansion of sublink may result in an equivalent expression with parameters, such as a = $1,*\n>> *which needs to deal with the equivalence classes again.*\n>>\n>> *3) So, I added ec_processed and asked to process it again (generate_base_implied_equalities)*\n>> *after the equivalence class changed (add_eq_member/process_equivalence).*\n>>\n>> *Maybe you have a better suggestion, please let me know.*\n>>\n>> 6) So we now have lazy_process_sublink callback? Does that mean we\n>> expand sublinks in two places - sometimes lazily, sometimes not?\n>>\n>> *Yes, not all sublink is delayed. Let me explain this:*\n>> *1) I added a GUC switch enable_lazy_process_sublink. If it is turned off, all\n>> lazy process sublink will not happen,*\n>>\n>> *qual pushdown to sublink depend on lazy procee sublink, which means no quals will be pushed down.*\n>> *2) Even if enable_lazy_process_sublink = true\n>> If Query in this level contains some complex features,*\n>> *sublink in this level query will not try do qual pushdown. (see function\n>> query_has_sublink_try_pushdown_qual).*\n>>\n>> *I want to support a minimum subset first. Then consider complex features such as CTE/DML.*\n>> *3) Finally, under conditions 1 and 2,\n>> all kinds of sublink contained in the SELECT clause or*\n>> *WHERE clause will delays expansion and try pushdown qual. The\n>> sublink elsewhere in the SQL statement*\n>> *does not delay process.*\n>>\n>> *The current status meets my requirements for\n>> now. Of course, after this scheme is proved to be feasible, maybe*\n>> *we can discuss that all sublinks are processed by overall delay, just like\n>> qual pushdown to subquery.*\n>>\n>> *thanks*\n>>\n>> *Wenjing*\n>>\n>>\n>>\n>> regards\n>>\n>> --\n>> Tomas Vondra\n>> EnterpriseDB: http://www.enterprisedb.com\n>> The Enterprise PostgreSQL Company\n>>\n> Hi,\n\n+ /* The outer var could exist in any of the upper-level queries to\nfind these roots */\n\nto find these roots -> so find these roots\n\n+ if (has_unexpand_sublink(root) && checkExprHasSubLink(node))\n\nhas_unexpand_sublink -> has_unexpanded_sublink\n\n+ if (enable_lazy_process_sublink)\n+ return true;\n\nThe above can be simplified to:\n\n return enable_lazy_process_sublink;\n\n+ if (checkExprHasSubLink(qual))\n+ {\n+ qual = lazy_process_sublink_qual(root, qual);\n+ newquals = lappend(newquals, qual);\n+ }\n+ else\n+ newquals = lappend(newquals, qual);\n\nSince the lappend() is common to both branches, you can remove the else\nclause. In the if block, only call lazy_process_sublink_qual().\n\n+ /* under lazy process sublink, parent root may have some data that\nchild not need, so set it to NULL */\n+ subroot->join_info_list = NIL;\n\nminor correction to the comment above:\n under lazy process sublink, parent root may have some data that child\ndoes not need, so set it to NIL\n\n+void\n+preprocess_qual_conditions(PlannerInfo *root, Node *jtnode, bool istop)\n\nPlease add a comment explaining the meaning of istop.\n\n+ if (istop)\n+ f->quals = preprocess_expression_ext(root, f->quals,\nEXPRKIND_QUAL, false);\n+ else\n+ f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);\n\nI think the code would be more readable if you replace\nthe preprocess_expression() call in else branch with call\nto preprocess_expression_ext().\n\n+ context->root->unexpand_sublink_counter++;\n\nunexpand_sublink_counter -> unexpanded_sublink_counter++\n\nFor sublink_query_push_qual(), the return at the end is not needed.\n\nFor condition_is_safe_pushdown_to_sublink, you can initialize context this\nway :\n\n+ equal_expr_info_context context = {0};\n\n+ if (cvar && cvar->varattno > 0 && equal(cvar, var))\n+ return true;\n\nThe last few lines of condition_is_safe_pushdown_to_sublink() can be\nwritten as:\n\n return cvar && cvar->varattno > 0 && equal(cvar, var);\n\n+ if (equal_expr_safety_check(node, &context))\n+ {\n+ /* It needs to be something like outer var = inner var */\n+ if (context.inner_var &&\n\nThe nested if blocks can be merged into one if block.\n\nCheers\n\nOn Sat, Dec 11, 2021 at 7:31 AM 曾文旌(义从) <wenjing.zwj@alibaba-inc.com> wrote: ------------------原始邮件 ------------------发件人:Tomas Vondra <tomas.vondra@enterprisedb.com>发送时间:Wed Dec 8 11:26:35 2021收件人:曾文旌(义从) <wenjing.zwj@alibaba-inc.com>, shawn wang <shawn.wang.pg@gmail.com>, ggysxcq@gmail.com <ggysxcq@gmail.com>, PostgreSQL Hackers <pgsql-hackers@postgresql.org>抄送:wjzeng <wjzeng2012@gmail.com>主题:Re: 回复:Re: Is it worth pushing conditions to sublink/subplan?Hi,On 12/7/21 10:44, 曾文旌(义从) wrote:> Hi Hackers> > For my previous proposal, I developed a prototype and passed> regression testing. It works similarly to subquery's qual pushdown.> We know that sublink expands at the beginning of each level of> query. At this stage, The query's conditions and equivalence classes> are not processed. But after generate_base_implied_equalities the> conditions are processed,  which is why qual can push down to > subquery but sublink not.> > My POC implementation chose to delay the sublink expansion in the> SELECT clause (targetList) and where clause. Specifically, it is> delayed after generate_base_implied_equalities. Thus, the equivalent> conditions already established in the Up level query can be easily> obtained in the sublink expansion process (make_subplan).> > For example, if the up level query has a.id = 10 and the sublink> query has a.id = b.id, then we get b.id = 10 and push it down to the> sublink quey. If b is a partitioned table and is partitioned by id,> then a large number of unrelated subpartitions are pruned out, This> optimizes a significant amount of Planner and SQL execution time, > especially if the partitioned table has a large number of> subpartitions and is what I want.> > Currently, There were two SQL failures in the regression test,> because the expansion order of sublink was changed, which did not> affect the execution result of SQL.> > Look forward to your suggestions on this proposal.> I took a quick look, and while I don't see / can't think of any problemswith delaying it until after generating implied equalities, there seemsto be a number of gaps.Thank you for your attention.1) Are there any regression tests exercising this modified behavior?Maybe there are, but if the only changes are due to change in order oftargetlist entries, that doesn't seem like a clear proof.It'd be good to add a couple tests exercising both the positive andnegative case (i.e. when we can and can't pushdown a qual).I added several samples to the regress(qual_pushdown_to_sublink.sql). and I used the partition table to show the plan status of qual being pushed down into sublink.Hopefully this will help you understand the details of this patch. Later, I will add more cases.2) apparently, contrib/postgres_fdw does crash like this:  #3  0x000000000077b412 in adjust_appendrel_attrs_mutator      (node=0x13f7ea0, context=0x7fffc3351b30) at appendinfo.c:470  470          Assert(!IsA(node, SubLink));  (gdb) p node  $1 = (Node *) 0x13f7ea0  (gdb) p *node  $2 = {type = T_SubLink}  Backtrace attached.For the patch attached in the last email, I passed all the tests under src/test/regress.As you pointed out, there was a problem with regression under contrib(in contrib/postgres_fdw). This time I fixed it and the current patch (V2) can pass the check-world.3) various parts of the patch really need at least some comments, like:  - try_push_outer_qual_to_sublink_query really needs some docs  - new stuff at the end of initsplan.cOk, I added some comments and will add more. If you have questions about any details,please point them out directly.4) generate_base_implied_equalities   shouldn't this        if (ec->ec_processed)            ;   really be?        if (ec->ec_processed)            continue;You are right. I fixed it.5) I'm not sure why we need the new ec_processed flag.I did this to eliminate duplicate equalities from the two generate_base_implied_equalities calls1) I need the base equivalent expression generated after generate_base_implied_equalities,which is used to pushdown qual to sublink(lazy_process_sublinks)2) The expansion of sublink may result in an equivalent expression with parameters, such as a = $1,which needs to deal with the equivalence classes again.3) So, I added ec_processed and asked to process it again (generate_base_implied_equalities)after the equivalence class changed (add_eq_member/process_equivalence).Maybe you have a better suggestion, please let me know.6) So we now have lazy_process_sublink callback? Does that mean weexpand sublinks in two places - sometimes lazily, sometimes not?Yes, not all sublink is delayed. Let me explain this:1) I added a GUC switch enable_lazy_process_sublink. If it is turned off, all lazy process sublink will not happen,qual pushdown to sublink depend on lazy procee sublink, which means no quals will be pushed down.2) Even  if enable_lazy_process_sublink = true If Query in this level contains some complex features,sublink in this level query will not try do qual pushdown. (see function query_has_sublink_try_pushdown_qual).I want to support a minimum subset first. Then consider complex features such as CTE/DML.3) Finally, under conditions 1 and 2, all kinds of sublink contained in the SELECT clause orWHERE clause will delays expansion and try pushdown qual. The sublink elsewhere in the SQL statementdoes not delay process.The current status meets my requirements for now. Of course, after this scheme is proved to be feasible, maybewe can discuss that all sublinks are processed by overall delay, just like qual pushdown to subquery.thanksWenjingregards-- Tomas VondraEnterpriseDB: http://www.enterprisedb.comThe Enterprise PostgreSQL CompanyHi,+       /* The outer var could exist in any of the upper-level queries to find these roots */to find these roots -> so find these roots +           if (has_unexpand_sublink(root) && checkExprHasSubLink(node))has_unexpand_sublink -> has_unexpanded_sublink+   if (enable_lazy_process_sublink)+       return true;The above can be simplified to:  return enable_lazy_process_sublink;+           if (checkExprHasSubLink(qual))+           {+               qual = lazy_process_sublink_qual(root, qual);+               newquals = lappend(newquals, qual);+           }+           else+               newquals = lappend(newquals, qual);Since the lappend() is common to both branches, you can remove the else clause. In the if block, only call lazy_process_sublink_qual().+       /* under lazy process sublink, parent root may have some data that child not need, so set it to NULL */+       subroot->join_info_list = NIL;minor correction to the comment above:  under lazy process sublink, parent root may have some data that child does not need, so set it to NIL+void+preprocess_qual_conditions(PlannerInfo *root, Node *jtnode, bool istop)Please add a comment explaining the meaning of istop.+       if (istop)+           f->quals = preprocess_expression_ext(root, f->quals, EXPRKIND_QUAL, false);+       else+           f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);I think the code would be more readable if you replace the preprocess_expression() call in else branch with call to preprocess_expression_ext().+           context->root->unexpand_sublink_counter++;unexpand_sublink_counter -> unexpanded_sublink_counter++For sublink_query_push_qual(), the return at the end is not needed.For condition_is_safe_pushdown_to_sublink, you can initialize context this way :+   equal_expr_info_context context = {0};+   if (cvar && cvar->varattno > 0 && equal(cvar, var))+       return true;The last few lines of condition_is_safe_pushdown_to_sublink() can be written as:  return cvar && cvar->varattno > 0 && equal(cvar, var);+       if (equal_expr_safety_check(node, &context))+       {+           /* It needs to be something like outer var = inner var */+           if (context.inner_var &&The nested if blocks can be merged into one if block.Cheers", "msg_date": "Sat, 11 Dec 2021 09:09:11 -0800", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "\n =?UTF-8?B?UmU6IFJlOiDlm57lpI3vvJpSZTogSXMgaXQgd29ydGggcHVzaGluZyBjb25kaXRpb25zIA==?=\n\t=?UTF-8?B?dG8gc3VibGluay9zdWJwbGFuPw==?=" }, { "msg_contents": "------------------原始邮件 ------------------\n发件人:Zhihong Yu <zyu@yugabyte.com>\n发送时间:Sun Dec 12 01:13:11 2021\n收件人:曾文旌(义从) <wenjing.zwj@alibaba-inc.com>\n抄送:Tomas Vondra <tomas.vondra@enterprisedb.com>, wjzeng <wjzeng2012@gmail.com>, PostgreSQL Hackers <pgsql-hackers@postgresql.org>, shawn wang <shawn.wang.pg@gmail.com>, ggysxcq@gmail.com <ggysxcq@gmail.com>\n主题:Re: Re: 回复:Re: Is it worth pushing conditions to sublink/subplan?\n\n\n\nOn Sat, Dec 11, 2021 at 7:31 AM 曾文旌(义从) <wenjing.zwj@alibaba-inc.com> wrote:\n\n\n\n\n ------------------原始邮件 ------------------\n发件人:Tomas Vondra <tomas.vondra@enterprisedb.com>\n发送时间:Wed Dec 8 11:26:35 2021\n收件人:曾文旌(义从) <wenjing.zwj@alibaba-inc.com>, shawn wang <shawn.wang.pg@gmail.com>, ggysxcq@gmail.com <ggysxcq@gmail.com>, PostgreSQL Hackers <pgsql-hackers@postgresql.org>\n抄送:wjzeng <wjzeng2012@gmail.com>\n主题:Re: 回复:Re: Is it worth pushing conditions to sublink/subplan?\n\nHi,\n\nOn 12/7/21 10:44, 曾文旌(义从) wrote:\n> Hi Hackers\n> \n> For my previous proposal, I developed a prototype and passed\n> regression testing. It works similarly to subquery's qual pushdown.\n> We know that sublink expands at the beginning of each level of\n> query. At this stage, The query's conditions and equivalence classes\n> are not processed. But after generate_base_implied_equalities the\n> conditions are processed, which is why qual can push down to \n> subquery but sublink not.\n> \n> My POC implementation chose to delay the sublink expansion in the\n> SELECT clause (targetList) and where clause. Specifically, it is\n> delayed after generate_base_implied_equalities. Thus, the equivalent\n> conditions already established in the Up level query can be easily\n> obtained in the sublink expansion process (make_subplan).\n> \n> For example, if the up level query has a.id = 10 and the sublink\n> query has a.id = b.id, then we get b.id = 10 and push it down to the\n> sublink quey. If b is a partitioned table and is partitioned by id,\n> then a large number of unrelated subpartitions are pruned out, This\n> optimizes a significant amount of Planner and SQL execution time, \n> especially if the partitioned table has a large number of\n> subpartitions and is what I want.\n> \n> Currently, There were two SQL failures in the regression test,\n> because the expansion order of sublink was changed, which did not\n> affect the execution result of SQL.\n> \n> Look forward to your suggestions on this proposal.\n> \n\nI took a quick look, and while I don't see / can't think of any problems\nwith delaying it until after generating implied equalities, there seems\nto be a number of gaps.\n\nThank you for your attention.\n\n1) Are there any regression tests exercising this modified behavior?\nMaybe there are, but if the only changes are due to change in order of\ntargetlist entries, that doesn't seem like a clear proof.\n\nIt'd be good to add a couple tests exercising both the positive and\nnegative case (i.e. when we can and can't pushdown a qual).\n\nI added several samples to the regress(qual_pushdown_to_sublink.sql). \nand I used the partition table to show the plan status of qual being pushed down into sublink.\nHopefully this will help you understand the details of this patch. Later, I will add more cases.\n2) apparently, contrib/postgres_fdw does crash like this:\n\n #3 0x000000000077b412 in adjust_appendrel_attrs_mutator\n (node=0x13f7ea0, context=0x7fffc3351b30) at appendinfo.c:470\n 470 Assert(!IsA(node, SubLink));\n (gdb) p node\n $1 = (Node *) 0x13f7ea0\n (gdb) p *node\n $2 = {type = T_SubLink}\n\n Backtrace attached.\n\nFor the patch attached in the last email, I passed all the tests under src/test/regress.\nAs you pointed out, there was a problem with regression under contrib(in contrib/postgres_fdw). \nThis time I fixed it and the current patch (V2) can pass the check-world.\n\n\n3) various parts of the patch really need at least some comments, like:\n\n - try_push_outer_qual_to_sublink_query really needs some docs\n\n - new stuff at the end of initsplan.c\n\nOk, I added some comments and will add more. If you have questions about any details,\nplease point them out directly.\n\n4) generate_base_implied_equalities\n\n shouldn't this\n\n if (ec->ec_processed)\n ;\n\n really be?\n\n if (ec->ec_processed)\n continue;\n\nYou are right. I fixed it.\n\n5) I'm not sure why we need the new ec_processed flag.\n\nI did this to eliminate duplicate equalities from the two generate_base_implied_equalities calls\n1) I need the base equivalent expression generated after generate_base_implied_equalities,\nwhich is used to pushdown qual to sublink(lazy_process_sublinks)\n2) The expansion of sublink may result in an equivalent expression with parameters, such as a = $1,\nwhich needs to deal with the equivalence classes again.\n3) So, I added ec_processed and asked to process it again (generate_base_implied_equalities)\nafter the equivalence class changed (add_eq_member/process_equivalence).\n\nMaybe you have a better suggestion, please let me know.\n\n6) So we now have lazy_process_sublink callback? Does that mean we\nexpand sublinks in two places - sometimes lazily, sometimes not?\n\nYes, not all sublink is delayed. Let me explain this:\n1) I added a GUC switch enable_lazy_process_sublink. If it is turned off, all lazy process sublink will not happen,\nqual pushdown to sublink depend on lazy procee sublink, which means no quals will be pushed down.\n2) Even if enable_lazy_process_sublink = true If Query in this level contains some complex features,\nsublink in this level query will not try do qual pushdown. (see function query_has_sublink_try_pushdown_qual).\nI want to support a minimum subset first. Then consider complex features such as CTE/DML.\n3) Finally, under conditions 1 and 2, all kinds of sublink contained in the SELECT clause or\nWHERE clause will delays expansion and try pushdown qual. The sublink elsewhere in the SQL statement\ndoes not delay process.\n\nThe current status meets my requirements for now. Of course, after this scheme is proved to be feasible, maybe\nwe can discuss that all sublinks are processed by overall delay, just like qual pushdown to subquery.\n\nthanks\n\nWenjing\n\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\nHi,\n\n+ /* The outer var could exist in any of the upper-level queries to find these roots */\n\nto find these roots -> so find these roots \n\n+ if (has_unexpand_sublink(root) && checkExprHasSubLink(node))\n\nhas_unexpand_sublink -> has_unexpanded_sublink\n\n+ if (enable_lazy_process_sublink)\n+ return true;\n\nThe above can be simplified to:\n\n return enable_lazy_process_sublink;\n\n+ if (checkExprHasSubLink(qual))\n+ {\n+ qual = lazy_process_sublink_qual(root, qual);\n+ newquals = lappend(newquals, qual);\n+ }\n+ else\n+ newquals = lappend(newquals, qual);\n\nSince the lappend() is common to both branches, you can remove the else clause. In the if block, only call lazy_process_sublink_qual().\n\n+ /* under lazy process sublink, parent root may have some data that child not need, so set it to NULL */\n+ subroot->join_info_list = NIL;\n\nminor correction to the comment above:\n under lazy process sublink, parent root may have some data that child does not need, so set it to NIL\n\n+void\n+preprocess_qual_conditions(PlannerInfo *root, Node *jtnode, bool istop)\n\nPlease add a comment explaining the meaning of istop.\n\n+ if (istop)\n+ f->quals = preprocess_expression_ext(root, f->quals, EXPRKIND_QUAL, false);\n+ else\n+ f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);\n\nI think the code would be more readable if you replace the preprocess_expression() call in else branch with call to preprocess_expression_ext().\n\n+ context->root->unexpand_sublink_counter++;\n\nunexpand_sublink_counter -> unexpanded_sublink_counter++\n\nFor sublink_query_push_qual(), the return at the end is not needed.\n\nFor condition_is_safe_pushdown_to_sublink, you can initialize context this way :\n\n+ equal_expr_info_context context = {0};\nI don't understand the benefits of doing this. Please give me some hints.\nWe can also see a number of memset initializations, such as get_range_partbound_string()\n\n\n+ if (cvar && cvar->varattno > 0 && equal(cvar, var))\n+ return true;\n\nThe last few lines of condition_is_safe_pushdown_to_sublink() can be written as:\n\n return cvar && cvar->varattno > 0 && equal(cvar, var);\n\n+ if (equal_expr_safety_check(node, &context))\n+ {\n+ /* It needs to be something like outer var = inner var */\n+ if (context.inner_var &&\n\nThe nested if blocks can be merged into one if block.\n\nCheers\n\nHI Zhihong Yu\n\nThank you for your attention.\nEvery suggestion you make makes the patch better.\nI have completed the v3 patch according to your suggestions.\nLooking forward to your feedback.\n\n\nWenjing", "msg_date": "Sun, 12 Dec 2021 20:51:08 +0800", "msg_from": "\"=?UTF-8?B?5pu+5paH5peMKOS5ieS7jik=?=\" <wenjing.zwj@alibaba-inc.com>", "msg_from_op": false, "msg_subject": "\n =?UTF-8?B?5Zue5aSN77yaUmU6IFJlOiDlm57lpI3vvJpSZTogSXMgaXQgd29ydGggcHVzaGluZyBjb25k?=\n =?UTF-8?B?aXRpb25zIHRvIHN1Ymxpbmsvc3VicGxhbj8=?=" }, { "msg_contents": "Fixed a bug found during testing.\n\n\nWenjing\n\n\n\n ------------------原始邮件 ------------------\n发件人:曾文旌(义从) <wenjing.zwj@alibaba-inc.com>\n发送时间:Sun Dec 12 20:51:08 2021\n收件人:Zhihong Yu <zyu@yugabyte.com>\n抄送:Tomas Vondra <tomas.vondra@enterprisedb.com>, wjzeng <wjzeng2012@gmail.com>, PostgreSQL Hackers <pgsql-hackers@postgresql.org>, shawn wang <shawn.wang.pg@gmail.com>, ggysxcq@gmail.com <ggysxcq@gmail.com>\n主题:回复:Re: Re: 回复:Re: Is it worth pushing conditions to sublink/subplan?\n\n\n\n\n ------------------原始邮件 ------------------\n发件人:Zhihong Yu <zyu@yugabyte.com>\n发送时间:Sun Dec 12 01:13:11 2021\n收件人:曾文旌(义从) <wenjing.zwj@alibaba-inc.com>\n抄送:Tomas Vondra <tomas.vondra@enterprisedb.com>, wjzeng <wjzeng2012@gmail.com>, PostgreSQL Hackers <pgsql-hackers@postgresql.org>, shawn wang <shawn.wang.pg@gmail.com>, ggysxcq@gmail.com <ggysxcq@gmail.com>\n主题:Re: Re: 回复:Re: Is it worth pushing conditions to sublink/subplan?\n\n\n\nOn Sat, Dec 11, 2021 at 7:31 AM 曾文旌(义从) <wenjing.zwj@alibaba-inc.com> wrote:\n\n\n\n\n ------------------原始邮件 ------------------\n发件人:Tomas Vondra <tomas.vondra@enterprisedb.com>\n发送时间:Wed Dec 8 11:26:35 2021\n收件人:曾文旌(义从) <wenjing.zwj@alibaba-inc.com>, shawn wang <shawn.wang.pg@gmail.com>, ggysxcq@gmail.com <ggysxcq@gmail.com>, PostgreSQL Hackers <pgsql-hackers@postgresql.org>\n抄送:wjzeng <wjzeng2012@gmail.com>\n主题:Re: 回复:Re: Is it worth pushing conditions to sublink/subplan?\n\nHi,\n\nOn 12/7/21 10:44, 曾文旌(义从) wrote:\n> Hi Hackers\n> \n> For my previous proposal, I developed a prototype and passed\n> regression testing. It works similarly to subquery's qual pushdown.\n> We know that sublink expands at the beginning of each level of\n> query. At this stage, The query's conditions and equivalence classes\n> are not processed. But after generate_base_implied_equalities the\n> conditions are processed, which is why qual can push down to \n> subquery but sublink not.\n> \n> My POC implementation chose to delay the sublink expansion in the\n> SELECT clause (targetList) and where clause. Specifically, it is\n> delayed after generate_base_implied_equalities. Thus, the equivalent\n> conditions already established in the Up level query can be easily\n> obtained in the sublink expansion process (make_subplan).\n> \n> For example, if the up level query has a.id = 10 and the sublink\n> query has a.id = b.id, then we get b.id = 10 and push it down to the\n> sublink quey. If b is a partitioned table and is partitioned by id,\n> then a large number of unrelated subpartitions are pruned out, This\n> optimizes a significant amount of Planner and SQL execution time, \n> especially if the partitioned table has a large number of\n> subpartitions and is what I want.\n> \n> Currently, There were two SQL failures in the regression test,\n> because the expansion order of sublink was changed, which did not\n> affect the execution result of SQL.\n> \n> Look forward to your suggestions on this proposal.\n> \n\nI took a quick look, and while I don't see / can't think of any problems\nwith delaying it until after generating implied equalities, there seems\nto be a number of gaps.\n\nThank you for your attention.\n\n1) Are there any regression tests exercising this modified behavior?\nMaybe there are, but if the only changes are due to change in order of\ntargetlist entries, that doesn't seem like a clear proof.\n\nIt'd be good to add a couple tests exercising both the positive and\nnegative case (i.e. when we can and can't pushdown a qual).\n\nI added several samples to the regress(qual_pushdown_to_sublink.sql). \nand I used the partition table to show the plan status of qual being pushed down into sublink.\nHopefully this will help you understand the details of this patch. Later, I will add more cases.\n2) apparently, contrib/postgres_fdw does crash like this:\n\n #3 0x000000000077b412 in adjust_appendrel_attrs_mutator\n (node=0x13f7ea0, context=0x7fffc3351b30) at appendinfo.c:470\n 470 Assert(!IsA(node, SubLink));\n (gdb) p node\n $1 = (Node *) 0x13f7ea0\n (gdb) p *node\n $2 = {type = T_SubLink}\n\n Backtrace attached.\n\nFor the patch attached in the last email, I passed all the tests under src/test/regress.\nAs you pointed out, there was a problem with regression under contrib(in contrib/postgres_fdw). \nThis time I fixed it and the current patch (V2) can pass the check-world.\n\n\n3) various parts of the patch really need at least some comments, like:\n\n - try_push_outer_qual_to_sublink_query really needs some docs\n\n - new stuff at the end of initsplan.c\n\nOk, I added some comments and will add more. If you have questions about any details,\nplease point them out directly.\n\n4) generate_base_implied_equalities\n\n shouldn't this\n\n if (ec->ec_processed)\n ;\n\n really be?\n\n if (ec->ec_processed)\n continue;\n\nYou are right. I fixed it.\n\n5) I'm not sure why we need the new ec_processed flag.\n\nI did this to eliminate duplicate equalities from the two generate_base_implied_equalities calls\n1) I need the base equivalent expression generated after generate_base_implied_equalities,\nwhich is used to pushdown qual to sublink(lazy_process_sublinks)\n2) The expansion of sublink may result in an equivalent expression with parameters, such as a = $1,\nwhich needs to deal with the equivalence classes again.\n3) So, I added ec_processed and asked to process it again (generate_base_implied_equalities)\nafter the equivalence class changed (add_eq_member/process_equivalence).\n\nMaybe you have a better suggestion, please let me know.\n\n6) So we now have lazy_process_sublink callback? Does that mean we\nexpand sublinks in two places - sometimes lazily, sometimes not?\n\nYes, not all sublink is delayed. Let me explain this:\n1) I added a GUC switch enable_lazy_process_sublink. If it is turned off, all lazy process sublink will not happen,\nqual pushdown to sublink depend on lazy procee sublink, which means no quals will be pushed down.\n2) Even if enable_lazy_process_sublink = true If Query in this level contains some complex features,\nsublink in this level query will not try do qual pushdown. (see function query_has_sublink_try_pushdown_qual).\nI want to support a minimum subset first. Then consider complex features such as CTE/DML.\n3) Finally, under conditions 1 and 2, all kinds of sublink contained in the SELECT clause or\nWHERE clause will delays expansion and try pushdown qual. The sublink elsewhere in the SQL statement\ndoes not delay process.\n\nThe current status meets my requirements for now. Of course, after this scheme is proved to be feasible, maybe\nwe can discuss that all sublinks are processed by overall delay, just like qual pushdown to subquery.\n\nthanks\n\nWenjing\n\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\nHi,\n\n+ /* The outer var could exist in any of the upper-level queries to find these roots */\n\nto find these roots -> so find these roots \n\n+ if (has_unexpand_sublink(root) && checkExprHasSubLink(node))\n\nhas_unexpand_sublink -> has_unexpanded_sublink\n\n+ if (enable_lazy_process_sublink)\n+ return true;\n\nThe above can be simplified to:\n\n return enable_lazy_process_sublink;\n\n+ if (checkExprHasSubLink(qual))\n+ {\n+ qual = lazy_process_sublink_qual(root, qual);\n+ newquals = lappend(newquals, qual);\n+ }\n+ else\n+ newquals = lappend(newquals, qual);\n\nSince the lappend() is common to both branches, you can remove the else clause. In the if block, only call lazy_process_sublink_qual().\n\n+ /* under lazy process sublink, parent root may have some data that child not need, so set it to NULL */\n+ subroot->join_info_list = NIL;\n\nminor correction to the comment above:\n under lazy process sublink, parent root may have some data that child does not need, so set it to NIL\n\n+void\n+preprocess_qual_conditions(PlannerInfo *root, Node *jtnode, bool istop)\n\nPlease add a comment explaining the meaning of istop.\n\n+ if (istop)\n+ f->quals = preprocess_expression_ext(root, f->quals, EXPRKIND_QUAL, false);\n+ else\n+ f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);\n\nI think the code would be more readable if you replace the preprocess_expression() call in else branch with call to preprocess_expression_ext().\n\n+ context->root->unexpand_sublink_counter++;\n\nunexpand_sublink_counter -> unexpanded_sublink_counter++\n\nFor sublink_query_push_qual(), the return at the end is not needed.\n\nFor condition_is_safe_pushdown_to_sublink, you can initialize context this way :\n\n+ equal_expr_info_context context = {0};\nI don't understand the benefits of doing this. Please give me some hints.\nWe can also see a number of memset initializations, such as get_range_partbound_string()\n\n\n+ if (cvar && cvar->varattno > 0 && equal(cvar, var))\n+ return true;\n\nThe last few lines of condition_is_safe_pushdown_to_sublink() can be written as:\n\n return cvar && cvar->varattno > 0 && equal(cvar, var);\n\n+ if (equal_expr_safety_check(node, &context))\n+ {\n+ /* It needs to be something like outer var = inner var */\n+ if (context.inner_var &&\n\nThe nested if blocks can be merged into one if block.\n\nCheers\n\nHI Zhihong Yu\n\nThank you for your attention.\nEvery suggestion you make makes the patch better.\nI have completed the v3 patch according to your suggestions.\nLooking forward to your feedback.\n\n\nWenjing", "msg_date": "Thu, 23 Dec 2021 19:52:05 +0800", "msg_from": "\"=?UTF-8?B?5pu+5paH5peMKOS5ieS7jik=?=\" <wenjing.zwj@alibaba-inc.com>", "msg_from_op": false, "msg_subject": "\n =?UTF-8?B?5Zue5aSN77ya5Zue5aSN77yaUmU6IFJlOiDlm57lpI3vvJpSZTogSXMgaXQgd29ydGggcHVz?=\n =?UTF-8?B?aGluZyBjb25kaXRpb25zIHRvIHN1Ymxpbmsvc3VicGxhbj8=?=" }, { "msg_contents": "On Thu, Dec 23, 2021 at 3:52 AM 曾文旌(义从) <wenjing.zwj@alibaba-inc.com> wrote:\n\n>\n> Fixed a bug found during testing.\n>\n>\n> Wenjing\n>\n>\n>>> Hi,\n+ if (condition_is_safe_pushdown_to_sublink(rinfo,\nexpr_info->outer))\n+ {\n+ /* replace qual expr from outer var = const to var = const\nand push down to sublink query */\n+ sublink_query_push_qual(subquery, (Node\n*)copyObject(rinfo->clause), expr_info->outer, expr_info->inner);\n\nSince sublink_query_push_qual() is always guarded\nby condition_is_safe_pushdown_to_sublink(), it seems\nsublink_query_push_qual() can be folded into\ncondition_is_safe_pushdown_to_sublink().\n\nFor generate_base_implied_equalities():\n\n+ if (ec->ec_processed)\n+ {\n+ ec_index++;\n+ continue;\n+ }\n+ else if (list_length(ec->ec_members) > 1)\n\nMinor comment: the keyword `else` can be omitted (due to `continue` above).\n\n+ * Since there may be an unexpanded sublink in the targetList,\n+ * we'll skip it for now.\n\nSince there may be an -> If there is an\n\n+ {\"lazy_process_sublink\", PGC_USERSET, QUERY_TUNING_METHOD,\n+ gettext_noop(\"enable lazy process sublink.\"),\n\nLooking at existing examples from src/backend/utils/misc/guc.c,\nenable_lazy_sublink_processing seems to be consistent with existing guc\nvariable naming.\n\n+lazy_process_sublinks(PlannerInfo *root, bool single_result_rte)\n\nlazy_process_sublinks -> lazily_process_sublinks\n\n+ else\n+ {\n /* There shouldn't be any OJ info to translate, as yet */\n Assert(subroot->join_info_list == NIL);\n\nIndentation for the else block is off.\n\n+ if (istop)\n+ f->quals = preprocess_expression_ext(root, f->quals,\nEXPRKIND_QUAL, false);\n+ else\n+ f->quals = preprocess_expression_ext(root, f->quals,\nEXPRKIND_QUAL, true);\n\nThe above can be written as:\n\n+ f->quals = preprocess_expression_ext(root, f->quals,\nEXPRKIND_QUAL, !istop);\n\nFor find_equal_conditions_contain_uplevelvar_in_sublink_query():\n+ context.has_unexpected_expr == false &&\n`!context.has_unexpected_expr` should suffice\n\nequal_expr_safety_check -> is_equal_expr_safe\n\nCheers\n\nOn Thu, Dec 23, 2021 at 3:52 AM 曾文旌(义从) <wenjing.zwj@alibaba-inc.com> wrote:Fixed a bug found during testing.WenjingHi,+           if (condition_is_safe_pushdown_to_sublink(rinfo, expr_info->outer))+           {+               /* replace qual expr from outer var = const to var = const and push down to sublink query */+               sublink_query_push_qual(subquery, (Node *)copyObject(rinfo->clause), expr_info->outer, expr_info->inner);Since sublink_query_push_qual() is always guarded by condition_is_safe_pushdown_to_sublink(), it seems sublink_query_push_qual() can be folded into condition_is_safe_pushdown_to_sublink().For generate_base_implied_equalities():+       if (ec->ec_processed)+       {+           ec_index++;+           continue;+       }+       else if (list_length(ec->ec_members) > 1)Minor comment: the keyword `else` can be omitted (due to `continue` above).+            * Since there may be an unexpanded sublink in the targetList,+            * we'll skip it for now.Since there may be an -> If there is an+       {\"lazy_process_sublink\", PGC_USERSET, QUERY_TUNING_METHOD,+           gettext_noop(\"enable lazy process sublink.\"),Looking at existing examples from src/backend/utils/misc/guc.c, enable_lazy_sublink_processing seems to be consistent with existing guc variable naming.+lazy_process_sublinks(PlannerInfo *root, bool single_result_rte)lazy_process_sublinks -> lazily_process_sublinks+   else+   {    /* There shouldn't be any OJ info to translate, as yet */    Assert(subroot->join_info_list == NIL);Indentation for the else block is off.+       if (istop)+           f->quals = preprocess_expression_ext(root, f->quals, EXPRKIND_QUAL, false);+       else+           f->quals = preprocess_expression_ext(root, f->quals, EXPRKIND_QUAL, true);The above can be written as:+           f->quals = preprocess_expression_ext(root, f->quals, EXPRKIND_QUAL, !istop);For find_equal_conditions_contain_uplevelvar_in_sublink_query():+               context.has_unexpected_expr == false &&`!context.has_unexpected_expr` should sufficeequal_expr_safety_check -> is_equal_expr_safeCheers", "msg_date": "Fri, 24 Dec 2021 10:28:57 -0800", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "\n =?UTF-8?B?UmU6IOWbnuWkje+8mlJlOiBSZTog5Zue5aSN77yaUmU6IElzIGl0IHdvcnRoIHB1c2hpbg==?=\n\t=?UTF-8?B?ZyBjb25kaXRpb25zIHRvIHN1Ymxpbmsvc3VicGxhbj8=?=" }, { "msg_contents": "I corrected it according to your suggestion.\n\nthanks\n\nWenjing.\n\n\nZhihong Yu <zyu@yugabyte.com> 于2021年12月25日周六 02:26写道:\n\n>\n>\n> On Thu, Dec 23, 2021 at 3:52 AM 曾文旌(义从) <wenjing.zwj@alibaba-inc.com>\n> wrote:\n>\n>>\n>> Fixed a bug found during testing.\n>>\n>>\n>> Wenjing\n>>\n>>\n>>>> Hi,\n> + if (condition_is_safe_pushdown_to_sublink(rinfo,\n> expr_info->outer))\n> + {\n> + /* replace qual expr from outer var = const to var = const\n> and push down to sublink query */\n> + sublink_query_push_qual(subquery, (Node\n> *)copyObject(rinfo->clause), expr_info->outer, expr_info->inner);\n>\n> Since sublink_query_push_qual() is always guarded\n> by condition_is_safe_pushdown_to_sublink(), it seems\n> sublink_query_push_qual() can be folded into\n> condition_is_safe_pushdown_to_sublink().\n>\n> For generate_base_implied_equalities():\n>\n> + if (ec->ec_processed)\n> + {\n> + ec_index++;\n> + continue;\n> + }\n> + else if (list_length(ec->ec_members) > 1)\n>\n> Minor comment: the keyword `else` can be omitted (due to `continue` above).\n>\n> + * Since there may be an unexpanded sublink in the targetList,\n> + * we'll skip it for now.\n>\n> Since there may be an -> If there is an\n>\n> + {\"lazy_process_sublink\", PGC_USERSET, QUERY_TUNING_METHOD,\n> + gettext_noop(\"enable lazy process sublink.\"),\n>\n> Looking at existing examples from src/backend/utils/misc/guc.c,\n> enable_lazy_sublink_processing seems to be consistent with existing guc\n> variable naming.\n>\n> +lazy_process_sublinks(PlannerInfo *root, bool single_result_rte)\n>\n> lazy_process_sublinks -> lazily_process_sublinks\n>\n> + else\n> + {\n> /* There shouldn't be any OJ info to translate, as yet */\n> Assert(subroot->join_info_list == NIL);\n>\n> Indentation for the else block is off.\n>\n> + if (istop)\n> + f->quals = preprocess_expression_ext(root, f->quals,\n> EXPRKIND_QUAL, false);\n> + else\n> + f->quals = preprocess_expression_ext(root, f->quals,\n> EXPRKIND_QUAL, true);\n>\n> The above can be written as:\n>\n> + f->quals = preprocess_expression_ext(root, f->quals,\n> EXPRKIND_QUAL, !istop);\n>\n> For find_equal_conditions_contain_uplevelvar_in_sublink_query():\n> + context.has_unexpected_expr == false &&\n> `!context.has_unexpected_expr` should suffice\n>\n> equal_expr_safety_check -> is_equal_expr_safe\n>\n> Cheers\n>\n>", "msg_date": "Thu, 6 Jan 2022 14:28:53 +0800", "msg_from": "wenjing <wjzeng2012@gmail.com>", "msg_from_op": false, "msg_subject": "\n =?UTF-8?B?UmU6IOWbnuWkje+8mlJlOiBSZTog5Zue5aSN77yaUmU6IElzIGl0IHdvcnRoIHB1c2hpbg==?=\n\t=?UTF-8?B?ZyBjb25kaXRpb25zIHRvIHN1Ymxpbmsvc3VicGxhbj8=?=" } ]
[ { "msg_contents": "Here is a patch to add support for hexadecimal, octal, and binary \ninteger literals:\n\n 0x42E\n 0o112\n 0b100101\n\nper SQL:202x draft.\n\nThis adds support in the lexer as well as in the integer type input \nfunctions.\n\nThose core parts are straightforward enough, but there are a bunch of \nother places where integers are parsed, and one could consider in each \ncase whether they should get the same treatment, for example the \nreplication syntax lexer, or input function for oid, numeric, and \nint2vector. There are also some opportunities to move some code around, \nfor example scanint8() could be in numutils.c. I have also looked with \nsome suspicion at some details of the number lexing in ecpg, but haven't \nfound anything I could break yet. Suggestions are welcome.", "msg_date": "Mon, 16 Aug 2021 11:51:50 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Non-decimal integer literals" }, { "msg_contents": "On Mon, Aug 16, 2021 at 5:52 AM Peter Eisentraut <\npeter.eisentraut@enterprisedb.com> wrote:\n>\n> Here is a patch to add support for hexadecimal, octal, and binary\n> integer literals:\n>\n> 0x42E\n> 0o112\n> 0b100101\n>\n> per SQL:202x draft.\n>\n> This adds support in the lexer as well as in the integer type input\n> functions.\n\nThe one thing that jumped out at me on a cursory reading is the {integer}\nrule, which seems to be used nowhere except to\ncall process_integer_literal, which must then inspect the token text to\nfigure out what type of integer it is. Maybe consider 4 separate\nprocess_*_literal functions?\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Mon, Aug 16, 2021 at 5:52 AM Peter Eisentraut <peter.eisentraut@enterprisedb.com> wrote:>> Here is a patch to add support for hexadecimal, octal, and binary> integer literals:>>      0x42E>      0o112>      0b100101>> per SQL:202x draft.>> This adds support in the lexer as well as in the integer type input> functions.The one thing that jumped out at me on a cursory reading is the {integer} rule, which seems to be used nowhere except to call process_integer_literal, which must then inspect the token text to figure out what type of integer it is. Maybe consider 4 separate process_*_literal functions?--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Mon, 16 Aug 2021 11:32:37 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 16.08.21 17:32, John Naylor wrote:\n> The one thing that jumped out at me on a cursory reading is \n> the {integer} rule, which seems to be used nowhere except to \n> call process_integer_literal, which must then inspect the token text to \n> figure out what type of integer it is. Maybe consider 4 separate \n> process_*_literal functions?\n\nAgreed, that can be done in a simpler way. Here is an updated patch.", "msg_date": "Tue, 7 Sep 2021 13:13:10 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Tue, Sep 7, 2021 at 4:13 AM Peter Eisentraut <\npeter.eisentraut@enterprisedb.com> wrote:\n\n> On 16.08.21 17:32, John Naylor wrote:\n> > The one thing that jumped out at me on a cursory reading is\n> > the {integer} rule, which seems to be used nowhere except to\n> > call process_integer_literal, which must then inspect the token text to\n> > figure out what type of integer it is. Maybe consider 4 separate\n> > process_*_literal functions?\n>\n> Agreed, that can be done in a simpler way. Here is an updated patch.\n>\nHi,\nMinor comment:\n\n+SELECT int4 '0o112';\n\nMaybe involve digits of up to 7 in the octal test case.\n\nThanks\n\nOn Tue, Sep 7, 2021 at 4:13 AM Peter Eisentraut <peter.eisentraut@enterprisedb.com> wrote:On 16.08.21 17:32, John Naylor wrote:\n> The one thing that jumped out at me on a cursory reading is \n> the {integer} rule, which seems to be used nowhere except to \n> call process_integer_literal, which must then inspect the token text to \n> figure out what type of integer it is. Maybe consider 4 separate \n> process_*_literal functions?\n\nAgreed, that can be done in a simpler way.  Here is an updated patch.Hi,Minor comment:+SELECT int4 '0o112';Maybe involve digits of up to 7 in the octal test case.Thanks", "msg_date": "Tue, 7 Sep 2021 04:50:15 -0700", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 8/16/21 11:51 AM, Peter Eisentraut wrote:\n> Here is a patch to add support for hexadecimal, octal, and binary\n> integer literals:\n> \n>     0x42E\n>     0o112\n>     0b100101\n> \n> per SQL:202x draft.\n\nIs there any hope of adding the optional underscores? I see a potential\nproblem there as SELECT 1_a; is currently parsed as SELECT 1 AS _a; when\nit should be parsed as SELECT 1_ AS a; or perhaps even as an error since\n0x1_a would be a valid number with no alias.\n\n(The standard does not allow identifiers to begin with _ but we do...)\n-- \nVik Fearing\n\n\n", "msg_date": "Wed, 8 Sep 2021 14:44:45 +0200", "msg_from": "Vik Fearing <vik@postgresfriends.org>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "Vik Fearing <vik@postgresfriends.org> writes:\n> On 8/16/21 11:51 AM, Peter Eisentraut wrote:\n>> Here is a patch to add support for hexadecimal, octal, and binary\n>> integer literals:\n>> \n>>     0x42E\n>>     0o112\n>>     0b100101\n>> \n>> per SQL:202x draft.\n\n> Is there any hope of adding the optional underscores? I see a potential\n> problem there as SELECT 1_a; is currently parsed as SELECT 1 AS _a; when\n> it should be parsed as SELECT 1_ AS a; or perhaps even as an error since\n> 0x1_a would be a valid number with no alias.\n\nEven without that point, this patch *is* going to break valid queries,\nbecause every one of those cases is a valid number-followed-by-identifier\ntoday, e.g.\n\nregression=# select 0x42e;\n x42e \n------\n 0\n(1 row)\n\nAFAIR we've seen exactly zero field demand for this feature,\nso I kind of wonder why we're in such a hurry to adopt something\nthat hasn't even made it past draft-standard status.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 08 Sep 2021 09:14:34 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 9/8/21 3:14 PM, Tom Lane wrote:\n> Vik Fearing <vik@postgresfriends.org> writes:\n> \n>> Is there any hope of adding the optional underscores? I see a potential\n>> problem there as SELECT 1_a; is currently parsed as SELECT 1 AS _a; when\n>> it should be parsed as SELECT 1_ AS a; or perhaps even as an error since\n>> 0x1_a would be a valid number with no alias.\n> \n> Even without that point, this patch *is* going to break valid queries,\n> because every one of those cases is a valid number-followed-by-identifier\n> today,\n\nAh, true that. So if this does go in, we may as well add the\nunderscores at the same time.\n\n> AFAIR we've seen exactly zero field demand for this feature,\n\nI have often wanted something like this, even if I didn't bring it up on\nthis list. I have had customers who have wanted this, too. My response\nhas always been to show these exact problems to explain why it's not\npossible, but if it's going to be in the standard then I favor doing it.\n\nI have never really had a use for octal, but sometimes binary and hex\nmake things much clearer. Having a grouping separator for large numbers\nis even more useful.\n\n> so I kind of wonder why we're in such a hurry to adopt something\n> that hasn't even made it past draft-standard status.\nI don't really see a hurry here. I am fine with waiting until the draft\nbecomes final.\n-- \nVik Fearing\n\n\n", "msg_date": "Thu, 9 Sep 2021 16:08:04 +0200", "msg_from": "Vik Fearing <vik@postgresfriends.org>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 07.09.21 13:50, Zhihong Yu wrote:\n> On 16.08.21 17:32, John Naylor wrote:\n> > The one thing that jumped out at me on a cursory reading is\n> > the {integer} rule, which seems to be used nowhere except to\n> > call process_integer_literal, which must then inspect the token\n> text to\n> > figure out what type of integer it is. Maybe consider 4 separate\n> > process_*_literal functions?\n> \n> Agreed, that can be done in a simpler way.  Here is an updated patch.\n> \n> Hi,\n> Minor comment:\n> \n> +SELECT int4 '0o112';\n> \n> Maybe involve digits of up to 7 in the octal test case.\n\nGood point, here is a lightly updated patch.", "msg_date": "Tue, 28 Sep 2021 17:26:51 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "\nOn 09.09.21 16:08, Vik Fearing wrote:\n>> Even without that point, this patch *is* going to break valid queries,\n>> because every one of those cases is a valid number-followed-by-identifier\n>> today,\n> \n> Ah, true that. So if this does go in, we may as well add the\n> underscores at the same time.\n\nYeah, looks like I'll need to look into the identifier lexing issues \npreviously discussed. I'll attack that during the next commit fest.\n\n>> so I kind of wonder why we're in such a hurry to adopt something\n>> that hasn't even made it past draft-standard status.\n> I don't really see a hurry here. I am fine with waiting until the draft\n> becomes final.\n\nRight, the point is to explore this now so that it can be ready when the \nstandard is ready.\n\n\n", "msg_date": "Tue, 28 Sep 2021 17:30:28 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 28.09.21 17:30, Peter Eisentraut wrote:\n> On 09.09.21 16:08, Vik Fearing wrote:\n>>> Even without that point, this patch *is* going to break valid queries,\n>>> because every one of those cases is a valid \n>>> number-followed-by-identifier\n>>> today,\n>>\n>> Ah, true that.  So if this does go in, we may as well add the\n>> underscores at the same time.\n> \n> Yeah, looks like I'll need to look into the identifier lexing issues \n> previously discussed.  I'll attack that during the next commit fest.\n\nHere is an updated patch for this. It's the previous patch polished a \nbit more, and it contains changes so that numeric literals reject \ntrailing identifier parts without whitespace in between, as discussed. \nMaybe I should split that into incremental patches, but for now I only \nhave the one. I don't have a patch for the underscores in numeric \nliterals yet. It's in progress, but not ready.", "msg_date": "Mon, 1 Nov 2021 07:09:15 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 01.11.21 07:09, Peter Eisentraut wrote:\n> Here is an updated patch for this.  It's the previous patch polished a \n> bit more, and it contains changes so that numeric literals reject \n> trailing identifier parts without whitespace in between, as discussed. \n> Maybe I should split that into incremental patches, but for now I only \n> have the one.  I don't have a patch for the underscores in numeric \n> literals yet.  It's in progress, but not ready.\n\nHere is a progressed version of this work, split into more incremental \npatches. The first three patches are harmless code cleanups. Patch 3 \nhas an interesting naming conflict, noted in the commit message; ideas \nwelcome. Patches 4 and 5 handle the rejection of trailing junk after \nnumeric literals, as discussed. I have expanded that compared to the v4 \npatch to also cover non-integer literals. It also comes with more tests \nnow. Patch 6 is the titular introduction of non-decimal integer \nliterals, unchanged from before.", "msg_date": "Thu, 25 Nov 2021 14:17:52 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Thu, Nov 25, 2021 at 5:18 AM Peter Eisentraut <\npeter.eisentraut@enterprisedb.com> wrote:\n\n> On 01.11.21 07:09, Peter Eisentraut wrote:\n> > Here is an updated patch for this. It's the previous patch polished a\n> > bit more, and it contains changes so that numeric literals reject\n> > trailing identifier parts without whitespace in between, as discussed.\n> > Maybe I should split that into incremental patches, but for now I only\n> > have the one. I don't have a patch for the underscores in numeric\n> > literals yet. It's in progress, but not ready.\n>\n> Here is a progressed version of this work, split into more incremental\n> patches. The first three patches are harmless code cleanups. Patch 3\n> has an interesting naming conflict, noted in the commit message; ideas\n> welcome. Patches 4 and 5 handle the rejection of trailing junk after\n> numeric literals, as discussed. I have expanded that compared to the v4\n> patch to also cover non-integer literals. It also comes with more tests\n> now. Patch 6 is the titular introduction of non-decimal integer\n> literals, unchanged from before.\n\nHi,\nFor patch 3,\n\n+int64\n+pg_strtoint64(const char *s)\n\nHow about naming the above function pg_scanint64()?\npg_strtoint64xx() can be named pg_strtoint64() - this would align with\nexisting function:\n\npg_strtouint64(const char *str, char **endptr, int base)\n\nCheers\n\nOn Thu, Nov 25, 2021 at 5:18 AM Peter Eisentraut <peter.eisentraut@enterprisedb.com> wrote:On 01.11.21 07:09, Peter Eisentraut wrote:\n> Here is an updated patch for this.  It's the previous patch polished a \n> bit more, and it contains changes so that numeric literals reject \n> trailing identifier parts without whitespace in between, as discussed. \n> Maybe I should split that into incremental patches, but for now I only \n> have the one.  I don't have a patch for the underscores in numeric \n> literals yet.  It's in progress, but not ready.\n\nHere is a progressed version of this work, split into more incremental \npatches.  The first three patches are harmless code cleanups.  Patch 3 \nhas an interesting naming conflict, noted in the commit message; ideas \nwelcome.  Patches 4 and 5 handle the rejection of trailing junk after \nnumeric literals, as discussed.  I have expanded that compared to the v4 \npatch to also cover non-integer literals.  It also comes with more tests \nnow.  Patch 6 is the titular introduction of non-decimal integer \nliterals, unchanged from before.Hi,For patch 3,+int64+pg_strtoint64(const char *s) How about naming the above function pg_scanint64()?pg_strtoint64xx() can be named pg_strtoint64() - this would align with existing function:pg_strtouint64(const char *str, char **endptr, int base)Cheers", "msg_date": "Thu, 25 Nov 2021 07:46:51 -0800", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "Hi Peter,\n\n0001\n\n-/* we no longer allow unary minus in numbers.\n- * instead we pass it separately to parser. there it gets\n- * coerced via doNegate() -- Leon aug 20 1999\n+/*\n+ * Numbers\n+ *\n+ * Unary minus is not part of a number here. Instead we pass it\nseparately to\n+ * parser, and there it gets coerced via doNegate().\n\nIf we're going to change the comment anyway, \"the parser\" sounds more\nnatural. Aside from that, 0001 and 0002 can probably be pushed now, if you\nlike. I don't have any good ideas about 0003 at the moment.\n\n0005\n\n--- a/src/interfaces/ecpg/preproc/pgc.l\n+++ b/src/interfaces/ecpg/preproc/pgc.l\n@@ -365,6 +365,10 @@ real ({integer}|{decimal})[Ee][-+]?{digit}+\n realfail1 ({integer}|{decimal})[Ee]\n realfail2 ({integer}|{decimal})[Ee][-+]\n\n+integer_junk {integer}{ident_start}\n+decimal_junk {decimal}{ident_start}\n+real_junk {real}{ident_start}\n\nA comment might be good here to explain these are only in ECPG for\nconsistency with the other scanners. Not really important, though.\n\n0006\n\n+{hexfail} {\n+ yyerror(\"invalid hexadecimal integer\");\n+ }\n+{octfail} {\n+ yyerror(\"invalid octal integer\");\n }\n-{decimal} {\n+{binfail} {\n+ yyerror(\"invalid binary integer\");\n+ }\n\nIt seems these could use SET_YYLLOC(), since the error cursor doesn't match\nother failure states:\n\n+SELECT 0b;\n+ERROR: invalid binary integer at or near \"SELECT 0b\"\n+LINE 1: SELECT 0b;\n+ ^\n+SELECT 1b;\n+ERROR: trailing junk after numeric literal at or near \"1b\"\n+LINE 1: SELECT 1b;\n+ ^\n\nWe might consider some tests for ECPG since lack of coverage has been a\nproblem.\n\nAlso, I'm curious: how does the spec work as far as deciding the year of\nrelease, or feature-freezing of new items?\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nHi Peter,0001-/* we no longer allow unary minus in numbers.- * instead we pass it separately to parser. there it gets- * coerced via doNegate() -- Leon aug 20 1999+/*+ * Numbers+ *+ * Unary minus is not part of a number here.  Instead we pass it separately to+ * parser, and there it gets coerced via doNegate().If we're going to change the comment anyway, \"the parser\" sounds more natural. Aside from that, 0001 and 0002 can probably be pushed now, if you like. I don't have any good ideas about 0003 at the moment.0005--- a/src/interfaces/ecpg/preproc/pgc.l+++ b/src/interfaces/ecpg/preproc/pgc.l@@ -365,6 +365,10 @@ real ({integer}|{decimal})[Ee][-+]?{digit}+ realfail1 ({integer}|{decimal})[Ee] realfail2 ({integer}|{decimal})[Ee][-+] +integer_junk {integer}{ident_start}+decimal_junk {decimal}{ident_start}+real_junk {real}{ident_start}A comment might be good here to explain these are only in ECPG for consistency with the other scanners. Not really important, though.0006+{hexfail}\t\t{+\t\t\t\t\tyyerror(\"invalid hexadecimal integer\");+\t\t\t\t}+{octfail}\t\t{+\t\t\t\t\tyyerror(\"invalid octal integer\"); \t\t\t\t}-{decimal}\t\t{+{binfail}\t\t{+\t\t\t\t\tyyerror(\"invalid binary integer\");+\t\t\t\t}It seems these could use SET_YYLLOC(), since the error cursor doesn't match other failure states:+SELECT 0b;+ERROR:  invalid binary integer at or near \"SELECT 0b\"+LINE 1: SELECT 0b;+        ^+SELECT 1b;+ERROR:  trailing junk after numeric literal at or near \"1b\"+LINE 1: SELECT 1b;+               ^We might consider some tests for ECPG since lack of coverage has been a problem.Also, I'm curious: how does the spec work as far as deciding the year of release, or feature-freezing of new items?--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Thu, 25 Nov 2021 13:51:43 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 25.11.21 16:46, Zhihong Yu wrote:\n> For patch 3,\n> \n> +int64\n> +pg_strtoint64(const char *s)\n> \n> How about naming the above function pg_scanint64()?\n> pg_strtoint64xx() can be named pg_strtoint64() - this would align with \n> existing function:\n> \n> pg_strtouint64(const char *str, char **endptr, int base)\n\nThat would be one way. But the existing pg_strtointNN() functions are \npretty widely used, so I would tend toward finding another name for the \nless used pg_strtouint64(), maybe pg_strtouint64x() (\"extended\").\n\n\n\n", "msg_date": "Wed, 1 Dec 2021 16:40:19 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 25.11.21 18:51, John Naylor wrote:\n> If we're going to change the comment anyway, \"the parser\" sounds more \n> natural. Aside from that, 0001 and 0002 can probably be pushed now, if \n> you like.\n\ndone\n\n> --- a/src/interfaces/ecpg/preproc/pgc.l\n> +++ b/src/interfaces/ecpg/preproc/pgc.l\n> @@ -365,6 +365,10 @@ real ({integer}|{decimal})[Ee][-+]?{digit}+\n>  realfail1 ({integer}|{decimal})[Ee]\n>  realfail2 ({integer}|{decimal})[Ee][-+]\n> \n> +integer_junk {integer}{ident_start}\n> +decimal_junk {decimal}{ident_start}\n> +real_junk {real}{ident_start}\n> \n> A comment might be good here to explain these are only in ECPG for \n> consistency with the other scanners. Not really important, though.\n\nYeah, it's a bit weird that not all the symbols are used in ecpg. I'll \nlook into explaining this better.\n\n> 0006\n> \n> +{hexfail} {\n> + yyerror(\"invalid hexadecimal integer\");\n> + }\n> +{octfail} {\n> + yyerror(\"invalid octal integer\");\n>   }\n> -{decimal} {\n> +{binfail} {\n> + yyerror(\"invalid binary integer\");\n> + }\n> \n> It seems these could use SET_YYLLOC(), since the error cursor doesn't \n> match other failure states:\n\nok\n\n> We might consider some tests for ECPG since lack of coverage has been a \n> problem.\n\nright\n\n> Also, I'm curious: how does the spec work as far as deciding the year of \n> release, or feature-freezing of new items?\n\nThe schedule has recently been extended again, so the current plan is \nfor SQL:202x with x=3, with feature freeze in mid-2022.\n\nSo the feature patches in this thread are in my mind now targeting \nPG15+1. But the preparation work (up to v5-0005, and some other number \nparsing refactoring that I'm seeing) could be considered for PG15.\n\nI'll move this to the next CF and come back with an updated patch set in \na little while.\n\n\n", "msg_date": "Wed, 1 Dec 2021 16:47:09 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "There has been some other refactoring going on, which made this patch \nset out of date. So here is an update.\n\nThe old pg_strtouint64() has been removed, so there is no longer a \nnaming concern with patch 0001. That one should be good to go.\n\nI also found that yet another way to parse integers in pg_atoi() has \nmostly faded away in utility, so I removed the last two callers and \nremoved the function in 0002 and 0003.\n\nThe remaining patches are as before, with some of the review comments \napplied. I still need to write some lexing unit tests for ecpg, which I \nhaven't gotten to yet. This affects patches 0004 and 0005.\n\nAs mentioned before, patches 0006 and 0007 are more feature previews at \nthis point.\n\n\nOn 01.12.21 16:47, Peter Eisentraut wrote:\n> On 25.11.21 18:51, John Naylor wrote:\n>> If we're going to change the comment anyway, \"the parser\" sounds more \n>> natural. Aside from that, 0001 and 0002 can probably be pushed now, if \n>> you like.\n> \n> done\n> \n>> --- a/src/interfaces/ecpg/preproc/pgc.l\n>> +++ b/src/interfaces/ecpg/preproc/pgc.l\n>> @@ -365,6 +365,10 @@ real ({integer}|{decimal})[Ee][-+]?{digit}+\n>>   realfail1 ({integer}|{decimal})[Ee]\n>>   realfail2 ({integer}|{decimal})[Ee][-+]\n>>\n>> +integer_junk {integer}{ident_start}\n>> +decimal_junk {decimal}{ident_start}\n>> +real_junk {real}{ident_start}\n>>\n>> A comment might be good here to explain these are only in ECPG for \n>> consistency with the other scanners. Not really important, though.\n> \n> Yeah, it's a bit weird that not all the symbols are used in ecpg.  I'll \n> look into explaining this better.\n> \n>> 0006\n>>\n>> +{hexfail} {\n>> + yyerror(\"invalid hexadecimal integer\");\n>> + }\n>> +{octfail} {\n>> + yyerror(\"invalid octal integer\");\n>>    }\n>> -{decimal} {\n>> +{binfail} {\n>> + yyerror(\"invalid binary integer\");\n>> + }\n>>\n>> It seems these could use SET_YYLLOC(), since the error cursor doesn't \n>> match other failure states:\n> \n> ok\n> \n>> We might consider some tests for ECPG since lack of coverage has been \n>> a problem.\n> \n> right\n> \n>> Also, I'm curious: how does the spec work as far as deciding the year \n>> of release, or feature-freezing of new items?\n> \n> The schedule has recently been extended again, so the current plan is \n> for SQL:202x with x=3, with feature freeze in mid-2022.\n> \n> So the feature patches in this thread are in my mind now targeting \n> PG15+1.  But the preparation work (up to v5-0005, and some other number \n> parsing refactoring that I'm seeing) could be considered for PG15.\n> \n> I'll move this to the next CF and come back with an updated patch set in \n> a little while.\n> \n>", "msg_date": "Thu, 30 Dec 2021 10:43:30 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "Another modest update, because of the copyright year update preventing \nthe previous patches from applying cleanly.\n\nI also did a bit of work on the ecpg scanner so that it also handles \nsome errors on par with the main scanner.\n\nThere is still no automated testing of this in ecpg, but I have a bunch \nof single-line test files that can provoke various errors. I will keep \nthese around and maybe put them into something more formal in the future.\n\n\nOn 30.12.21 10:43, Peter Eisentraut wrote:\n> There has been some other refactoring going on, which made this patch \n> set out of date.  So here is an update.\n> \n> The old pg_strtouint64() has been removed, so there is no longer a \n> naming concern with patch 0001.  That one should be good to go.\n> \n> I also found that yet another way to parse integers in pg_atoi() has \n> mostly faded away in utility, so I removed the last two callers and \n> removed the function in 0002 and 0003.\n> \n> The remaining patches are as before, with some of the review comments \n> applied.  I still need to write some lexing unit tests for ecpg, which I \n> haven't gotten to yet.  This affects patches 0004 and 0005.\n> \n> As mentioned before, patches 0006 and 0007 are more feature previews at \n> this point.\n> \n> \n> On 01.12.21 16:47, Peter Eisentraut wrote:\n>> On 25.11.21 18:51, John Naylor wrote:\n>>> If we're going to change the comment anyway, \"the parser\" sounds more \n>>> natural. Aside from that, 0001 and 0002 can probably be pushed now, \n>>> if you like.\n>>\n>> done\n>>\n>>> --- a/src/interfaces/ecpg/preproc/pgc.l\n>>> +++ b/src/interfaces/ecpg/preproc/pgc.l\n>>> @@ -365,6 +365,10 @@ real ({integer}|{decimal})[Ee][-+]?{digit}+\n>>>   realfail1 ({integer}|{decimal})[Ee]\n>>>   realfail2 ({integer}|{decimal})[Ee][-+]\n>>>\n>>> +integer_junk {integer}{ident_start}\n>>> +decimal_junk {decimal}{ident_start}\n>>> +real_junk {real}{ident_start}\n>>>\n>>> A comment might be good here to explain these are only in ECPG for \n>>> consistency with the other scanners. Not really important, though.\n>>\n>> Yeah, it's a bit weird that not all the symbols are used in ecpg. \n>> I'll look into explaining this better.\n>>\n>>> 0006\n>>>\n>>> +{hexfail} {\n>>> + yyerror(\"invalid hexadecimal integer\");\n>>> + }\n>>> +{octfail} {\n>>> + yyerror(\"invalid octal integer\");\n>>>    }\n>>> -{decimal} {\n>>> +{binfail} {\n>>> + yyerror(\"invalid binary integer\");\n>>> + }\n>>>\n>>> It seems these could use SET_YYLLOC(), since the error cursor doesn't \n>>> match other failure states:\n>>\n>> ok\n>>\n>>> We might consider some tests for ECPG since lack of coverage has been \n>>> a problem.\n>>\n>> right\n>>\n>>> Also, I'm curious: how does the spec work as far as deciding the year \n>>> of release, or feature-freezing of new items?\n>>\n>> The schedule has recently been extended again, so the current plan is \n>> for SQL:202x with x=3, with feature freeze in mid-2022.\n>>\n>> So the feature patches in this thread are in my mind now targeting \n>> PG15+1.  But the preparation work (up to v5-0005, and some other \n>> number parsing refactoring that I'm seeing) could be considered for PG15.\n>>\n>> I'll move this to the next CF and come back with an updated patch set \n>> in a little while.\n>>\n>>", "msg_date": "Thu, 13 Jan 2022 14:42:42 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "Rebased patch set\n\nOn 13.01.22 14:42, Peter Eisentraut wrote:\n> Another modest update, because of the copyright year update preventing \n> the previous patches from applying cleanly.\n> \n> I also did a bit of work on the ecpg scanner so that it also handles \n> some errors on par with the main scanner.\n> \n> There is still no automated testing of this in ecpg, but I have a bunch \n> of single-line test files that can provoke various errors.  I will keep \n> these around and maybe put them into something more formal in the future.\n> \n> \n> On 30.12.21 10:43, Peter Eisentraut wrote:\n>> There has been some other refactoring going on, which made this patch \n>> set out of date.  So here is an update.\n>>\n>> The old pg_strtouint64() has been removed, so there is no longer a \n>> naming concern with patch 0001.  That one should be good to go.\n>>\n>> I also found that yet another way to parse integers in pg_atoi() has \n>> mostly faded away in utility, so I removed the last two callers and \n>> removed the function in 0002 and 0003.\n>>\n>> The remaining patches are as before, with some of the review comments \n>> applied.  I still need to write some lexing unit tests for ecpg, which \n>> I haven't gotten to yet.  This affects patches 0004 and 0005.\n>>\n>> As mentioned before, patches 0006 and 0007 are more feature previews \n>> at this point.\n>>\n>>\n>> On 01.12.21 16:47, Peter Eisentraut wrote:\n>>> On 25.11.21 18:51, John Naylor wrote:\n>>>> If we're going to change the comment anyway, \"the parser\" sounds \n>>>> more natural. Aside from that, 0001 and 0002 can probably be pushed \n>>>> now, if you like.\n>>>\n>>> done\n>>>\n>>>> --- a/src/interfaces/ecpg/preproc/pgc.l\n>>>> +++ b/src/interfaces/ecpg/preproc/pgc.l\n>>>> @@ -365,6 +365,10 @@ real ({integer}|{decimal})[Ee][-+]?{digit}+\n>>>>   realfail1 ({integer}|{decimal})[Ee]\n>>>>   realfail2 ({integer}|{decimal})[Ee][-+]\n>>>>\n>>>> +integer_junk {integer}{ident_start}\n>>>> +decimal_junk {decimal}{ident_start}\n>>>> +real_junk {real}{ident_start}\n>>>>\n>>>> A comment might be good here to explain these are only in ECPG for \n>>>> consistency with the other scanners. Not really important, though.\n>>>\n>>> Yeah, it's a bit weird that not all the symbols are used in ecpg. \n>>> I'll look into explaining this better.\n>>>\n>>>> 0006\n>>>>\n>>>> +{hexfail} {\n>>>> + yyerror(\"invalid hexadecimal integer\");\n>>>> + }\n>>>> +{octfail} {\n>>>> + yyerror(\"invalid octal integer\");\n>>>>    }\n>>>> -{decimal} {\n>>>> +{binfail} {\n>>>> + yyerror(\"invalid binary integer\");\n>>>> + }\n>>>>\n>>>> It seems these could use SET_YYLLOC(), since the error cursor \n>>>> doesn't match other failure states:\n>>>\n>>> ok\n>>>\n>>>> We might consider some tests for ECPG since lack of coverage has \n>>>> been a problem.\n>>>\n>>> right\n>>>\n>>>> Also, I'm curious: how does the spec work as far as deciding the \n>>>> year of release, or feature-freezing of new items?\n>>>\n>>> The schedule has recently been extended again, so the current plan is \n>>> for SQL:202x with x=3, with feature freeze in mid-2022.\n>>>\n>>> So the feature patches in this thread are in my mind now targeting \n>>> PG15+1.  But the preparation work (up to v5-0005, and some other \n>>> number parsing refactoring that I'm seeing) could be considered for \n>>> PG15.\n>>>\n>>> I'll move this to the next CF and come back with an updated patch set \n>>> in a little while.\n>>>\n>>>", "msg_date": "Mon, 24 Jan 2022 09:41:20 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Mon, Jan 24, 2022 at 3:41 AM Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n> Rebased patch set\n\nWhat if someone finds this new behavior too permissive?\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 24 Jan 2022 13:53:16 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 24.01.22 19:53, Robert Haas wrote:\n> On Mon, Jan 24, 2022 at 3:41 AM Peter Eisentraut\n> <peter.eisentraut@enterprisedb.com> wrote:\n>> Rebased patch set\n> \n> What if someone finds this new behavior too permissive?\n\nWhich part exactly? There are several different changes proposed here.\n\n\n", "msg_date": "Tue, 25 Jan 2022 11:34:17 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Tue, Jan 25, 2022 at 5:34 AM Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n> On 24.01.22 19:53, Robert Haas wrote:\n> > On Mon, Jan 24, 2022 at 3:41 AM Peter Eisentraut\n> > <peter.eisentraut@enterprisedb.com> wrote:\n> >> Rebased patch set\n> >\n> > What if someone finds this new behavior too permissive?\n>\n> Which part exactly? There are several different changes proposed here.\n\nI was just going based on the description of the feature in your\noriginal post. If someone is hoping that int4in() will accept only\n^\\d+$ then they will be disappointed by this patch.\n\nMaybe nobody is hoping that, though.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 25 Jan 2022 13:15:43 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 2022-Jan-24, Peter Eisentraut wrote:\n\n> +decinteger\t\t{decdigit}(_?{decdigit})*\n> +hexinteger\t\t0[xX](_?{hexdigit})+\n> +octinteger\t\t0[oO](_?{octdigit})+\n> +bininteger\t\t0[bB](_?{bindigit})+\n\nI think there should be test cases for literals that these seemingly\nstrange expressions reject, which are a number with trailing _ (0x123_),\nand one with consecutive underscores __ (0x12__34).\n\nI like the idea of these literals. I would have found them useful on\nmany occassions.\n\n-- \nÁlvaro Herrera Valdivia, Chile — https://www.EnterpriseDB.com/\n\n\n", "msg_date": "Tue, 25 Jan 2022 15:43:35 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> On Tue, Jan 25, 2022 at 5:34 AM Peter Eisentraut\n> <peter.eisentraut@enterprisedb.com> wrote:\n>> Which part exactly? There are several different changes proposed here.\n\n> I was just going based on the description of the feature in your\n> original post. If someone is hoping that int4in() will accept only\n> ^\\d+$ then they will be disappointed by this patch.\n\nMaybe I misunderstood, but I thought this was about what you could\nwrite as a SQL literal, not about the I/O behavior of the integer\ntypes. I'd be -0.1 on changing the latter.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 25 Jan 2022 19:02:38 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 26.01.22 01:02, Tom Lane wrote:\n> Robert Haas <robertmhaas@gmail.com> writes:\n>> On Tue, Jan 25, 2022 at 5:34 AM Peter Eisentraut\n>> <peter.eisentraut@enterprisedb.com> wrote:\n>>> Which part exactly? There are several different changes proposed here.\n> \n>> I was just going based on the description of the feature in your\n>> original post. If someone is hoping that int4in() will accept only\n>> ^\\d+$ then they will be disappointed by this patch.\n> \n> Maybe I misunderstood, but I thought this was about what you could\n> write as a SQL literal, not about the I/O behavior of the integer\n> types. I'd be -0.1 on changing the latter.\n\nI think it would be strange if I/O routines would accept a different \nsyntax from the literals. Also, the behavior of a cast from string/text \nto a numeric type is usually defined in terms of what the literal syntax \nis, so they need to be aligned.\n\n\n", "msg_date": "Wed, 26 Jan 2022 16:10:39 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "\nOn 1/25/22 13:43, Alvaro Herrera wrote:\n> On 2022-Jan-24, Peter Eisentraut wrote:\n>\n>> +decinteger\t\t{decdigit}(_?{decdigit})*\n>> +hexinteger\t\t0[xX](_?{hexdigit})+\n>> +octinteger\t\t0[oO](_?{octdigit})+\n>> +bininteger\t\t0[bB](_?{bindigit})+\n> I think there should be test cases for literals that these seemingly\n> strange expressions reject, which are a number with trailing _ (0x123_),\n> and one with consecutive underscores __ (0x12__34).\n>\n> I like the idea of these literals. I would have found them useful on\n> many occassions.\n\n\n+1. I can't remember the number of times I have miscounted a long string\nof digits in a literal.\n\n\ncheers\n\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Wed, 26 Jan 2022 11:19:15 -0500", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Wed, Jan 26, 2022 at 10:10 PM Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n> [v8 patch]\n\n0001-0004 seem pretty straightforward.\n\n0005:\n\n {realfail1} {\n- /*\n- * throw back the [Ee], and figure out whether what\n- * remains is an {integer} or {decimal}.\n- */\n- yyless(yyleng - 1);\n SET_YYLLOC();\n- return process_integer_literal(yytext, yylval);\n+ yyerror(\"trailing junk after numeric literal\");\n }\n\nrealfail1 has been subsumed by integer_junk and decimal_junk, so that\npattern can be removed.\n\n <SQL>{\n+/*\n+ * Note that some trailing junk is valid in C (such as 100LL), so we contain\n+ * this to SQL mode.\n+ */\n\nIt seems Flex doesn't like C comments after the \"%%\", so this stanza\nwas indented in 0006. If these are to be committed separately, that\nfix should happen here.\n\n0006:\n\nMinor nit -- the s/decimal/numeric/ change doesn't seem to have any\nnotational advantage, but it's not worse, either.\n\n0007:\n\nI've attached an addendum to restore the no-backtrack property.\n\nWill the underscore syntax need treatment in the input routines as well?\n\n-- \nJohn Naylor\nEDB: http://www.enterprisedb.com", "msg_date": "Sun, 13 Feb 2022 19:14:07 +0700", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "Re: Peter Eisentraut\n> This adds support in the lexer as well as in the integer type input\n> functions.\n> \n> Those core parts are straightforward enough, but there are a bunch of other\n> places where integers are parsed, and one could consider in each case\n> whether they should get the same treatment, for example the replication\n> syntax lexer, or input function for oid, numeric, and int2vector.\n\nOne thing I always found weird is that timeline IDs appear most\nprominently as hex numbers in WAL filenames, but they are printed as\ndecimal in the log (\"new timeline id nn\"), and have to be specified as\ndecimal in recovery_target_timeline.\n\nPerhaps both these could make use of 0xhex numbers as well.\n\nChristoph\n\n\n", "msg_date": "Mon, 14 Feb 2022 19:49:59 +0100", "msg_from": "Christoph Berg <myon@debian.org>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "\nOn 13.02.22 13:14, John Naylor wrote:\n> On Wed, Jan 26, 2022 at 10:10 PM Peter Eisentraut\n> <peter.eisentraut@enterprisedb.com> wrote:\n>> [v8 patch]\n> \n> 0001-0004 seem pretty straightforward.\n\nThese have been committed.\n\n> \n> 0005:\n> \n> {realfail1} {\n> - /*\n> - * throw back the [Ee], and figure out whether what\n> - * remains is an {integer} or {decimal}.\n> - */\n> - yyless(yyleng - 1);\n> SET_YYLLOC();\n> - return process_integer_literal(yytext, yylval);\n> + yyerror(\"trailing junk after numeric literal\");\n> }\n> \n> realfail1 has been subsumed by integer_junk and decimal_junk, so that\n> pattern can be removed.\n\nCommitted with that change.\n\nI found that the JSON path lexer has the same trailing-junk issue. I \nhave researched the relevant ECMA standard and it explicitly points out \nthat this is not allowed. I will look into that separately. I'm just \npointing that out here because grepping for \"realfail1\" will still show \na hit after this.\n\nThe remaining patches are material for PG16 at this point, and I will \nset the commit fest item to returned with feedback in the meantime.\n\n> 0006:\n> \n> Minor nit -- the s/decimal/numeric/ change doesn't seem to have any\n> notational advantage, but it's not worse, either.\n\nI did that because with the addition of non-decimal literals, the word \n\"decimal\" becomes ambiguous or misleading. (It doesn't mean \"uses \ndecimal digits\" but \"has a decimal point\".) (Of course, \"numeric\" isn't \nentirely free of ambiguity, but there are only so many words available \nin this space. ;-) )\n\n> 0007:\n> \n> I've attached an addendum to restore the no-backtrack property.\n\nThanks, that is helpful.\n\n> Will the underscore syntax need treatment in the input routines as well?\n\nYeah, various additional work is required for this.\n\n\n", "msg_date": "Wed, 16 Feb 2022 11:11:05 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 16.02.22 11:11, Peter Eisentraut wrote:\n> The remaining patches are material for PG16 at this point, and I will \n> set the commit fest item to returned with feedback in the meantime.\n\nTime to continue with this.\n\nAttached is a rebased and cleaned up patch for non-decimal integer \nliterals. (I don't include the underscores-in-numeric literals patch. \nI'm keeping that for later.)\n\nTwo open issues from my notes:\n\nTechnically, numeric_in() should be made aware of this, but that seems \nrelatively complicated and maybe not necessary for the first iteration.\n\nTaking another look around ecpg to see how this interacts with C-syntax \ninteger literals. I'm not aware of any particular issues, but it's \nunderstandably tricky.\n\nOther than that, this seems pretty complete as a start.", "msg_date": "Mon, 10 Oct 2022 16:17:23 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "Hi Peter,\n\n /* process digits */\n+ if (ptr[0] == '0' && (ptr[1] == 'x' || ptr[1] == 'X'))\n+ {\n+ ptr += 2;\n+ while (*ptr && isxdigit((unsigned char) *ptr))\n+ {\n+ int8 digit = hexlookup[(unsigned char) *ptr];\n+\n+ if (unlikely(pg_mul_s16_overflow(tmp, 16, &tmp)) ||\n+ unlikely(pg_sub_s16_overflow(tmp, digit, &tmp)))\n+ goto out_of_range;\n+\n+ ptr++;\n+ }\n+ }\n+ else if (ptr[0] == '0' && (ptr[1] == 'o' || ptr[1] == 'O'))\n+ {\n+ ptr += 2;\n+\n+ while (*ptr && (*ptr >= '0' && *ptr <= '7'))\n+ {\n+ int8 digit = (*ptr++ - '0');\n+\n+ if (unlikely(pg_mul_s16_overflow(tmp, 8, &tmp)) ||\n+ unlikely(pg_sub_s16_overflow(tmp, digit, &tmp)))\n+ goto out_of_range;\n+ }\n+ }\n+ else if (ptr[0] == '0' && (ptr[1] == 'b' || ptr[1] == 'B'))\n+ {\n+ ptr += 2;\n+\n+ while (*ptr && (*ptr >= '0' && *ptr <= '1'))\n+ {\n+ int8 digit = (*ptr++ - '0');\n+\n+ if (unlikely(pg_mul_s16_overflow(tmp, 2, &tmp)) ||\n+ unlikely(pg_sub_s16_overflow(tmp, digit, &tmp)))\n+ goto out_of_range;\n+ }\n+ }\n+ else\n+ {\n while (*ptr && isdigit((unsigned char) *ptr))\n {\n int8 digit = (*ptr++ - '0');\n@@ -128,6 +181,7 @@ pg_strtoint16(const char *s)\n unlikely(pg_sub_s16_overflow(tmp, digit, &tmp)))\n goto out_of_range;\n }\n+ }\n\nWhat do you think if we move these code into a static inline function? like:\n\nstatic inline char*\nprocess_digits(char *ptr, int32 *result)\n{\n...\n}\n\nOn Mon, Oct 10, 2022 at 10:17 PM Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n>\n> On 16.02.22 11:11, Peter Eisentraut wrote:\n> > The remaining patches are material for PG16 at this point, and I will\n> > set the commit fest item to returned with feedback in the meantime.\n>\n> Time to continue with this.\n>\n> Attached is a rebased and cleaned up patch for non-decimal integer\n> literals. (I don't include the underscores-in-numeric literals patch.\n> I'm keeping that for later.)\n>\n> Two open issues from my notes:\n>\n> Technically, numeric_in() should be made aware of this, but that seems\n> relatively complicated and maybe not necessary for the first iteration.\n>\n> Taking another look around ecpg to see how this interacts with C-syntax\n> integer literals. I'm not aware of any particular issues, but it's\n> understandably tricky.\n>\n> Other than that, this seems pretty complete as a start.\n\n\n\n-- \nRegards\nJunwang Zhao\n\n\n", "msg_date": "Tue, 11 Oct 2022 11:29:35 +0800", "msg_from": "Junwang Zhao <zhjwpku@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 11.10.22 05:29, Junwang Zhao wrote:\n> What do you think if we move these code into a static inline function? like:\n> \n> static inline char*\n> process_digits(char *ptr, int32 *result)\n> {\n> ...\n> }\n\nHow would you handle the different ways each branch checks for valid \ndigits and computes the value of each digit?\n\n\n\n", "msg_date": "Tue, 11 Oct 2022 10:59:30 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Tue, Oct 11, 2022 at 4:59 PM Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n>\n> On 11.10.22 05:29, Junwang Zhao wrote:\n> > What do you think if we move these code into a static inline function? like:\n> >\n> > static inline char*\n> > process_digits(char *ptr, int32 *result)\n> > {\n> > ...\n> > }\n>\n> How would you handle the different ways each branch checks for valid\n> digits and computes the value of each digit?\n>\n\nDidn't notice that, sorry for the noise ;(\n\n\n-- \nRegards\nJunwang Zhao\n\n\n", "msg_date": "Tue, 11 Oct 2022 18:16:08 +0800", "msg_from": "Junwang Zhao <zhjwpku@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Mon, Oct 10, 2022 at 9:17 PM Peter Eisentraut <\npeter.eisentraut@enterprisedb.com> wrote:\n\n> Taking another look around ecpg to see how this interacts with C-syntax\n> integer literals. I'm not aware of any particular issues, but it's\n> understandably tricky.\n\nI can find no discussion in the archives about the commit that added \"xch\":\n\ncommit 6fb3c3f78fbb2296894424f6e3183d339915eac7\nAuthor: Michael Meskes <meskes@postgresql.org>\nDate: Fri Oct 15 19:02:08 1999 +0000\n\n *** empty log message ***\n\n...and I can't think of why bounds checking a C literal was done like this.\n\nRegarding the patch, it looks good overall. My only suggestion would be to\nadd a regression test for just below and just above overflow, at least for\nint2.\n\nMinor nits:\n\n- * Process {integer}. Note this will also do the right thing with\n{decimal},\n+ * Process {*integer}. Note this will also do the right thing with\n{numeric},\n\nI scratched my head for a while, thinking this was Flex syntax, until I\nrealized my brain was supposed to do shell-globbing first, at which point I\ncould see it was referring to multiple Flex rules. I'd try to rephrase.\n\n+T661 Non-decimal integer literals YES SQL:202x draft\n\nIs there an ETA yet?\n\nAlso, it's not this patch's job to do it, but there are at least a half\ndozen places that open-code turning a hex char into a number. It might be a\ngood easy \"todo item\" to unify that.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Mon, Oct 10, 2022 at 9:17 PM Peter Eisentraut <peter.eisentraut@enterprisedb.com> wrote:> Taking another look around ecpg to see how this interacts with C-syntax> integer literals.  I'm not aware of any particular issues, but it's> understandably tricky.I can find no discussion in the archives about the commit that added \"xch\":commit 6fb3c3f78fbb2296894424f6e3183d339915eac7Author: Michael Meskes <meskes@postgresql.org>Date:   Fri Oct 15 19:02:08 1999 +0000    *** empty log message ***...and I can't think of why bounds checking a C literal was done like this.Regarding the patch, it looks good overall. My only suggestion would be to add a regression test for just below and just above overflow, at least for int2.Minor nits:- * Process {integer}.  Note this will also do the right thing with {decimal},+ * Process {*integer}.  Note this will also do the right thing with {numeric},I scratched my head for a while, thinking this was Flex syntax, until I realized my brain was supposed to do shell-globbing first, at which point I could see it was referring to multiple Flex rules. I'd try to rephrase.+T661\tNon-decimal integer literals\t\t\tYES\tSQL:202x draftIs there an ETA yet?Also, it's not this patch's job to do it, but there are at least a half dozen places that open-code turning a hex char into a number. It might be a good easy \"todo item\" to unify that.--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Mon, 14 Nov 2022 14:25:30 +0700", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 14.11.22 08:25, John Naylor wrote:\n> Regarding the patch, it looks good overall. My only suggestion would be \n> to add a regression test for just below and just above overflow, at \n> least for int2.\n\nok\n\n> Minor nits:\n> \n> - * Process {integer}.  Note this will also do the right thing with \n> {decimal},\n> + * Process {*integer}.  Note this will also do the right thing with \n> {numeric},\n> \n> I scratched my head for a while, thinking this was Flex syntax, until I \n> realized my brain was supposed to do shell-globbing first, at which \n> point I could see it was referring to multiple Flex rules. I'd try to \n> rephrase.\n\nok\n\n> +T661 Non-decimal integer literals YES SQL:202x draft\n> \n> Is there an ETA yet?\n\nMarch 2023\n\n> Also, it's not this patch's job to do it, but there are at least a half \n> dozen places that open-code turning a hex char into a number. It might \n> be a good easy \"todo item\" to unify that.\n\nright\n\n\n\n", "msg_date": "Tue, 15 Nov 2022 11:31:03 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 15.11.22 11:31, Peter Eisentraut wrote:\n> On 14.11.22 08:25, John Naylor wrote:\n>> Regarding the patch, it looks good overall. My only suggestion would \n>> be to add a regression test for just below and just above overflow, at \n>> least for int2.\n> \n> ok\n\nThis was a valuable suggestion, because this found some breakage. In \nparticular, the handling of grammar-level literals that overflow to \n\"Float\" was not correct. (The radix prefix was simply stripped and \nforgotten.) So I added a bunch more tests for this. Here is a new patch.", "msg_date": "Tue, 22 Nov 2022 14:36:45 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Tue, Nov 22, 2022 at 8:36 PM Peter Eisentraut <\npeter.eisentraut@enterprisedb.com> wrote:\n>\n> On 15.11.22 11:31, Peter Eisentraut wrote:\n> > On 14.11.22 08:25, John Naylor wrote:\n> >> Regarding the patch, it looks good overall. My only suggestion would\n> >> be to add a regression test for just below and just above overflow, at\n> >> least for int2.\n> >\n> > ok\n>\n> This was a valuable suggestion, because this found some breakage. In\n> particular, the handling of grammar-level literals that overflow to\n> \"Float\" was not correct. (The radix prefix was simply stripped and\n> forgotten.) So I added a bunch more tests for this. Here is a new patch.\n\nLooks good to me.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Tue, Nov 22, 2022 at 8:36 PM Peter Eisentraut <peter.eisentraut@enterprisedb.com> wrote:>> On 15.11.22 11:31, Peter Eisentraut wrote:> > On 14.11.22 08:25, John Naylor wrote:> >> Regarding the patch, it looks good overall. My only suggestion would> >> be to add a regression test for just below and just above overflow, at> >> least for int2.> >> > ok>> This was a valuable suggestion, because this found some breakage.  In> particular, the handling of grammar-level literals that overflow to> \"Float\" was not correct.  (The radix prefix was simply stripped and> forgotten.)  So I added a bunch more tests for this.  Here is a new patch.Looks good to me.--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Wed, 23 Nov 2022 11:35:17 +0700", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Wed, 23 Nov 2022 at 02:37, Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n> Here is a new patch.\n\nThis looks like quite an inefficient way to convert a hex string into an int64:\n\n while (*ptr && isxdigit((unsigned char) *ptr))\n {\n int8 digit = hexlookup[(unsigned char) *ptr];\n\n if (unlikely(pg_mul_s64_overflow(tmp, 16, &tmp)) ||\n unlikely(pg_sub_s64_overflow(tmp, digit, &tmp)))\n goto out_of_range;\n\n ptr++;\n }\n\nI wonder if you'd be better off with something like:\n\n while (*ptr && isxdigit((unsigned char) *ptr))\n {\n if (unlikely(tmp & UINT64CONST(0xF000000000000000)))\n goto out_of_range;\n\n tmp = (tmp << 4) | hexlookup[(unsigned char) *ptr++];\n }\n\nGoing by [1], clang will actually use multiplication by 16 to\nimplement the former. gcc is better and shifts left by 4, so likely\nwon't improve things for gcc. It seems worth doing it this way for\nanything that does not have HAVE__BUILTIN_OP_OVERFLOW anyway.\n\nDavid\n\n[1] https://godbolt.org/z/jz6Th6jnM\n\n\n", "msg_date": "Wed, 23 Nov 2022 21:54:25 +1300", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Wed, 23 Nov 2022 at 21:54, David Rowley <dgrowleyml@gmail.com> wrote:\n> I wonder if you'd be better off with something like:\n>\n> while (*ptr && isxdigit((unsigned char) *ptr))\n> {\n> if (unlikely(tmp & UINT64CONST(0xF000000000000000)))\n> goto out_of_range;\n>\n> tmp = (tmp << 4) | hexlookup[(unsigned char) *ptr++];\n> }\n\nHere's a delta diff with it changed to work that way.\n\nDavid", "msg_date": "Wed, 23 Nov 2022 21:56:15 +1300", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Wed, Nov 23, 2022 at 3:54 PM David Rowley <dgrowleyml@gmail.com> wrote:\n>\n> Going by [1], clang will actually use multiplication by 16 to\n> implement the former. gcc is better and shifts left by 4, so likely\n> won't improve things for gcc. It seems worth doing it this way for\n> anything that does not have HAVE__BUILTIN_OP_OVERFLOW anyway.\n\nFWIW, gcc 12.2 generates an imul on my system when compiling in situ. I've\nfound it useful to run godbolt locally* and load the entire PG file (nicer\nto read than plain objdump) -- compilers can make different decisions when\ngoing from isolated snippets to within full functions.\n\n* clone from https://github.com/compiler-explorer/compiler-explorer\ninstall npm 16\nrun \"make\" and when finished will show the localhost url\nadd the right flags, which in this case was\n\n-Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement\n-Werror=vla -Wendif-labels -Wmissing-format-attribute\n-Wimplicit-fallthrough=3 -Wcast-function-type -Wformat-security\n-fno-strict-aliasing -fwrapv -fexcess-precision=standard\n-Wno-format-truncation -Wno-stringop-truncation -O2\n-I/path/to/srcdir/src/include -I/path/to/builddir/src/include -D_GNU_SOURCE\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Wed, Nov 23, 2022 at 3:54 PM David Rowley <dgrowleyml@gmail.com> wrote:>> Going by [1], clang will actually use multiplication by 16 to> implement the former. gcc is better and shifts left by 4, so likely> won't improve things for gcc.  It seems worth doing it this way for> anything that does not have HAVE__BUILTIN_OP_OVERFLOW anyway.FWIW, gcc 12.2 generates an imul on my system when compiling in situ. I've found it useful to run godbolt locally* and load the entire PG file (nicer to read than plain objdump) -- compilers can make different decisions when going from isolated snippets to within full functions. * clone from https://github.com/compiler-explorer/compiler-explorerinstall npm 16run \"make\" and when finished will show the localhost urladd the right flags, which in this case was -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wimplicit-fallthrough=3 -Wcast-function-type -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -Wno-format-truncation -Wno-stringop-truncation -O2 -I/path/to/srcdir/src/include -I/path/to/builddir/src/include  -D_GNU_SOURCE--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Wed, 23 Nov 2022 16:19:27 +0700", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Tue, 22 Nov 2022 at 13:37, Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n>\n> On 15.11.22 11:31, Peter Eisentraut wrote:\n> > On 14.11.22 08:25, John Naylor wrote:\n> >> Regarding the patch, it looks good overall. My only suggestion would\n> >> be to add a regression test for just below and just above overflow, at\n> >> least for int2.\n> >\n> This was a valuable suggestion, because this found some breakage. In\n> particular, the handling of grammar-level literals that overflow to\n> \"Float\" was not correct. (The radix prefix was simply stripped and\n> forgotten.) So I added a bunch more tests for this. Here is a new patch.\n\nTaking a quick look, I noticed that there are no tests for negative\nvalues handled in the parser.\n\nGiving that a spin shows that make_const() fails to correctly identify\nthe base of negative non-decimal integers in the T_Float case, causing\nit to fall through to numeric_in() and fail:\n\nSELECT -0x80000000;\n\nERROR: invalid input syntax for type numeric: \"-0x80000000\"\n ^\nRegards,\nDean\n\n\n", "msg_date": "Wed, 23 Nov 2022 16:25:50 +0000", "msg_from": "Dean Rasheed <dean.a.rasheed@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 23.11.22 09:54, David Rowley wrote:\n> On Wed, 23 Nov 2022 at 02:37, Peter Eisentraut\n> <peter.eisentraut@enterprisedb.com> wrote:\n>> Here is a new patch.\n> \n> This looks like quite an inefficient way to convert a hex string into an int64:\n> \n> while (*ptr && isxdigit((unsigned char) *ptr))\n> {\n> int8 digit = hexlookup[(unsigned char) *ptr];\n> \n> if (unlikely(pg_mul_s64_overflow(tmp, 16, &tmp)) ||\n> unlikely(pg_sub_s64_overflow(tmp, digit, &tmp)))\n> goto out_of_range;\n> \n> ptr++;\n> }\n> \n> I wonder if you'd be better off with something like:\n> \n> while (*ptr && isxdigit((unsigned char) *ptr))\n> {\n> if (unlikely(tmp & UINT64CONST(0xF000000000000000)))\n> goto out_of_range;\n> \n> tmp = (tmp << 4) | hexlookup[(unsigned char) *ptr++];\n> }\n> \n> Going by [1], clang will actually use multiplication by 16 to\n> implement the former. gcc is better and shifts left by 4, so likely\n> won't improve things for gcc. It seems worth doing it this way for\n> anything that does not have HAVE__BUILTIN_OP_OVERFLOW anyway.\n\nMy code follows the style used for parsing the decimal integers. \nKeeping that consistent is valuable I think. I think the proposed \nchange makes the code significantly harder to understand. Also, what \nyou are suggesting here would amount to an attempt to make parsing \nhexadecimal integers even faster than parsing decimal integers. Is that \nuseful?\n\n\n", "msg_date": "Thu, 24 Nov 2022 09:35:08 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Thu, 24 Nov 2022 at 21:35, Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n> My code follows the style used for parsing the decimal integers.\n> Keeping that consistent is valuable I think. I think the proposed\n> change makes the code significantly harder to understand. Also, what\n> you are suggesting here would amount to an attempt to make parsing\n> hexadecimal integers even faster than parsing decimal integers. Is that\n> useful?\n\nIsn't it being faster one of the major use cases for this feature? I\nremember many years ago and several jobs ago when working with SQL\nServer being able to speed up importing data using hexadecimal\nDATETIMEs. I can't think why else you might want to represent a\nDATETIME as a hexstring, so I assumed this was a large part of the use\ncase for INTs in PostgreSQL. Are you telling me that better\nperformance is not something anyone will want out of this feature?\n\nDavid\n\n\n", "msg_date": "Thu, 24 Nov 2022 22:13:39 +1300", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 24.11.22 10:13, David Rowley wrote:\n> On Thu, 24 Nov 2022 at 21:35, Peter Eisentraut\n> <peter.eisentraut@enterprisedb.com> wrote:\n>> My code follows the style used for parsing the decimal integers.\n>> Keeping that consistent is valuable I think. I think the proposed\n>> change makes the code significantly harder to understand. Also, what\n>> you are suggesting here would amount to an attempt to make parsing\n>> hexadecimal integers even faster than parsing decimal integers. Is that\n>> useful?\n> \n> Isn't it being faster one of the major use cases for this feature?\n\nNever thought about it that way.\n\n> I\n> remember many years ago and several jobs ago when working with SQL\n> Server being able to speed up importing data using hexadecimal\n> DATETIMEs. I can't think why else you might want to represent a\n> DATETIME as a hexstring, so I assumed this was a large part of the use\n> case for INTs in PostgreSQL. Are you telling me that better\n> performance is not something anyone will want out of this feature?\n\nThis isn't about datetimes but about integers.\n\n\n\n", "msg_date": "Fri, 25 Nov 2022 17:13:29 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 23.11.22 17:25, Dean Rasheed wrote:\n> Taking a quick look, I noticed that there are no tests for negative\n> values handled in the parser.\n> \n> Giving that a spin shows that make_const() fails to correctly identify\n> the base of negative non-decimal integers in the T_Float case, causing\n> it to fall through to numeric_in() and fail:\n\nFixed in new patch.", "msg_date": "Mon, 28 Nov 2022 14:59:52 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Sat, 26 Nov 2022 at 05:13, Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n>\n> On 24.11.22 10:13, David Rowley wrote:\n> > I\n> > remember many years ago and several jobs ago when working with SQL\n> > Server being able to speed up importing data using hexadecimal\n> > DATETIMEs. I can't think why else you might want to represent a\n> > DATETIME as a hexstring, so I assumed this was a large part of the use\n> > case for INTs in PostgreSQL. Are you telling me that better\n> > performance is not something anyone will want out of this feature?\n>\n> This isn't about datetimes but about integers.\n\nI'm aware. My aim was to show that hex is commonly used as a more\nefficient way of getting integer numbers in and out of computers.\n\nLikely it's better for me to quantify this performance increase claim\nwith some actual performance results.\n\nHere's master (@f0cd57f85) doing copy ab2 from '/tmp/ab.csv';\n\nab2 is a table with no indexes and just 2 int columns.\n\n 16.55% postgres [.] CopyReadLine\n 7.82% postgres [.] pg_strtoint32\n 7.60% postgres [.] CopyReadAttributesText\n 7.06% postgres [.] NextCopyFrom\n 4.40% postgres [.] CopyFrom\n\nThe copy completes in 2512.5278 ms (average time over 10 runs)\n\nPatching master with your v11 patch and copying in hex numbers instead\nof decimal numbers shows:\n\n 14.39% postgres [.] CopyReadLine\n 8.60% postgres [.] pg_strtoint32\n 6.95% postgres [.] NextCopyFrom\n 6.79% postgres [.] CopyReadAttributesText\n 4.81% postgres [.] CopyFrom\n\nThis shows that we're spending proportionally less time in\nCopyReadLine() and proportionally more time in pg_strtoint32(). There\nare probably two things going on there, CopyReadLine is likely faster\ndue to having to read fewer bytes and pg_strtoint32() is likely slower\ndue to additional branching and code size.\n\nThis (copy ab2 from '/tmp/abhex.csv') saw an average time of 2720.1387\nms over 10 runs.\n\nPatching master with your v11 patch +\nmore_efficient_hex_oct_and_binary_processing.diff\n\n 15.68% postgres [.] CopyReadLine\n 7.75% postgres [.] NextCopyFrom\n 7.73% postgres [.] pg_strtoint32\n 6.25% postgres [.] CopyReadAttributesText\n 4.76% postgres [.] CopyFrom\n\nThe average time to import the hex version of the csv file comes down\nto 2385.7298 ms over 10 runs.\n\nI didn't run any tests to see how much the performance of importing\nthe decimal representation slowed down from the v11 patch. I assume\nthere will be a small performance hit due to the extra processing done\nin pg_strtoint32()\n\nDavid\n\n\n", "msg_date": "Tue, 29 Nov 2022 12:43:33 +1300", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Wed, 23 Nov 2022 at 08:56, David Rowley <dgrowleyml@gmail.com> wrote:\n>\n> On Wed, 23 Nov 2022 at 21:54, David Rowley <dgrowleyml@gmail.com> wrote:\n> > I wonder if you'd be better off with something like:\n> >\n> > while (*ptr && isxdigit((unsigned char) *ptr))\n> > {\n> > if (unlikely(tmp & UINT64CONST(0xF000000000000000)))\n> > goto out_of_range;\n> >\n> > tmp = (tmp << 4) | hexlookup[(unsigned char) *ptr++];\n> > }\n>\n> Here's a delta diff with it changed to work that way.\n>\n\nThis isn't correct, because those functions are meant to accumulate a\nnegative number in \"tmp\".\n\nThe overflow check can't just ignore the final digit either, so I'm\nnot sure how much this would end up saving once those issues are\nfixed.\n\nRegards,\nDean\n\n\n", "msg_date": "Tue, 29 Nov 2022 10:11:00 +0000", "msg_from": "Dean Rasheed <dean.a.rasheed@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Tue, 29 Nov 2022 at 23:11, Dean Rasheed <dean.a.rasheed@gmail.com> wrote:\n>\n> On Wed, 23 Nov 2022 at 08:56, David Rowley <dgrowleyml@gmail.com> wrote:\n> >\n> > On Wed, 23 Nov 2022 at 21:54, David Rowley <dgrowleyml@gmail.com> wrote:\n> > > I wonder if you'd be better off with something like:\n> > >\n> > > while (*ptr && isxdigit((unsigned char) *ptr))\n> > > {\n> > > if (unlikely(tmp & UINT64CONST(0xF000000000000000)))\n> > > goto out_of_range;\n> > >\n> > > tmp = (tmp << 4) | hexlookup[(unsigned char) *ptr++];\n> > > }\n> >\n> > Here's a delta diff with it changed to work that way.\n> >\n>\n> This isn't correct, because those functions are meant to accumulate a\n> negative number in \"tmp\".\n\nLooks like I didn't quite look at that code closely enough.\n\nTo make that work we could just form the non-decimal versions in an\nunsigned integer of the given size and then check if that's become\ngreater than -PG_INTXX_MIN after the loop. We'd then just need to\nconvert it back to its negative form.\n\ni.e:\n\nuint64 tmp2 = 0;\nptr += 2;\nwhile (*ptr && isxdigit((unsigned char) *ptr))\n{\n if (unlikely(tmp2 & UINT64CONST(0xF000000000000000)))\n goto out_of_range;\n\n tmp2 = (tmp2 << 4) | hexlookup[(unsigned char) *ptr++];\n}\n\nif (tmp2 > -PG_INT64_MIN)\n goto out_of_range;\ntmp = -((int64) tmp2);\n\nDavid\n\n\n", "msg_date": "Wed, 30 Nov 2022 09:16:55 +1300", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Tue, 29 Nov 2022 at 03:00, Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n> Fixed in new patch.\n\nThere seems to be a small bug in the pg_strtointXX functions in the\ncode that checks that there's at least 1 digit. This causes 0x to be\na valid representation of zero. That does not seem to be allowed by\nthe parser, so I think we should likely reject it in COPY too.\n\n-- Does not work.\npostgres=# select 0x + 1;\nERROR: invalid hexadecimal integer at or near \"0x\"\nLINE 1: select 0x + 1;\n\n\npostgres=# create table a (a int);\nCREATE TABLE\n\n-- probably shouldn't work\npostgres=# copy a from stdin;\nEnter data to be copied followed by a newline.\nEnd with a backslash and a period on a line by itself, or an EOF signal.\n>> 0x\n>> \\.\nCOPY 1\n\nDavid\n\n\n", "msg_date": "Wed, 30 Nov 2022 09:22:25 +1300", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Wed, 23 Nov 2022 at 22:19, John Naylor <john.naylor@enterprisedb.com> wrote:\n>\n>\n> On Wed, Nov 23, 2022 at 3:54 PM David Rowley <dgrowleyml@gmail.com> wrote:\n> >\n> > Going by [1], clang will actually use multiplication by 16 to\n> > implement the former. gcc is better and shifts left by 4, so likely\n> > won't improve things for gcc. It seems worth doing it this way for\n> > anything that does not have HAVE__BUILTIN_OP_OVERFLOW anyway.\n>\n> FWIW, gcc 12.2 generates an imul on my system when compiling in situ.\n\nI spent a bit more time trying to figure out why the compiler does\nimul instead of bit shifting and it just seems to be down to a\ncombination of signed-ness plus the overflow check. See [1]. Neither\nof the two compilers I tested could use bit shifting with a signed\ntype when overflow checking is done, which is what we're doing in the\nnew code.\n\nIn clang 15, multiplication is done in both smultiply16 and\numultiply16. These both check for overflow. The versions without the\noverflow checks both use bit shifting. With GCC, only smultiply16 does\nmultiplication. The other 3 variants all use bit shifting.\n\nDavid\n\n[1] https://godbolt.org/z/EG9jKMjq5\n\n\n", "msg_date": "Wed, 30 Nov 2022 18:50:12 +1300", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Wed, 30 Nov 2022 at 05:50, David Rowley <dgrowleyml@gmail.com> wrote:\n>\n> I spent a bit more time trying to figure out why the compiler does\n> imul instead of bit shifting and it just seems to be down to a\n> combination of signed-ness plus the overflow check. See [1]. Neither\n> of the two compilers I tested could use bit shifting with a signed\n> type when overflow checking is done, which is what we're doing in the\n> new code.\n>\n\nAh, interesting. That makes me think that it might be possible to get\nsome performance gains for all bases (including 10) by separating the\noverflow check from the multiplication, and giving the compiler the\nbest chance to decide on the optimal way to do the multiplication. For\nexample, on my Intel box, GCC prefers a pair of LEA instructions over\nan IMUL, to multiply by 10.\n\nI like your previous idea of using an unsigned integer for the\naccumulator, because then the overflow check in the loop doesn't need\nto be exact, as long as an exact check is done later. That way, there\nare fewer conditional branches in the loop, and the possibility for\nthe compiler to choose the fastest multiplication method. So something\nlike:\n\n // Accumulate positive value using unsigned int, with approximate\n // overflow check. If acc >= 1 - INT_MIN / 10, then acc * 10 is\n // sure to exceed -INT_MIN.\n unsigned int cutoff = 1 - INT_MIN / 10;\n unsigned int acc = 0;\n\n while (*ptr && isdigit((unsigned char) *ptr))\n {\n if (unlikely(acc >= cutoff))\n goto out_of_range;\n acc = acc * 10 + (*ptr - '0');\n ptr++;\n }\n\nand similar for other bases, allowing the coding for all bases to be\nkept similar.\n\nI think it's probably best to consider this as a follow-on patch\nthough. It shouldn't delay getting the main feature committed.\n\nRegards,\nDean\n\n\n", "msg_date": "Wed, 30 Nov 2022 11:34:07 +0000", "msg_from": "Dean Rasheed <dean.a.rasheed@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Thu, 1 Dec 2022 at 00:34, Dean Rasheed <dean.a.rasheed@gmail.com> wrote:\n> So something\n> like:\n>\n> // Accumulate positive value using unsigned int, with approximate\n> // overflow check. If acc >= 1 - INT_MIN / 10, then acc * 10 is\n> // sure to exceed -INT_MIN.\n> unsigned int cutoff = 1 - INT_MIN / 10;\n> unsigned int acc = 0;\n>\n> while (*ptr && isdigit((unsigned char) *ptr))\n> {\n> if (unlikely(acc >= cutoff))\n> goto out_of_range;\n> acc = acc * 10 + (*ptr - '0');\n> ptr++;\n> }\n>\n> and similar for other bases, allowing the coding for all bases to be\n> kept similar.\n\nSeems like a good idea to me. Couldn't the cutoff check just be \"acc >\nINT_MAX / 10\"?\n\n> I think it's probably best to consider this as a follow-on patch\n> though. It shouldn't delay getting the main feature committed.\n\nI agree that it should be a separate patch. But thinking about what\nTom mentioned in [1], I had in mind this patch would need to wait\nuntil the new standard is out so that we have a more genuine reason\nfor breaking existing queries.\n\nI've drafted up a full patch for improving the current base-10 code,\nso I'll go post that on another thread.\n\nDavid\n\n[1] https://postgr.es/m/3260805.1631106874@sss.pgh.pa.us\n\n\n", "msg_date": "Thu, 1 Dec 2022 12:11:56 +1300", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "David Rowley <dgrowleyml@gmail.com> writes:\n> I agree that it should be a separate patch. But thinking about what\n> Tom mentioned in [1], I had in mind this patch would need to wait\n> until the new standard is out so that we have a more genuine reason\n> for breaking existing queries.\n\nWell, we already broke them in v15: that example now gives\n\nregression=# select 0x42e;\nERROR: trailing junk after numeric literal at or near \"0x\"\nLINE 1: select 0x42e;\n ^\n\nSo there's probably no compatibility reason not to drop the\nother shoe.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 30 Nov 2022 18:36:47 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 29.11.22 21:22, David Rowley wrote:\n> There seems to be a small bug in the pg_strtointXX functions in the\n> code that checks that there's at least 1 digit. This causes 0x to be\n> a valid representation of zero. That does not seem to be allowed by\n> the parser, so I think we should likely reject it in COPY too.\n> -- probably shouldn't work\n> postgres=# copy a from stdin;\n> Enter data to be copied followed by a newline.\n> End with a backslash and a period on a line by itself, or an EOF signal.\n>>> 0x\n>>> \\.\n> COPY 1\n\nFixed in new patch. I moved the \"require at least one digit\" checks \nafter the loops over the digits, to make it easier to write one check \nfor all bases.\n\nThis patch is also incorporates your changes to the digit analysis \nalgorithm. I didn't check it carefully, but all the tests still pass. ;-)", "msg_date": "Thu, 8 Dec 2022 12:16:29 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 08.12.22 12:16, Peter Eisentraut wrote:\n> On 29.11.22 21:22, David Rowley wrote:\n>> There seems to be a small bug in the pg_strtointXX functions in the\n>> code that checks that there's at least 1 digit.  This causes 0x to be\n>> a valid representation of zero.  That does not seem to be allowed by\n>> the parser, so I think we should likely reject it in COPY too.\n>> -- probably shouldn't work\n>> postgres=# copy a from stdin;\n>> Enter data to be copied followed by a newline.\n>> End with a backslash and a period on a line by itself, or an EOF signal.\n>>>> 0x\n>>>> \\.\n>> COPY 1\n> \n> Fixed in new patch.  I moved the \"require at least one digit\" checks \n> after the loops over the digits, to make it easier to write one check \n> for all bases.\n> \n> This patch is also incorporates your changes to the digit analysis \n> algorithm.  I didn't check it carefully, but all the tests still pass. ;-)\n\ncommitted\n\n\n", "msg_date": "Wed, 14 Dec 2022 06:47:28 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Wed, 14 Dec 2022 at 05:47, Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n>\n> committed\n\nNow that we have this for integer types, I think it's worth doing for\nnumeric as well, since the parser will now pass such things through to\nnumeric_in() when they don't fit in an int64, and it seems plausible\nthat at least some people might use non-decimal integers beyond\nINT64MIN/MAX. Also, without such support in numeric_in(), the feature\nlooks a little incomplete:\n\nSELECT -0x8000000000000000;\n ?column?\n----------------------\n -9223372036854775808\n(1 row)\n\nSELECT 0x8000000000000000;\nERROR: invalid input syntax for type numeric: \"0x8000000000000000\"\nLINE 1: select 0x8000000000000000;\n ^\n\nOne concern I had was what the performance would be like. I don't\nreally expect people to pass in the kinds of truly huge values that\nnumeric supports, but it can't be ruled out. So I gave it a go, to see\nhow hard it would be, and what the worst-case performance looks like.\n(I included underscore-handling too, so that I could measure that at\nthe same time.)\n\nThe base-conversion algorithm is O(N^2), and the worst case before\noverflow is with hex strings with around 108,000 digits, oct strings\nwith around 145,000 digits, or binary strings with around 435,000\ndigits. Each of those takes around 400ms to parse on my machine.\nThat's around the level at which I might consider adding\nCHECK_FOR_INTERRUPTS()'s, but I think that it's probably not worth it,\ngiven how unrealistic such huge inputs are in practice.\n\nThe other important thing is that this shouldn't impact the\nperformance when parsing regular decimal inputs. The bulk of the\nnon-decimal integer parsing is handled by a separate function, which\nis called directly from numeric_in(), since non-decimal handling isn't\nrequired at the set_var_from_str() level (used by the float4/8 ->\nnumeric conversion functions). I also re-arranged the numeric_in()\ncode somewhat, and was able to make substantial savings by reducing\nthe number of pg_strncasecmp() calls, and avoiding those calls\nentirely for regular numbers that aren't NaN or Inf. Testing that with\nCOPY with a few million numbers of different sizes, I observed a\n10-15% performance increase.\n\nSo I'm feeling quite good about the end result -- I set out hoping not\nto make performance noticeably worse, but ended up making it\nsignificantly better.\n\nRegards,\nDean", "msg_date": "Fri, 13 Jan 2023 10:01:15 +0000", "msg_from": "Dean Rasheed <dean.a.rasheed@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On 13.01.23 11:01, Dean Rasheed wrote:\n> So I'm feeling quite good about the end result -- I set out hoping not\n> to make performance noticeably worse, but ended up making it\n> significantly better.\n\nThis is great! How do you want to proceed? You also posted an updated \npatch in the \"underscores\" thread and suggested some additional work \nthere. In which order should these be addressed, in your opinion?\n\n\n\n", "msg_date": "Mon, 23 Jan 2023 16:55:17 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Mon, 23 Jan 2023 at 15:55, Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n>\n> On 13.01.23 11:01, Dean Rasheed wrote:\n> > So I'm feeling quite good about the end result -- I set out hoping not\n> > to make performance noticeably worse, but ended up making it\n> > significantly better.\n>\n> This is great! How do you want to proceed? You also posted an updated\n> patch in the \"underscores\" thread and suggested some additional work\n> there. In which order should these be addressed, in your opinion?\n>\n\nI think it makes most sense if I push 0001 now, and then merge 0002\ninto the underscores patch. I think at least one of the suggested\nchanges to the underscores patch required 0002 to work.\n\nRegards,\nDean\n\n\n", "msg_date": "Mon, 23 Jan 2023 16:22:35 +0000", "msg_from": "Dean Rasheed <dean.a.rasheed@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Fri, Jan 13, 2023, at 07:01, Dean Rasheed wrote:\n> Attachments:\n> * 0001-Add-non-decimal-integer-support-to-type-numeric.patch\n\nNice! This also simplifies when dealing with non-negative integers represented as byte arrays,\ncommon in e.g. cryptography code.\n\nBefore, one had to implement numeric_from_bytes(bytea) in plpgsql [1],\nwhich can now be greatly simplified:\n\ncreate function numeric_from_bytes(bytea) returns numeric language sql as $$\nselect ('0'||right($1::text,-1))::numeric\n$$;\n\n\\timing\nselect numeric_from_bytes(('\\x'||repeat('0123456789abcdef',1000))::bytea);\nTime: 484.223 ms -- HEAD + plpgsql numeric_from_bytes()\nTime: 19.790 ms -- 0001 + simplified numeric_from_bytes()\n\nAbout 25x faster!\n\nWould we want a built-in function for this?\nTo avoid the text casts, but also to improve user-friendliness,\nsince the improved solution is still a hack a user needing it has to someone come up with or find.\nThe topic \"Convert hex in text representation to decimal number\" is an old one on Stackoverflow [2],\nposted 11 years ago, with a myriad of various hackis solutions, out of which one had a bug that I reported.\nMany other modern languages seems to have this as a built-in or in stdlibs:\nPython3:\nclassmethod int.from_bytes(bytes, byteorder='big', *, signed=False)\nRust:\npub const fn from_be_bytes(bytes: [u8; 8]) -> u64\n\n/Joel\n\n[1] https://gist.github.com/joelonsql/f54552db1f0fd6d9b3397d255e51f58a\n[2] https://stackoverflow.com/questions/8316164/convert-hex-in-text-representation-to-decimal-number\n\n\n", "msg_date": "Mon, 23 Jan 2023 17:00:14 -0300", "msg_from": "\"Joel Jacobson\" <joel@compiler.org>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" }, { "msg_contents": "On Mon, 23 Jan 2023 at 20:00, Joel Jacobson <joel@compiler.org> wrote:\n>\n> Nice! This also simplifies when dealing with non-negative integers represented as byte arrays,\n> common in e.g. cryptography code.\n>\n\nAh, interesting. I hadn't thought of that use-case.\n\n> create function numeric_from_bytes(bytea) returns numeric language sql as $$\n> select ('0'||right($1::text,-1))::numeric\n> $$;\n>\n> Would we want a built-in function for this?\n\nNot sure. It does feel a bit niche. It's quite common in other\nprogramming languages, but that doesn't mean that a lot of Postgres\nusers need it. Perhaps start a new thread to gauge people's interest?\n\nRegards,\nDean\n\n\n", "msg_date": "Mon, 23 Jan 2023 21:20:45 +0000", "msg_from": "Dean Rasheed <dean.a.rasheed@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Non-decimal integer literals" } ]
[ { "msg_contents": "Hi.\n\nI'm currently looking on pushing down SQLValue expressions to foreign \nservers and was surprised that two timestamptz-related functions are not \nimmutable.\nI see that this was changed in commit\n\ncommit 1ab415596d1de61561d0de8fe9da4aea207adca4\nAuthor: Tom Lane <tgl@sss.pgh.pa.us>\nDate: Mon Oct 4 22:13:14 2004 +0000\n\n Correct the volatility labeling of ten timestamp-related functions,\n per discussion from Friday. initdb not forced in this commit but I \nintend\n to do that later.\n\nI'm not sure, why timestamptz_pl_interval and timestamptz_mi_interval \nare not immutable. Even if we change timezone during transaction, \naddition of the same interval to the same timestamps with time zone \ngives the same result.\n\npostgres=# begin ;\nBEGIN\npostgres=*# select current_timestamp;\n current_timestamp\n-------------------------------\n 2021-08-16 13:26:59.366452+03\n(1 row)\n\npostgres=*# select timestamptz '2021-08-16 13:26:59.366452+03';\n timestamptz\n-------------------------------\n 2021-08-16 13:26:59.366452+03\n(1 row)\n\npostgres=*# select timestamptz '2021-08-16 13:26:59.366452+03' + '2 \ndays'::interval;\n ?column?\n-------------------------------\n 2021-08-18 13:26:59.366452+03\n(1 row)\n\npostgres=*# set timezone to UTC;\nSET\npostgres=*# select timestamptz '2021-08-16 13:26:59.366452+03' + '2 \ndays'::interval;\n ?column?\n-------------------------------\n 2021-08-18 10:26:59.366452+00\n(1 row)\n\npostgres=*# select timestamptz '2021-08-18 13:26:59.366452+03' = \ntimestamptz '2021-08-18 10:26:59.366452+00';\n ?column?\n----------\n t\n(1 row)\n\nWhat do I miss?\n\n-- \nBest regards,\nAlexander Pyhalov,\nPostgres Professional\n\n\n", "msg_date": "Mon, 16 Aug 2021 13:29:45 +0300", "msg_from": "Alexander Pyhalov <a.pyhalov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Why timestamptz_pl_interval and timestamptz_mi_interval are not\n immutable?" }, { "msg_contents": "> \n> What do I miss?\n> \n> --\n> Best regards,\n> Alexander Pyhalov,\n> Postgres Professional\n> \n\nSee for example around DST changes\n\npostgres=# begin;\nBEGIN\npostgres =# show timezone;\n TimeZone \n------------------\n Europe/Amsterdam\n(1 row)\n\npostgres=# select '2021-03-27 15:00 +0100'::timestamptz + interval '1d';\n ?column? \n------------------------\n 2021-03-28 15:00:00+02\n(1 row)\n\npostgres =# set timezone to UTC;\nSET\npostgres =# select '2021-03-27 15:00 +0100'::timestamptz + interval '1d';\n ?column? \n------------------------\n 2021-03-28 14:00:00+00\n(1 row)\n\npostgres =# select '2021-03-28 15:00:00+02' = '2021-03-28 14:00:00+00';\n ?column? \n----------\n f\n(1 row)\n\n\n\n", "msg_date": "Mon, 16 Aug 2021 11:25:49 +0000", "msg_from": "Floris Van Nee <florisvannee@Optiver.com>", "msg_from_op": false, "msg_subject": "RE: Why timestamptz_pl_interval and timestamptz_mi_interval are not\n immutable?" } ]
[ { "msg_contents": "Attached patches introduce more macros to group some RELKIND_* macros:\n\n- RELKIND_HAS_PARTITIONS()\n- RELKIND_HAS_TABLESPACE()\n- RELKIND_HAS_TABLE_AM()\n- RELKIND_HAS_INDEX_AM()\n\nI collected those mainly while working on the relkind error messages \npatch [0]. I think they improve the self-documentation of the code in \nmany places that are currently just random collections or endless \nstreams of RELKIND macros.\n\nSome may recall the previous thread [1] that made a similar proposal. \nThe result here was that those macros were too thinly sliced and not \ngenerally useful enough. My proposal is completely separate from that.\n\n\n[0]: \nhttps://www.postgresql.org/message-id/flat/dc35a398-37d0-75ce-07ea-1dd71d98f8ec@2ndquadrant.com\n[1]: \nhttps://www.postgresql.org/message-id/flat/CAFjFpRcfzs%2Byst6YBCseD_orEcDNuAr9GUTraZ5GC%3DAvCYh55Q%40mail.gmail.com", "msg_date": "Mon, 16 Aug 2021 15:20:07 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Some RELKIND macro refactoring" }, { "msg_contents": "On 2021-Aug-16, Peter Eisentraut wrote:\n\n> +\t\tif (rel->rd_rel->relkind == RELKIND_INDEX ||\n> +\t\t\trel->rd_rel->relkind == RELKIND_SEQUENCE)\n> +\t\t\tRelationCreateStorage(rel->rd_node, relpersistence);\n> +\t\telse if (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))\n> +\t\t\ttable_relation_set_new_filenode(rel, &rel->rd_node,\n> +\t\t\t\t\t\t\t\t\t\t\trelpersistence,\n> +\t\t\t\t\t\t\t\t\t\t\trelfrozenxid, relminmxid);\n> +\t\telse\n> +\t\t\tAssert(false);\n\nI think you could turn this one (and the one in RelationSetNewRelfilenode) around:\n\n\tif (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))\n\t\ttable_relation_set_new_filenode(...);\n\telse if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind))\n\t\tRelationCreateStorage(...);\n\n> +/*\n> + * Relation kinds with a table access method (rd_tableam). Although sequences\n> + * use the heap table AM, they are enough of a special case in most uses that\n> + * they are not included here.\n> + */\n> +#define RELKIND_HAS_TABLE_AM(relkind) \\\n> +\t((relkind) == RELKIND_RELATION || \\\n> +\t (relkind) == RELKIND_TOASTVALUE || \\\n> +\t (relkind) == RELKIND_MATVIEW)\n\nPartitioned tables are not listed here, but IIRC there's a patch to let\npartitioned tables have a table AM so that their partitions inherit it.\nI'm wondering if that patch is going to have to change this spot; and if\nit does, how will that affect the callers of this macro that this patch\ncreates. I think a few places assume that HAS_TABLE_AM means that the\ntable has storage, but perhaps it would be better to spell that out\nexplicitly:\n\n@@ -303,9 +303,7 @@ verify_heapam(PG_FUNCTION_ARGS)\n \t/*\n \t * Check that a relation's relkind and access method are both supported.\n \t */\n-\tif (ctx.rel->rd_rel->relkind != RELKIND_RELATION &&\n-\t\tctx.rel->rd_rel->relkind != RELKIND_MATVIEW &&\n-\t\tctx.rel->rd_rel->relkind != RELKIND_TOASTVALUE)\n+\tif (!(RELKIND_HAS_TABLE_AM(ctx.rel->rd_rel->relkind) && RELKIND_HAS_STOAGE(ctx.rel->rd_rel->relkind)))\n \t\tereport(ERROR,\n \t\t\t\t(errcode(ERRCODE_WRONG_OBJECT_TYPE),\n \t\t\t\t errmsg(\"cannot check relation \\\"%s\\\"\",\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\n\n", "msg_date": "Mon, 16 Aug 2021 10:22:50 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Some RELKIND macro refactoring" }, { "msg_contents": "On Mon, Aug 16, 2021 at 10:22:50AM -0400, Alvaro Herrera wrote:\n> Partitioned tables are not listed here, but IIRC there's a patch to let\n> partitioned tables have a table AM so that their partitions inherit it.\n\nThis was raised in the thread for ALTER TABLE SET ACCESS METHOD (see\npatch 0002):\nhttps://www.postgresql.org/message-id/20210308010707.GA29832@telsasoft.com\n\nI am not sure whether we'd want to do that for table AMs as\nproperty inheritance combined with partitioned tables has always been\na sensitive topic for any properties, but if we discuss this it should\nbe on a new thread.\n--\nMichael", "msg_date": "Tue, 17 Aug 2021 11:59:53 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Some RELKIND macro refactoring" }, { "msg_contents": "While analyzing this again, I think I found an existing mistake. The \nhandling of RELKIND_PARTITIONED_INDEX in \nRelationGetNumberOfBlocksInFork() seems to be misplaced. See attached \npatch.", "msg_date": "Tue, 24 Aug 2021 12:01:33 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Some RELKIND macro refactoring" }, { "msg_contents": "On Tue, Aug 24, 2021 at 12:01:33PM +0200, Peter Eisentraut wrote:\n> While analyzing this again, I think I found an existing mistake. The\n> handling of RELKIND_PARTITIONED_INDEX in RelationGetNumberOfBlocksInFork()\n> seems to be misplaced. See attached patch.\n\nRight. This maps with RELKIND_HAS_STORAGE(). Makes me wonder whether\nis would be better to add a check on RELKIND_HAS_STORAGE() in this\narea, even if that's basically the same as the Assert() already used\nin this code path.\n--\nMichael", "msg_date": "Wed, 25 Aug 2021 14:44:27 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Some RELKIND macro refactoring" }, { "msg_contents": "On 2021-Aug-25, Michael Paquier wrote:\n\n> On Tue, Aug 24, 2021 at 12:01:33PM +0200, Peter Eisentraut wrote:\n> > While analyzing this again, I think I found an existing mistake. The\n> > handling of RELKIND_PARTITIONED_INDEX in RelationGetNumberOfBlocksInFork()\n> > seems to be misplaced. See attached patch.\n\nAgreed, that's a mistake.\n\n> Right. This maps with RELKIND_HAS_STORAGE(). Makes me wonder whether\n> is would be better to add a check on RELKIND_HAS_STORAGE() in this\n> area, even if that's basically the same as the Assert() already used\n> in this code path.\n\nWell, the patch replaces the switch on individual relkind values with if\ntests on RELKIND_HAS_FOO macros. I suppose we'd have\n\nAssert(RELKIND_HAS_STORAGE(relkind));\n\nso the function would not even be called for partitioned indexes. (In a\nquick scan of 'git grep RelationGetNumberOfBlocks' I see nothing that\nwould obviously call this function on a partitioned index.)\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/\n\n\n", "msg_date": "Wed, 25 Aug 2021 09:31:46 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Some RELKIND macro refactoring" }, { "msg_contents": "On 16.08.21 16:22, Alvaro Herrera wrote:\n> On 2021-Aug-16, Peter Eisentraut wrote:\n> \n>> +\t\tif (rel->rd_rel->relkind == RELKIND_INDEX ||\n>> +\t\t\trel->rd_rel->relkind == RELKIND_SEQUENCE)\n>> +\t\t\tRelationCreateStorage(rel->rd_node, relpersistence);\n>> +\t\telse if (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))\n>> +\t\t\ttable_relation_set_new_filenode(rel, &rel->rd_node,\n>> +\t\t\t\t\t\t\t\t\t\t\trelpersistence,\n>> +\t\t\t\t\t\t\t\t\t\t\trelfrozenxid, relminmxid);\n>> +\t\telse\n>> +\t\t\tAssert(false);\n> \n> I think you could turn this one (and the one in RelationSetNewRelfilenode) around:\n> \n> \tif (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))\n> \t\ttable_relation_set_new_filenode(...);\n> \telse if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind))\n> \t\tRelationCreateStorage(...);\n\ndone\n\n>> +/*\n>> + * Relation kinds with a table access method (rd_tableam). Although sequences\n>> + * use the heap table AM, they are enough of a special case in most uses that\n>> + * they are not included here.\n>> + */\n>> +#define RELKIND_HAS_TABLE_AM(relkind) \\\n>> +\t((relkind) == RELKIND_RELATION || \\\n>> +\t (relkind) == RELKIND_TOASTVALUE || \\\n>> +\t (relkind) == RELKIND_MATVIEW)\n> \n> Partitioned tables are not listed here, but IIRC there's a patch to let\n> partitioned tables have a table AM so that their partitions inherit it.\n> I'm wondering if that patch is going to have to change this spot; and if\n> it does, how will that affect the callers of this macro that this patch\n> creates.\n\nInteresting. It would be useful to consider both patches together then, \nso that conceptual clarity is achieved. I will take a look.\n\nAfter some consideration, I have removed RELKIND_HAS_INDEX_AM(), since \nthe way I had it and also considering that other patch effort, it didn't \nmake much sense.\n\n> I think a few places assume that HAS_TABLE_AM means that the\n> table has storage, but perhaps it would be better to spell that out\n> explicitly:\n> \n> @@ -303,9 +303,7 @@ verify_heapam(PG_FUNCTION_ARGS)\n> \t/*\n> \t * Check that a relation's relkind and access method are both supported.\n> \t */\n> -\tif (ctx.rel->rd_rel->relkind != RELKIND_RELATION &&\n> -\t\tctx.rel->rd_rel->relkind != RELKIND_MATVIEW &&\n> -\t\tctx.rel->rd_rel->relkind != RELKIND_TOASTVALUE)\n> +\tif (!(RELKIND_HAS_TABLE_AM(ctx.rel->rd_rel->relkind) && RELKIND_HAS_STOAGE(ctx.rel->rd_rel->relkind)))\n> \t\tereport(ERROR,\n> \t\t\t\t(errcode(ERRCODE_WRONG_OBJECT_TYPE),\n> \t\t\t\t errmsg(\"cannot check relation \\\"%s\\\"\",\n> \n\nI think, if something has a table AM, it implies that it has storage.\n\nIn the contrib modules, the right way to phrase the check is sometimes \nnot entirely clear, since part of the job of these modules is sometimes \nto bypass the normal APIs and do extra checks etc.", "msg_date": "Mon, 30 Aug 2021 10:17:30 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Some RELKIND macro refactoring" }, { "msg_contents": "Small rebase of this patch set.", "msg_date": "Mon, 1 Nov 2021 07:28:16 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Some RELKIND macro refactoring" }, { "msg_contents": "On Mon, Nov 01, 2021 at 07:28:16AM +0100, Peter Eisentraut wrote:\n> \n> Small rebase of this patch set.\n\nRegarding 0001, I find the existing code a bit more self-documenting\nif we keep those checks flagInhAttrs() and guessConstraintInheritance().\nSo I would rather leave these.\n\nI like 0002, which makes things a bit easier to go through across\nvarious places where relkind-only checks are replaced by those new\nmacros. There is one thing I bumped into, though..\n\n> if (create_storage)\n> {\n> - switch (rel->rd_rel->relkind)\n> - {\n> - case RELKIND_VIEW:\n> - case RELKIND_COMPOSITE_TYPE:\n> - case RELKIND_FOREIGN_TABLE:\n> - case RELKIND_PARTITIONED_TABLE:\n> - case RELKIND_PARTITIONED_INDEX:\n> - Assert(false);\n> - break;\n> - [ .. deletions .. ]\n> - }\n> + if (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))\n> + table_relation_set_new_filenode(rel, &rel->rd_node,\n> + relpersistence,\n> + relfrozenxid, relminmxid);\n> + else\n> + RelationCreateStorage(rel->rd_node, relpersistence);\n> }\n\nI think that you should keep this block as it is now. The part where\na relkind does not support table AMs and does not require storage\nwould get uncovered, and this new code would just attempt to create\nstorage, so it seems to me that the existing code is better when it\ncomes to prevent mistakes from developers? You could as well use an\nelse if (RELKIND_INDEX || RELKIND_SEQUENCE) for\nRelationCreateStorage(), and fall back to Assert(false) in the else\nbranch, to get the same result as the original without impacting the\nlevel of safety of the original code.\n--\nMichael", "msg_date": "Fri, 19 Nov 2021 16:31:41 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Some RELKIND macro refactoring" }, { "msg_contents": "On 19.11.21 08:31, Michael Paquier wrote:\n> On Mon, Nov 01, 2021 at 07:28:16AM +0100, Peter Eisentraut wrote:\n>>\n>> Small rebase of this patch set.\n> \n> Regarding 0001, I find the existing code a bit more self-documenting\n> if we keep those checks flagInhAttrs() and guessConstraintInheritance().\n> So I would rather leave these.\n\nIn that case, the existing check in guessConstraintInheritance() seems \nwrong, because it doesn't check for RELKIND_MATVIEW. Should we fix \nthat? It's dead code either way, but if the code isn't exercises, then \nthese kinds of inconsistency come about.\n\n> I like 0002, which makes things a bit easier to go through across\n> various places where relkind-only checks are replaced by those new\n> macros. There is one thing I bumped into, though..\n> \n>> if (create_storage)\n>> {\n>> - switch (rel->rd_rel->relkind)\n>> - {\n>> - case RELKIND_VIEW:\n>> - case RELKIND_COMPOSITE_TYPE:\n>> - case RELKIND_FOREIGN_TABLE:\n>> - case RELKIND_PARTITIONED_TABLE:\n>> - case RELKIND_PARTITIONED_INDEX:\n>> - Assert(false);\n>> - break;\n>> - [ .. deletions .. ]\n>> - }\n>> + if (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))\n>> + table_relation_set_new_filenode(rel, &rel->rd_node,\n>> + relpersistence,\n>> + relfrozenxid, relminmxid);\n>> + else\n>> + RelationCreateStorage(rel->rd_node, relpersistence);\n>> }\n> \n> I think that you should keep this block as it is now. The part where\n> a relkind does not support table AMs and does not require storage\n> would get uncovered, and this new code would just attempt to create\n> storage, so it seems to me that the existing code is better when it\n> comes to prevent mistakes from developers? You could as well use an\n> else if (RELKIND_INDEX || RELKIND_SEQUENCE) for\n> RelationCreateStorage(), and fall back to Assert(false) in the else\n> branch, to get the same result as the original without impacting the\n> level of safety of the original code.\n\nMaybe\n\n else\n {\n Assert(RELKIND_HAS_STORAGE(rel->rd_rel->relkind);\n RelationCreateStorage(rel->rd_node, relpersistence);\n }\n\ncreate_storage is set earlier based on RELKIND_HAS_STORAGE(), so this \nwould be consistent.\n\n\n", "msg_date": "Mon, 22 Nov 2021 11:21:52 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Some RELKIND macro refactoring" }, { "msg_contents": "On 2021-Nov-19, Michael Paquier wrote:\n\n> I think that you should keep this block as it is now. The part where\n> a relkind does not support table AMs and does not require storage\n> would get uncovered, and this new code would just attempt to create\n> storage, so it seems to me that the existing code is better when it\n> comes to prevent mistakes from developers? You could as well use an\n> else if (RELKIND_INDEX || RELKIND_SEQUENCE) for\n> RelationCreateStorage(), and fall back to Assert(false) in the else\n> branch, to get the same result as the original without impacting the\n> level of safety of the original code.\n\nHmm, I think the added condition and else would make it safe and clear:\n\n+ if (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))\n+ table_relation_set_new_filenode(rel, &rel->rd_node,\n+ relpersistence,\n+ relfrozenxid, relminmxid);\n+ else if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind))\n+ RelationCreateStorage(rel->rd_node, relpersistence);\n+ else\n+ Assert(false);\n\nThis is the same coding the patch proposed to put in\nRelationSetNewRelfilenode, which IMO validates the idea.\n\n\nIn init_fork(), there's a typo:\n\n+ * For tables, the AM callback creates both the main and the init fork.\nshould read:\n+ * For tables, the AM callback creates both the main and the init forks.\n\n\nIn heap_create_with_catalog, you have\n\n+ if (!relid)\nshould be\n+ if (!OidIsValid(relid))\n\n\nOverall, LGTM.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\n\n", "msg_date": "Tue, 23 Nov 2021 12:09:00 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Some RELKIND macro refactoring" }, { "msg_contents": "On 2021-Nov-22, Peter Eisentraut wrote:\n\n> Maybe\n> \n> else\n> {\n> Assert(RELKIND_HAS_STORAGE(rel->rd_rel->relkind);\n> RelationCreateStorage(rel->rd_node, relpersistence);\n> }\n> \n> create_storage is set earlier based on RELKIND_HAS_STORAGE(), so this would\n> be consistent.\n\nHmm, right ... but I think we can make this a little simpler. How about\nthe attached?\n\n-- \nÁlvaro Herrera Valdivia, Chile — https://www.EnterpriseDB.com/", "msg_date": "Tue, 23 Nov 2021 12:19:13 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Some RELKIND macro refactoring" }, { "msg_contents": "On 2021-Nov-23, Alvaro Herrera wrote:\n\n> On 2021-Nov-22, Peter Eisentraut wrote:\n> \n> > Maybe\n> > \n> > else\n> > {\n> > Assert(RELKIND_HAS_STORAGE(rel->rd_rel->relkind);\n> > RelationCreateStorage(rel->rd_node, relpersistence);\n> > }\n> > \n> > create_storage is set earlier based on RELKIND_HAS_STORAGE(), so this would\n> > be consistent.\n> \n> Hmm, right ... but I think we can make this a little simpler. How about\n> the attached?\n\nThis doesn't actually work, so nevermind that.\n\n-- \nÁlvaro Herrera 39°49'30\"S 73°17'W — https://www.EnterpriseDB.com/\nEssentially, you're proposing Kevlar shoes as a solution for the problem\nthat you want to walk around carrying a loaded gun aimed at your foot.\n(Tom Lane)\n\n\n", "msg_date": "Tue, 23 Nov 2021 12:36:15 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Some RELKIND macro refactoring" }, { "msg_contents": "On Mon, Nov 22, 2021 at 11:21:52AM +0100, Peter Eisentraut wrote:\n> On 19.11.21 08:31, Michael Paquier wrote:\n>> Regarding 0001, I find the existing code a bit more self-documenting\n>> if we keep those checks flagInhAttrs() and guessConstraintInheritance().\n>> So I would rather leave these.\n> \n> In that case, the existing check in guessConstraintInheritance() seems\n> wrong, because it doesn't check for RELKIND_MATVIEW. Should we fix that?\n> It's dead code either way, but if the code isn't exercises, then these kinds\n> of inconsistency come about.\n\nYeah, this one could be added. Perhaps that comes down to one's taste\nat the end, but I would add it.\n\n> Maybe\n> \n> else\n> {\n> Assert(RELKIND_HAS_STORAGE(rel->rd_rel->relkind);\n> RelationCreateStorage(rel->rd_node, relpersistence);\n> }\n> \n> create_storage is set earlier based on RELKIND_HAS_STORAGE(), so this would\n> be consistent.\n\nSounds fine by me. Perhaps you should apply the same style in\nRelationGetNumberOfBlocksInFork(), then?\n--\nMichael", "msg_date": "Wed, 24 Nov 2021 13:20:29 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Some RELKIND macro refactoring" }, { "msg_contents": "On 24.11.21 05:20, Michael Paquier wrote:\n> On Mon, Nov 22, 2021 at 11:21:52AM +0100, Peter Eisentraut wrote:\n>> On 19.11.21 08:31, Michael Paquier wrote:\n>>> Regarding 0001, I find the existing code a bit more self-documenting\n>>> if we keep those checks flagInhAttrs() and guessConstraintInheritance().\n>>> So I would rather leave these.\n>> In that case, the existing check in guessConstraintInheritance() seems\n>> wrong, because it doesn't check for RELKIND_MATVIEW. Should we fix that?\n>> It's dead code either way, but if the code isn't exercises, then these kinds\n>> of inconsistency come about.\n> Yeah, this one could be added. Perhaps that comes down to one's taste\n> at the end, but I would add it.\n\nOk, I have committed adding the missing relkind, as you suggest. Patch \nv3-0001 is therefore obsolete.\n\n\n\n", "msg_date": "Thu, 2 Dec 2021 16:56:02 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Some RELKIND macro refactoring" }, { "msg_contents": "On 23.11.21 16:09, Alvaro Herrera wrote:\n> In init_fork(), there's a typo:\n> \n> + * For tables, the AM callback creates both the main and the init fork.\n> should read:\n> + * For tables, the AM callback creates both the main and the init forks.\n\nI believe the original wording is correct.\n\n> Overall, LGTM.\n\nCommitted with the (other) suggested adjustments.\n\n\n\n", "msg_date": "Fri, 3 Dec 2021 14:12:35 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Some RELKIND macro refactoring" } ]
[ { "msg_contents": "I have suspected that there are serious design issues with the FSM\n(and related heapam code like hio.c) for several years now [1]. This\nhas a lot to do with the experience of using Jan Wieck's BenchmarkSQL\nimplementation of TPC-C [2][3][4]. It clearly makes Postgres exhibit\npathological performance issues, especially heap fragmentation.\n\nThere is a clear way in which free space in the two largest tables\n(orders and order lines) ought to be managed, given the fixed pattern\nof the workload, but that isn't what we see. I had the opportunity to\nwork with Jan Wieck and Greg Smith directly on this, shortly before I\nleft Crunchy Data several weeks ago. Jan was able to fix some issues\non the BenchmarkSQL side, which helped a lot. But the real problems\nremain. It is generally understood that the FSM leads to Postgres\ndoing badly with TPC-C. I personally believe that this is\nrepresentative of real practical problems, and not just a problem with\nthis one benchmark.\n\nThis email is an attempt to impose some order on a disorderly problem\nspace. I'd like to compare notes with other people that are interested\nin the problem. I suspect that some experienced hackers have yet to be\nconvinced of the importance of the FSM when it comes to bloat.\nHopefully I'll manage to make that case convincingly on this thread.\n\nIf any of my more concrete claims about problems in the FSM seem like\nthey need to be justified, please let me know. I am omitting details\nin this initial overview email for the sake of brevity. It's already\ntoo long.\n\nProblems\n--------\n\nThe FSM gives out space without considering the passage of time, or\nthe likelihood that a particular transaction or client will consume\nits requested free space in a more or less predictable and steady way\nover time. It has no memory. The FSM therefore fails to capture\nnaturally occurring locality, or at least doesn't specifically care\nabout it. This is the central problem, that all other problems with\nthe FSM seem to stem from in one way or another.\n\nThe FSM should group related rows (e.g. rows from the same transaction\nor backend) together, so that they reliably go on the same heap page\n-- careless mixing of unrelated rows should be avoided. When I say\n\"related\", I mean related in whatever sense the application or end\nuser thinks of them as related. As a general rule we should expect\ngroups of rows that were inserted by the same transaction to also be\nread, updated, deleted, or removed by VACUUM together, as a group.\nWhile this isn't guaranteed, it's a good working assumption for the\nFSM. It avoids unnecessary fragmentation. The current FSM design\ncauses significant fragmentation with workloads where users *expect*\nno fragmentation at all. I see this with TPC-C. The way that the FSM\n*ought* to behave for the workload in question is intuitively obvious,\nonce you lay it all out. But that's not what we see in practice -- far\nfrom it. (Happy to go into more detail on this.)\n\nYou don't even need temporal locality to see problems. Even random\ninserts show up certain FSM implementation problems. The FSM lacks\neven a basic understanding of the *aggregate* result of backends\napplying various FSM heuristics over time, and with concurrent access.\nInserting backends currently behave like an amateur soccer team where\nevery individual soccer player chases the ball, without any\ncoordination among team members. The players in this analogy somehow\nfail to consider where the ball *is about to be* -- there is no\ntemporal awareness. They also miss the importance of cooperating with\neach other as a team -- there is also no spatial awareness, and no\nthought given to second order effects. This leads to increased buffer\nlock contention and fragmentation.\n\n(Other known FSM problems have been omitted for the sake of brevity.)\n\nBackground\n----------\n\nTo recap, the FSM tracks how much free space is in every heap page.\nMost FSM maintenance takes place during VACUUM, though ordinary\nconnection backends occasionally help to keep the FSM current, via\ncalls to RecordAndGetPageWithFreeSpace() made from hio.c.\n\nThere is also a bulk extension mechanism added by commit 719c84c1be,\nwhich is used when we detect multiple concurrent inserters. This bulk\nextension mechanism does change things a little (it gives some thought\nto systematic effects), though it still has the same basic issues: it\ndoesn't do nearly enough to group likely-related rows together. I\nsuspect that improving the bulk extension mechanism will be an\nimportant part of improving the overall picture. That mechanism needs\nto be more explicit, and more careful about who gets what free space\nwhen. I'll go into the significance of this mechanism to the FSM\nbelow, under \"Opportunities\". But first, more background information.\n\nPapers\n------\n\nI've taken time to review the database research literature, which\ndoesn't have all that much to say here. But there are a couple of\nrelevant classic papers that I know of [6][7].\n\nA lot of the considerations for free space management in heap-based\nsystems like DB2 and Oracle are naturally intertwined with concurrency\ncontrol, recovery, and even heavyweight locking. These systems must\ntreat TIDs as stable identifiers of a logical row, and not identifiers\nof a physical tuple -- another important difference. \"Free space\" is\nonly truly available to reuse in these systems some time after a\ndeleter commits and releases its heavyweight locks. This is why their\nFSM equivalents must be WAL-logged. There is even a need for logical\nUNDO to cover these FSM-equivalent data structures, which have their\nown tricky rollback path issues that align with those in the heap\nstructure. Everything is tied together to avoid rollback safety\nhazards. Physical rollback cannot find that the tuple needed to\nrestore form UNDO will no longer physically fit on the original heap\npage. Plus the line pointer can't just be recycled. It's all quite\ndelicate.\n\nAt first I thought that this UNDO rollback safety business meant that\nI had nothing to learn from these old papers. Postgres naturally\ndoesn't have to care about a transaction reusing space before another\ntransaction that deleted the space commits (or after an inserter\naborts) -- in Postgres, space is just that: space. We always have the\n*option* to create a new HOT chain on another page. However, I\neventually changed my mind -- these old papers are relevant. In a way\nPostgres actually does have rollback. It doesn't involve delicate\nphysical handling, in large part because TID stability isn't\nguaranteed in Postgres. But Postgres style \"logical rollback\" is more\nsimilar than it is different.\n\nLogical database\n----------------\n\nWhile it certainly is good that Postgres has the freedom to allow the\nphysical representation of the logical database to diverge in all\nkinds of ways, that doesn't mean that we should be totally unconcerned\nabout just how far the divergence goes. It's good that we have the\noption to retain a few extra versions without considering rollback\nhazards. But an option isn't an obligation. That's what makes an\noption useful -- it gives us the ability to have our cake, and eat it\ntoo.\n\nClearly we should try to avoid the need for a new HOT chain on another\nheap block, for example. OTOH we shouldn't bend over backwards to make\nsure of it -- that can't be worth it, since it isn't a matter of\nfundamental correctness with Postgres style concurrency control. As I\nsaid, we should try to be a little bit like ARIES with full UNDO\nrollback, purely to avoid bloat and improve temporal locality --\nconcurrent inserters should not clobber the same heap pages. I believe\nthat something a little like FSM transaction rollback is just what we\nneed here. A design that is inspired by other existing designs,\nincluding even the UNDO + rollback parts, which are pretty essential.\nTransaction boundaries and ownership semantics for free space really\ndo seem to matter when it comes to avoiding bloat.\n\nRoughly the same high level approach led to my developing bottom-up\nindex deletion for Postgres 14 [5] -- the same \"logical vs physical\"\ntension exists in Postgres B-Tree indexes. Using \"logical database\nsurrogates\" in the physical database is actually a standard family of\ntechniques used in DB systems design. This family of techniques has\nbeen underexploited within Postgres, probably because it isn't so\nnatural in a world without UNDO style rollback. This family of\ntechniques is something to keep in your \"bag of tricks\" as a Postgres\nhacker (as Hellerstein once put it).\n\nI'll return to how we might actually do something a bit like UNDO\nstyle rollback in the FSM later on. It is counterintuitive, but stay\nwith me.\n\nOpen and closed pages\n---------------------\n\nNote that other designs for FSM style structures (for a heap table\naccess method) all seem to have fewer than 10 possible \"page has this\nmuch free space\" increments [6] -- the granularity is far coarser than\nour own FSM_CATEGORIES granularity (which has a massive 255 distinct\nincrements of free space for each heap page). One reason for this is\nthat ignoring tiny differences avoids contention and fragmentation\nfrom chasing insignificant differences between heap blocks, which I\ndon't need to go into again (my earlier amatuer soccer team analogy is\nenough for now). But it's also related to the logical\ndatabase/rollback stuff that I just went into. It sometimes makes\nsense to think of a physical heap page as more than just a data\nstructure. Even things that we tend to naturally think of as strictly\nphysical may need to be rethought just a little.\n\nTake DB2's version of the FSM, FSIP [7]. This design usually doesn't\never end up inserting *any* new logical rows on a heap page after the\npage first fills -- it is initially \"open\" when first allocated, and\nthen quickly becomes \"closed\" to inserts of new logical rows, once it\ncrosses a certain almost-empty space threshold. The heap page usually\nstays \"closed\" forever. While the design does not *completely* ignore\nthe possibility that the page won't eventually get so empty that reuse\nreally does look like a good idea, it makes it rare. A heap page needs\nto have rather a lot of the original logical rows deleted before that\nbecomes possible again. It's rare for it to go backwards because the\nthreshold that makes a closed page become open again is much lower\n(i.e. involves much more free space) than the threshold that initially\nmade a (newly allocated) heap page closed. This one-way stickiness\nquality is important. As with simulated annealing algorithms, our\nalgorithm has heap pages that naturally settle. Our algorithm makes it\nhard to change things once they become settled -- it has to be really\nworth it before we'll flip a page back to \"open\" again. There is a\ngeneral bias against disturbing that which has become the settled\nstate. (I think that the terms \"open\" and \"closed\" come from the world\nof online bin packing problems, where the same tension and\nuncertainties exist.)\n\nThis stickiness concept is called \"hysteresis\" by some DB researchers,\noften when discussing UNDO stuff [8]. Having *far less* granularity\nthan FSM_CATEGORIES/255 seems essential to make that work as intended.\nPages need to be able to settle without being disturbed by noise-level\ndifferences. That's all that super fine grained values buy you: more\nnoise, more confusion.\n\nVisibility map\n--------------\n\nIf the logical database and natural locality are important to the FSM,\nthen what about the visibility map? And what about the relationship\nbetween the FSM and the visibility map, in light of all this?\n\nCurrently VACUUM doesn't care about how its FSM behavior interacts\nwith how it sets all-frozen/all-visible bits for the same heap page.\nTo me this seems completely unreasonable -- they're *obviously*\nrelated! We're probably only gaining a minimal amount of free space on\none occasion by ignoring the VM/FSM relationship, for which we pay a\nhigh cost. Worst of all we're *perpetuating the cycle* of dirtying and\nredirtying the same pages over time. Maybe we should go as far as\nmerging the FSM and VM, even -- that seems like a natural consequence\nof logical-ish/qualitative definitions of \"page is full\".\n\nOpportunities\n-------------\n\nNow more about what I think a new FSM design for Postgres *should* do.\nThis is almost a description of an actual data structure. A new FSM.\nBut not quite.\n\nAs we've seen, free space management in a true ARIES-style system\n(like the DB2 FSIP design) is forced to think of free space in terms\nof \"leases\", or bulk-allocated free lists of usually-contiguous pages.\nUnder a true ARIES design, it is strictly necessary to track which\ndeleter XID freed-up which individual lease of free space lest some\nconcurrent inserter reuse the space before it is truly safe to do so\n-- the deleter xact must commit before that reuse can be safely\nallowed. While delete + commit does seem mostly irrelevant to the\nPostgres FSM, insert + abort case handling seems to be something that\nwe can learn from. Maybe the same principles can be applied in\nPostgres, where we need leases to avoid leaks in the presence of\nerrors (not necessarily rollback per se). We must be able to tolerate\nincorrect speculations about where free space will be needed next.\nTransactions must be given the opportunity to make use of the heap\nfree space lease that they asked for -- but not forever. It's a\nbalancing act.\n\nImagine if the FSM tracked recent free space requests that have been\nsatisfied already. Requesting backends will maintain this same\nmetadata when they burn through their bulk allocation of reserved\nspace/heap pages. This new structure would contain metadata like the\nrequesting XID/backend for a given lease of heap pages, the number of\nleases during the last bulk extension operation, and maybe the number\nof concurrently waiting backends at that time. Now we have some sense\nof recent history, and start to recognize trends over time. The FSM is\nnow able to *take back* some of the space that it gives out, based on\nnew information. Now the FSM can afford to make mistakes because the\nmistakes can always be corrected a little later. The FSM can be\ngenerous based on speculation, heuristics, whatever it might be. It\nshould be possible for the FSM to have it both ways, more or less.\n\nConsider the bulk extension mechanism for concurrent inserters that\nwas added by commit 719c84c1be once again.\n\nThe mechanism's leader backend process performs the actual bulk heap\nrelation extension, allocating up to 512 new heap pages all at once.\nEven when the leader backend ends up extending a heap relation by\nquite a few pages (hundreds), the leader is still unable to *directly*\nhand off free space to particular backends that drove the leader to\nextend aggressively in the first place. It would be quite natural for\nthe leader backend to say to each individual follower backend: thank\nyou for waiting for me, here is a big contiguous range of heap pages\n(e.g., as many as 50 heap pages or more per xact when things truly\nramp up), which should be enough to allow you to avoid going to the\nFSM again for quite a long time.\n\nBut the leader backend doesn't do that at all -- it just puts all of\nthe pages (up to 512 total) in the FSM. All of the waiting follower\nbackends are left to senselessly fight it out for free space by simply\ngoing back to the FSM when they wake up again. Why can't they\ncooperate intelligently? What stops that today?\n\nFSM \"rollback\"\n-------------\n\n(This is where my argument comes together, finally.)\n\nFSM rollback in the FSIP paper is really just about reliable ownership\nsemantics. Ownership of free space in heap pages that is scoped at the\nlevel of transactions.\n\nIt seems to me that ownership of free space in heap pages by\nparticular transactions is really all that the bulk extension FSM\nlogic is missing -- and getting that right seems like a big part of\nfixing the FSM comprehensively. The bulk extension mechanism cannot\n*trust* the backends to use more than a little space at a time today.\nWhile on average each backend's use of free space probably *is*\npredictable over time, it only takes one or two straggler backends per\nbulk operation to mess everything up -- that's enough for the system\nto end up with very poor space utilization. Since we don't have any\nsense of ownership of space in heap pages by transactions today, the\ncode must hedge against stragglers/space leaks by making the space\n*generally* available to all. Of course, this hedging comes at a high\ncost: it prevents the whole system (heapam, FSM, and backends) from\ncapturing naturally occurring locality in a variety of important\ncases. Including the important TPC-C case I mentioned.\n\nExplicit scoped ownership of free space in heap pages removes the need\nto hedge. It addresses the problem of would-be space leaks directly,\nwhile *also* fixing the FSM locality problems implicitly. Metadata\nabout recent requests gives us the *context* needed to do all this\nwell. Sure, we don't need it for transaction rollback using ARIES\nstyle UNDO, but we can still use it for this. Perhaps this can be\npushed much further. Long running transactions ought to have as much\ntime as they need to use the large lease of free space that they were\nprovided. But when the transaction commits or aborts, we might then\nmake the FSM code much more aggressive about stealing space back from\nthe backend that inherits the lease from the now-committed\ntransaction. It all depends.\n\nMaybe we can teach VACUUM to eagerly clean up aborted transactions\nthat are known to have consumed a lot of free space that turns out to\nnot be needed for the inserted rows. It might also be feasible to make\nour new slimmed-down FSM crash-safe. The way that REDO routines for\nVACUUM handle FSM maintenance is pretty sloppy right now.\n\nBean counting\n------------\n\nIn general I find the idea that an algorithm can always make better\ndecisions with more information dubious. Accounting for every tiny\nlittle fragment of free space (\"bean counting\") is definitely not an\nintrinsic good. Maybe keeping that information is not just wasteful --\nmaybe it's actually harmful. There is a real risk of overinterpreting\nnoise-level difference [9]. I'd prefer to err in the direction of\nunderfitting.\n\nI now wonder if the FSM is fundamentally doing the wrong thing by\nkeeping track of all \"free space\" in every page over time. Why\nwouldn't we just have a free space management strategy that is\ngenerally only concerned with recent events? If we find a way to make\nalmost all newly allocated heap pages become \"closed\" quickly (maybe\nthey're marked all-frozen quickly too), and make sure that that\ncondition is sticky, then this can work out well. We may not even need\nto store explicit freespace information for most heap pages in the\ndatabase -- a page being \"closed\" can be made implicit by the FSM\nand/or VM. Making heap pages age-out like this (and mostly stay that\nway over time) has obvious benefits in many different areas.\n\nThis won't help workloads like stock pgbench, which is pretty\nunrealistic anyway. But it needn't hurt them either.\n\n[1] https://postgr.es/m/CAH2-WzkEP6wz2Eg7mgKbF-qTPi21+BWrJgNm0qfU5kf0iJBV2g@mail.gmail.com\n[2] https://postgr.es/m/0265f9e2-3e32-e67d-f106-8abde596c0e4@commandprompt.com\n[3] https://github.com/wieck/benchmarksql/commit/6ac326ad23d55de2edc18bfbffb10b21f1b39b48\n[4] https://github.com/wieck/benchmarksql/commit/0830c5f526061529eb2b45831c544539caa65435\n[5] https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=d168b666823b6e0bcf60ed19ce24fb5fb91b8ccf\n[6] https://dl.acm.org/doi/abs/10.1145/235968.233355\n[7] https://www.semanticscholar.org/paper/Algorithms-for-Flexible-Space-Management-in-Systems-Mohan-Haderle/9db1a8104daade31949b6399cac9169751fa1605\n[8] https://queue.acm.org/detail.cfm?id=3099561\n[9] https://en.wikipedia.org/wiki/Bias%E2%80%93variance_tradeoff#Approaches\n--\nPeter Geoghegan\n\n\n", "msg_date": "Mon, 16 Aug 2021 10:35:45 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Mon, Aug 16, 2021 at 10:35:45AM -0700, Peter Geoghegan wrote:\n> I have suspected that there are serious design issues with the FSM\n> (and related heapam code like hio.c) for several years now [1]. This\n> has a lot to do with the experience of using Jan Wieck's BenchmarkSQL\n> implementation of TPC-C [2][3][4]. It clearly makes Postgres exhibit\n> pathological performance issues, especially heap fragmentation.\n\nOK, here is my feedback. First, I understand the space\nreservation/soccer idea, but I am also concerned that adding space\nreservation could improve some things and make others worse.\n\nSecond, let's look at a concrete example, and see how it can be improved\nmore simply. As I understand it, there are three operations that need\nfree space:\n\n\t1. INSERT/COPY\n\t2. UPDATE where there is insufficient space on the page of the\n\t old row\n\t3. UPDATE where there is sufficient page space\n\nThe third option already can use the existing page for a HOT update, so\nthe FSM doesn't matter. For 1 & 2, suppose you have a table with 10 8k\npages, all 80% full. As I understand it, the first page will go from\n80% to 81%, then the next row addition will take the second page from\n80% to 81%, until all pages are 81%, and then it starts over again. Is\nthat accurate? Is that the non-temporal memory issue you are concerned\nabout?\tDoesn't spreading the new rows out increase the ability to do\nHOT updates?\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Mon, 16 Aug 2021 18:49:28 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Mon, Aug 16, 2021 at 3:49 PM Bruce Momjian <bruce@momjian.us> wrote:\n> OK, here is my feedback. First, I understand the space\n> reservation/soccer idea, but I am also concerned that adding space\n> reservation could improve some things and make others worse.\n\nThat is definitely a legitimate concern.\n\nThere is a trade-off here: if we do too much preallocation, there may\nbe cases where the preallocated space that we expected to be used\nquickly is never used by anybody. But that doesn't seem like a\nproblem, provided we don't lose track of the fact that it happened.\nThen the worst that can happen is that we have empty pages that nobody\nwill ever use, because nobody inserts into the table ever again (not\nthe backend with the leaked space lease, not anybody else). That seems\nmanageable. We can add some kind of ramp-up behavior that gets more\nand more aggressive as demand for new space from backends is steady or\nincreasing.\n\n> Second, let's look at a concrete example, and see how it can be improved\n> more simply. As I understand it, there are three operations that need\n> free space:\n>\n> 1. INSERT/COPY\n> 2. UPDATE where there is insufficient space on the page of the\n> old row\n> 3. UPDATE where there is sufficient page space\n\nRight.\n\n> The third option already can use the existing page for a HOT update, so\n> the FSM doesn't matter.\n\nI agree.\n\nAll good questions. Thank you for diving in on this.\n\n> For 1 & 2, suppose you have a table with 10 8k\n> pages, all 80% full. As I understand it, the first page will go from\n> 80% to 81%, then the next row addition will take the second page from\n> 80% to 81%, until all pages are 81%, and then it starts over again. Is\n> that accurate?\n\nNo. Generally backends have their own target block (a simple\nBlockNumber) that they store in the relcache, one per table recently\nmodified. Backends/heapam uses RelationGetTargetBlock() to access this\nlocal cache. So there is \"backend affinity\" for particular individual\nheap pages, even today. However, that still has many problems.\n\nIt doesn't make sense to have a local cache for a shared resource --\nthat's the problem. You actually need some kind of basic locking or\nlease system, so that 10 backends don't all decide at the same time\nthat one particular heap block is fully empty, and therefore a good\ntarget block for that backend alone. It's as if the backends believe\nthat they're special little snowflakes, and that no other backend\ncould possibly be thinking the same thing at the same time about the\nsame heap page. And so when TPC-C does its initial bulk insert,\ndistinct orders are already shuffled together in a hodge-podge, just\nbecause concurrent bulk inserters all insert on the same heap pages.\n\nIf we could safely give out 10 or 50 pages directly to each backend,\nthen clearly the related data would be stored together in this\nscenario -- each backend would be able to work through its lease of\ncontiguous heap pages for quite a while before revisiting the\nFSM/relation extension. The trick is to teach the implementation to do\nthat without allowing the backend to permanently leak whole entire\nleases with maybe dozens of free pages.\n\nSystems like DB2 and Oracle probably can't have this problem. Even the\nbulk lease case is just an extension of something they had to do\nanyway. You see, some kind of FSM lease system that knows about\ntransaction lifetime for any given piece of free space is strictly\nnecessary with UNDO based rollback. Without that, transaction rollback\nbreaks in certain edge cases involving concurrent inserts into the\nsame page, right before a rollback that needs to put an updated\nversion back in place. If the updated version from undo happens to be\nphysically larger than the now-aborted successor version, and if there\nis little or no space left to cover that, what can rollback do about\nit? Nothing. It's a nasty bug. They use heavyweight locks to avoid\nthis.\n\n> Is that the non-temporal memory issue you are concerned\n> about?\n\nWhen I talk about memory or time, what I'm usually referring to is the\nability to manage larger allocations of multiple blocks for a while\nafter they're originally requested. So that a requesting\ntransaction/backend is given the opportunity to use the space that\nthey asked for. They shouldn't be completely trusted. We should trust\nbut verify.\n\n> Doesn't spreading the new rows out increase the ability to do\n> HOT updates?\n\nIt's true that the problem scenario with TPC-C does involve updates,\nand it's true that that's when things really go badly. But I\ndeliberately haven't gone into the role that the updates play there\ntoo much. Not just yet.\n\nIt's important to note that the problems really do start when we\ninsert, even if that's not obvious -- that's when the locality is\nlost, right when the original order transaction comes in. We lose\nlocality just because we have concurrent inserters into the same\ntable, where each transaction inserts multiple related rows. We fail\nto group related rows together right from the start, setting us up for\nfailure later on.\n\nThis is actually quite simple -- the chaos that follows is where it\ngets truly complicated (and not necessarily worth getting into just\nyet). The update of a given order and its order lines entries takes\nplace hours later, within a delivery transaction.\n\nAnother concern is knock on effects *after* any initial problematic\nupdates -- that's certainly not where it ends. Every action has\nconsequences, and these consequences themselves have consequences. By\nmigrating a row from an earlier block into a later block (both\nphysically and temporally early/late), we're not just changing things\nfor that original order row or rows (the order non-HOT-updated by the\ndelivery transaction). Since the old/original version left behind by a\ndelivery transaction will itself get vacuumed eventually, that space\ngoes in the FSM eventually. And so this same block will get some entirely\nunrelated version (could be a new insert or update). It's systematic.\n\nWe dare not waste a tiny amount of free space. Surely we should cut\nour losses at some point and accept that we're \"wasting space\", but\nthere is never any natural backpressure. Nothing to break the cycle of\nfragmentation. (This is another thing involving time, not quite\nrelated to my central point about free space leases.)\n\n--\nPeter Geoghegan\n\n\n", "msg_date": "Mon, 16 Aug 2021 17:15:36 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Mon, Aug 16, 2021 at 5:15 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> Another concern is knock on effects *after* any initial problematic\n> updates -- that's certainly not where it ends. Every action has\n> consequences, and these consequences themselves have consequences. By\n> migrating a row from an earlier block into a later block (both\n> physically and temporally early/late), we're not just changing things\n> for that original order row or rows (the order non-HOT-updated by the\n> delivery transaction).\n\nTo be clear, TPC-C looks like this: each order row and each order line\nrow will be inserted just once, and then later updated just once. But\nthat's it, forever -- no more modifications. Both tables grow and grow\nfor as long as the benchmark runs. Users with workloads like this will\nnaturally expect that performance will steady over time. Even over\ndays or even weeks. But that's not what we see.\n\nWhat we actually see is that the FSM can never quite resist the\ntemptation to dirty older pages that should be aging out. And so\nperformance degrades over days and weeks -- that's how long Jan has\nsaid that it can take.\n\nThe FSM does have a bias in favor of using earlier pages in favor of\nlater pages, in order to make relation truncation by VACUUM more\nlikely in general. That bias certainly isn't helping us here, and\nmight be another thing that hurts us. I think that the fundamental\nproblem is that the FSM just doesn't have any way of recognizing that\nit's behavior is penny wise, pound foolish. I don't believe that there\nis any fundamental reason why Postgres can't have *stable* long term\nperformance for this workload in the way that it's really expected to.\nThat seems possible within the confines of the existing design for HOT\nand VACUUM, which already work very well for the first few hours.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Mon, 16 Aug 2021 17:42:11 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "Hi,\n\nOn 2021-08-16 10:35:45 -0700, Peter Geoghegan wrote:\n> Problems\n> --------\n>\n> The FSM gives out space without considering the passage of time, or\n> the likelihood that a particular transaction or client will consume\n> its requested free space in a more or less predictable and steady way\n> over time. It has no memory. The FSM therefore fails to capture\n> naturally occurring locality, or at least doesn't specifically care\n> about it. This is the central problem, that all other problems with\n> the FSM seem to stem from in one way or another.\n\nI suspect that one other fairly fundamental issue is that we are very\nreticent updating the FSM with information about free space. As long as\nthat's the case a smarter placement logic would often not have a better\nplace to choose from.\n\n\n> Background\n> ----------\n>\n> To recap, the FSM tracks how much free space is in every heap page.\n> Most FSM maintenance takes place during VACUUM, though ordinary\n> connection backends occasionally help to keep the FSM current, via\n> calls to RecordAndGetPageWithFreeSpace() made from hio.c.\n>\n> There is also a bulk extension mechanism added by commit 719c84c1be,\n> which is used when we detect multiple concurrent inserters. This bulk\n> extension mechanism does change things a little (it gives some thought\n> to systematic effects), though it still has the same basic issues: it\n> doesn't do nearly enough to group likely-related rows together. I\n> suspect that improving the bulk extension mechanism will be an\n> important part of improving the overall picture.\n\nI think the design of the current bulk extension mechanism is quite backward\n(it only takes contention into account not other needs for bulk work, it does\nexpensive stuff like finding victim buffers under lock, it doesn't release\nlocks until all blocks are extended, ...). But: I don't think a bulk\nextension mechanism should be tasked with doing grouping or anything like\nthat.\n\n\n> Take DB2's version of the FSM, FSIP [7]. This design usually doesn't\n> ever end up inserting *any* new logical rows on a heap page after the\n> page first fills -- it is initially \"open\" when first allocated, and\n> then quickly becomes \"closed\" to inserts of new logical rows, once it\n> crosses a certain almost-empty space threshold. The heap page usually\n> stays \"closed\" forever. While the design does not *completely* ignore\n> the possibility that the page won't eventually get so empty that reuse\n> really does look like a good idea, it makes it rare. A heap page needs\n> to have rather a lot of the original logical rows deleted before that\n> becomes possible again. It's rare for it to go backwards because the\n> threshold that makes a closed page become open again is much lower\n> (i.e. involves much more free space) than the threshold that initially\n> made a (newly allocated) heap page closed. This one-way stickiness\n> quality is important.\n\nI suspect that we'd get a *LOT* of complaints if we introduced that degree of\nstickiness.\n\n\n> This stickiness concept is called \"hysteresis\" by some DB researchers,\n> often when discussing UNDO stuff [8]. Having *far less* granularity\n> than FSM_CATEGORIES/255 seems essential to make that work as intended.\n> Pages need to be able to settle without being disturbed by noise-level\n> differences. That's all that super fine grained values buy you: more\n> noise, more confusion.\n\nWhy is that directly tied to FSM_CATEGORIES? ISTM that there's ways to benefit\nfrom a fairly granular FSM_CATEGORIES, while still achieving better\nlocality. You could e.g. search for free space for an out-of-page update in\nnearby pages with a lower free-percentage threshold, while having a different\nthreshold and selection criteria for placement of inserts.\n\n\n> Visibility map\n> --------------\n>\n> If the logical database and natural locality are important to the FSM,\n> then what about the visibility map? And what about the relationship\n> between the FSM and the visibility map, in light of all this?\n>\n> Currently VACUUM doesn't care about how its FSM behavior interacts\n> with how it sets all-frozen/all-visible bits for the same heap page.\n> To me this seems completely unreasonable -- they're *obviously*\n> related! We're probably only gaining a minimal amount of free space on\n> one occasion by ignoring the VM/FSM relationship, for which we pay a\n> high cost. Worst of all we're *perpetuating the cycle* of dirtying and\n> redirtying the same pages over time. Maybe we should go as far as\n> merging the FSM and VM, even -- that seems like a natural consequence\n> of logical-ish/qualitative definitions of \"page is full\".\n\nThe density of the VM is fairly crucial for efficient IOS, so I'm doubtful\nmerging FSM and VM is a good direction to go to. Additionally we need to make\nsure that the VM is accurately durable, which isn't the case for the FSM\n(which I think we should use to maintain it more accurately).\n\nBut perhaps I'm just missing something here. What is the strong interlink\nbetween FSM and all-frozen/all-visible you see on the side of VACUUM? ISTM\nthat the main linkage is on the side of inserts/update that choose a target\npage from the FSM. Isn't it better to make that side smarter?\n\n\n\n> Imagine if the FSM tracked recent free space requests that have been\n> satisfied already. Requesting backends will maintain this same\n> metadata when they burn through their bulk allocation of reserved\n> space/heap pages. This new structure would contain metadata like the\n> requesting XID/backend for a given lease of heap pages, the number of\n> leases during the last bulk extension operation, and maybe the number\n> of concurrently waiting backends at that time. Now we have some sense\n> of recent history, and start to recognize trends over time. The FSM is\n> now able to *take back* some of the space that it gives out, based on\n> new information. Now the FSM can afford to make mistakes because the\n> mistakes can always be corrected a little later. The FSM can be\n> generous based on speculation, heuristics, whatever it might be. It\n> should be possible for the FSM to have it both ways, more or less.\n\nHm. To me this seems like a somewhat separate layer from the FSM. Having that\nkind of data go through shared buffers, with a need to worry about on-disk\nconsistency/cleanup etc, the inability to add granular locks on a sub-page\nlevel, the need to go through buffer mapping / pinning all seem like things\nyou wouldn't actually want.\n\nTo me this seems like it'd be better addressed by a shared, per-relfilenode,\nin-memory datastructure. Thomas Munro has been working on keeping accurate\nper-relfilenode relation size information. ISTM that that that'd be a better\nplace to hook in for this.\n\n\n> would be quite natural for the leader backend to say to each individual\n> follower backend: thank you for waiting for me, here is a big contiguous\n> range of heap pages (e.g., as many as 50 heap pages or more per xact when\n> things truly ramp up), which should be enough to allow you to avoid going to\n> the FSM again for quite a long time.\n\nThat'd end up badly if we did for a relation that's hotly inserted into by a\nlot of connections, but where each connection only inserts a few rows. I\nsuspect we'd either need information from the inserting backends about the\nnumber of pages they're likely going to need (e.g. a smarter \"extension queue\"\nwhere each entry lists the number of pages requested) and/or stats about the\nnumber of consecutive insertions a relation typically gets.\n\n\n> But the leader backend doesn't do that at all -- it just puts all of\n> the pages (up to 512 total) in the FSM. All of the waiting follower\n> backends are left to senselessly fight it out for free space by simply\n> going back to the FSM when they wake up again. Why can't they\n> cooperate intelligently? What stops that today?\n\nThe lack of suitable in-memory coordination facilities.\n\nIt turns out that I looked a bunch at this area because of AIO + DIO: With DIO\nthe typical linux filesystems (ext4, xfs) do not perform any delayed\nallocation, which means that the non-bulk extension leads to *horrible*\nfilesystem fragmentation. And even the bulk paths don't allocate enough blocks\nat once to avoid fragmentation with common amounts of concurrency. But just\nincreasing the degree of bulk extension isn't helpful - it just exacerbates\nalready bad thundering herd issues: All backends will decide to try to extend\nat the same time, all-1 backends will wait, one backend will extend wake up\nall-1, they then contend for the same locks etc.\n\nI addressed (or rather sidestepped) this to a small degree in the AIO+DIO\npatchset, by making extension faster and doing a few improvements around\nlocking. But it's not good enough.\n\nIf the relation extension infrastructure instead had information about the\nnumber of blocks each waiter wants and we had Thomas' \"accurate shared\nrelation size\" infrastructure, we could do a lot better:\n\n1) Whenever a backend needs new space and most of the previously bulk-extended\n space is used opportunistically try to bulk-extend. In the happy path this\n avoids the thundering herd issue because other backends can continue\n inserting while extension is in progress.\n\n2) Whenever bulk extending, release pages to individual backends by looking in\n the queue of backends needing extension and wake up backends individually\n whenever we've bulk extended sufficiently for that backend.\n\n This provides two main benefits: First, it avoids all backends trying to\n acquire exactly the same resources just after waking up, without being able\n to benefit (because the first backend will often just fill the\n page). Second, it improves average latency during extension substantially,\n because individual backends can start continuing as soon as bulk extension\n has progressed enough for some backend, rather than needing to wait for the\n entire extension.\n\n\n\n> FSM \"rollback\"\n> -------------\n>\n> (This is where my argument comes together, finally.)\n>\n> FSM rollback in the FSIP paper is really just about reliable ownership\n> semantics. Ownership of free space in heap pages that is scoped at the\n> level of transactions.\n>\n> It seems to me that ownership of free space in heap pages by\n> particular transactions is really all that the bulk extension FSM\n> logic is missing -- and getting that right seems like a big part of\n> fixing the FSM comprehensively. The bulk extension mechanism cannot\n> *trust* the backends to use more than a little space at a time today.\n> While on average each backend's use of free space probably *is*\n> predictable over time, it only takes one or two straggler backends per\n> bulk operation to mess everything up -- that's enough for the system\n> to end up with very poor space utilization. Since we don't have any\n> sense of ownership of space in heap pages by transactions today, the\n> code must hedge against stragglers/space leaks by making the space\n> *generally* available to all. Of course, this hedging comes at a high\n> cost: it prevents the whole system (heapam, FSM, and backends) from\n> capturing naturally occurring locality in a variety of important\n> cases. Including the important TPC-C case I mentioned.\n\nI think the fundamental issue of bulk extension issue is more that bulk\nextension shouldn't actually get pages from the FSM at all. That's just an\nugly implementation detail of the hack we have currently, rather than\nsomething that should live on. We may want to decide to continue inserting\nbulk extended pages into the FSM to handle edge cases of backends erroring out\nbefore space is used, but the happy path should not touch the FSM at all.\n\n\n> Explicit scoped ownership of free space in heap pages removes the need\n> to hedge. It addresses the problem of would-be space leaks directly,\n> while *also* fixing the FSM locality problems implicitly. Metadata\n> about recent requests gives us the *context* needed to do all this\n> well.\n\nIt sounds like you're thinking of using some global history, or at least a\nbackend local history? I think it might be better to have backend local,\nper-command state. E.g. for a COPY aggressively increase the amount of space\nreserved, but not for a single-row insert.\n\n\n\n> I now wonder if the FSM is fundamentally doing the wrong thing by\n> keeping track of all \"free space\" in every page over time. Why\n> wouldn't we just have a free space management strategy that is\n> generally only concerned with recent events?\n\nI guess it depends on what you define as recent, but I don't see a way to\nbound the timeframe usefully. We need to deal with cases where table sizes go\nup and down over time, e.g. because there's periodic batch activity and\nongoing activity. What's the time bound for unused space somewhere in a\nrelation? I don't see any, unless we add compaction logic to vacuum.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 17 Aug 2021 06:17:51 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Tue, Aug 17, 2021 at 9:18 AM Andres Freund <andres@anarazel.de> wrote:\n> > Take DB2's version of the FSM, FSIP [7]. This design usually doesn't\n> > ever end up inserting *any* new logical rows on a heap page after the\n> > page first fills -- it is initially \"open\" when first allocated, and\n> > then quickly becomes \"closed\" to inserts of new logical rows, once it\n> > crosses a certain almost-empty space threshold. The heap page usually\n> > stays \"closed\" forever. While the design does not *completely* ignore\n> > the possibility that the page won't eventually get so empty that reuse\n> > really does look like a good idea, it makes it rare. A heap page needs\n> > to have rather a lot of the original logical rows deleted before that\n> > becomes possible again. It's rare for it to go backwards because the\n> > threshold that makes a closed page become open again is much lower\n> > (i.e. involves much more free space) than the threshold that initially\n> > made a (newly allocated) heap page closed. This one-way stickiness\n> > quality is important.\n>\n> I suspect that we'd get a *LOT* of complaints if we introduced that degree of\n> stickiness.\n\nI don't know what the right degree of stickiness is, but I can easily\nbelieve that we want to have more than none. Part of Peter's point, at\nleast as I understand it, is that if a page has 100 tuples and you\ndelete 1 or 2 or 3 of them, it is not smart to fill up the space thus\ncreated with 1 or 2 or 3 new tuples. You should instead hope that\nspace will optimize future HOT updates, or else wait for the page to\nlose some larger number of tuples and then fill up all the space at\nthe same time with tuples that are, hopefully, related to each other\nin some useful way. Now what's the threshold? 20 out of 100? 50? 80?\nThat's not really clear to me. But it's probably not 1 out of 100.\n\n> > This stickiness concept is called \"hysteresis\" by some DB researchers,\n> > often when discussing UNDO stuff [8]. Having *far less* granularity\n> > than FSM_CATEGORIES/255 seems essential to make that work as intended.\n> > Pages need to be able to settle without being disturbed by noise-level\n> > differences. That's all that super fine grained values buy you: more\n> > noise, more confusion.\n>\n> Why is that directly tied to FSM_CATEGORIES? ISTM that there's ways to benefit\n> from a fairly granular FSM_CATEGORIES, while still achieving better\n> locality. You could e.g. search for free space for an out-of-page update in\n> nearby pages with a lower free-percentage threshold, while having a different\n> threshold and selection criteria for placement of inserts.\n\nYeah, I don't think that reducing FSM_CATEGORIES is likely to have\nmuch value for its own sake. But it might be useful as a way of\naccomplishing some other goal. For example if we decided that we need\na bit per page to track \"open\" vs. \"closed\" status or something of\nthat sort, I don't think we'd lose much by having fewer categories.\n\n> The density of the VM is fairly crucial for efficient IOS, so I'm doubtful\n> merging FSM and VM is a good direction to go to. Additionally we need to make\n> sure that the VM is accurately durable, which isn't the case for the FSM\n> (which I think we should use to maintain it more accurately).\n>\n> But perhaps I'm just missing something here. What is the strong interlink\n> between FSM and all-frozen/all-visible you see on the side of VACUUM? ISTM\n> that the main linkage is on the side of inserts/update that choose a target\n> page from the FSM. Isn't it better to make that side smarter?\n\nI don't have a well-formed opinion on this point yet. I am also\nskeptical of the idea of merging the FSM and VM, because it seems to\nme that which pages are all-visible and which pages are full are two\ndifferent things. However, there's something to Peter's point too. An\nempty page is all-visible but still valid as an insertion target, but\nthis is not as much of a contradiction to the idea of merging them as\nit might seem, because marking the empty page as all-visible is not\nnearly as useful as marking a full page all-visible. An index-only\nscan can't care about the all-visible status of a page that doesn't\ncontain any tuples, and we're also likely to make the page non-empty\nin the near future, in which case the work we did to set the\nall-visible bit and log the change was wasted. The only thing we're\naccomplishing by making the page all-visible is letting VACUUM skip\nit, which will work out to a win if it stays empty for multiple VACUUM\ncycles, but not otherwise.\n\nConceptually, you might think of the merged data structure as a\n\"quiescence map.\" Pages that aren't being actively updated are\nprobably all-visible and are probably not great insertion targets.\nThose that are being actively updated are probably not all-visible and\nhave better chances of being good insertion targets. However, there\nare a lot of gremlins buried in the word \"probably.\" A page could get\nfull but still not be all-visible for a long time, due to long-running\ntransactions, and it doesn't seem likely to me that we can just ignore\nthat possibility. Nor on the other hand does the difference between an\nold-but-mostly-full page and an old-but-mostly-empty page seem like\nsomething we just want to ignore. So I don't know how a merged data\nstructure would actually end up being an improvement, exactly.\n\n> To me this seems like it'd be better addressed by a shared, per-relfilenode,\n> in-memory datastructure. Thomas Munro has been working on keeping accurate\n> per-relfilenode relation size information. ISTM that that that'd be a better\n> place to hook in for this.\n\n+1. I had this same thought reading Peter's email. I'm not sure if it\nmakes sense to hook that into Thomas's work, but I think it makes a\nton of sense to use shared memory to coordinate transient state like\n\"hey, right now I'm inserting into this block, you guys leave it\nalone\" while using the disk for durable state like \"here's how much\nspace this block has left.\"\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 17 Aug 2021 12:48:45 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Mon, Aug 16, 2021 at 05:15:36PM -0700, Peter Geoghegan wrote:\n> It doesn't make sense to have a local cache for a shared resource --\n> that's the problem. You actually need some kind of basic locking or\n> lease system, so that 10 backends don't all decide at the same time\n> that one particular heap block is fully empty, and therefore a good\n> target block for that backend alone. It's as if the backends believe\n> that they're special little snowflakes, and that no other backend\n> could possibly be thinking the same thing at the same time about the\n> same heap page. And so when TPC-C does its initial bulk insert,\n> distinct orders are already shuffled together in a hodge-podge, just\n> because concurrent bulk inserters all insert on the same heap pages.\n\nOK, I am trying to think of something simple we could test to see the\nbenefit, with few downsides. I assume the case you are considering is\nthat you have a 10 8k-page table, and one page is 80% full and the\nothers are 81% full, and if several backends start adding rows at the\nsame time, they will all choose the 80%-full page.\n\nWhat if we change how we select pages with this:\n\n1. find the page with the most free space\n2. find all pages with up to 10% less free space than page #1\n3. count the number of pages in #2\n4. compute the proc_id modulus step #3 and use that page's offset from\n step #2\n\nFor example:\n\n1. page with most freespace is 95% free\n2. pages 2,4,6,8,10 have between 86%-95% free\n3. five pages\n4. proc id 14293 % 5 = 3 so use the third page from #2, page 6\n\nThis should spread out page usage to be more even, but still favor pages\nwith more freespace. Yes, this is simplistic, but it would seem to have\nfew downsides and I would be interested to see how much it helps.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Tue, 17 Aug 2021 14:24:40 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Mon, Aug 16, 2021 at 1:36 PM Peter Geoghegan <pg@bowt.ie> wrote:\n>\n> Open and closed pages\n> ---------------------\n\n> This stickiness concept is called \"hysteresis\" by some DB researchers,\n> often when discussing UNDO stuff [8]. Having *far less* granularity\n> than FSM_CATEGORIES/255 seems essential to make that work as intended.\n> Pages need to be able to settle without being disturbed by noise-level\n> differences. That's all that super fine grained values buy you: more\n> noise, more confusion.\n\nI'm not sure it's essential to have \"far\" fewer categories, if the\nclosed-to-open transition is made less granular through some other\nmechanism. We can certainly get by with fewer categories, freeing up bits\n-- it seems we'd need at least one bit to track a block's open-close state.\n\n> Visibility map\n> --------------\n>\n> If the logical database and natural locality are important to the FSM,\n> then what about the visibility map? And what about the relationship\n> between the FSM and the visibility map, in light of all this?\n>\n> Currently VACUUM doesn't care about how its FSM behavior interacts\n> with how it sets all-frozen/all-visible bits for the same heap page.\n> To me this seems completely unreasonable -- they're *obviously*\n> related! We're probably only gaining a minimal amount of free space on\n> one occasion by ignoring the VM/FSM relationship, for which we pay a\n> high cost. Worst of all we're *perpetuating the cycle* of dirtying and\n> redirtying the same pages over time. Maybe we should go as far as\n> merging the FSM and VM, even -- that seems like a natural consequence\n> of logical-ish/qualitative definitions of \"page is full\".\n\n> [...]\n\n> I now wonder if the FSM is fundamentally doing the wrong thing by\n> keeping track of all \"free space\" in every page over time. Why\n> wouldn't we just have a free space management strategy that is\n> generally only concerned with recent events? If we find a way to make\n> almost all newly allocated heap pages become \"closed\" quickly (maybe\n> they're marked all-frozen quickly too), and make sure that that\n> condition is sticky, then this can work out well. We may not even need\n> to store explicit freespace information for most heap pages in the\n> database -- a page being \"closed\" can be made implicit by the FSM\n> and/or VM. Making heap pages age-out like this (and mostly stay that\n> way over time) has obvious benefits in many different areas.\n\nThe second paragraph here is an interesting idea and makes a great deal of\nsense. It would lead to smaller FSMs that are navigated more quickly and\nlocked for shorter durations.\n\nImplicit \"closure\" seems riskier in my view if you want to bring VM\nqualities into it, however. Currently, setting an all-visible or all-frozen\nflag must be correct and crash-safe, but clearing those is just a lost\noptimization. If either of those qualities are implicit by lack of\nreference, it seems more vulnerable to bugs.\n\nOn Tue, Aug 17, 2021 at 12:48 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> On Tue, Aug 17, 2021 at 9:18 AM Andres Freund <andres@anarazel.de> wrote:\n>\n> > To me this seems like it'd be better addressed by a shared,\nper-relfilenode,\n> > in-memory datastructure. Thomas Munro has been working on keeping\naccurate\n> > per-relfilenode relation size information. ISTM that that that'd be a\nbetter\n> > place to hook in for this.\n>\n> +1. I had this same thought reading Peter's email. I'm not sure if it\n> makes sense to hook that into Thomas's work, but I think it makes a\n> ton of sense to use shared memory to coordinate transient state like\n> \"hey, right now I'm inserting into this block, you guys leave it\n> alone\" while using the disk for durable state like \"here's how much\n> space this block has left.\"\n\nThis makes sense as well. Shared memory for more recent / highly contended\nstate, and disk for less recent / less contended / stickier state. This\nalso might have the advantage of smaller, more focused projects from a\ncoding standpoint.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Mon, Aug 16, 2021 at 1:36 PM Peter Geoghegan <pg@bowt.ie> wrote:>> Open and closed pages> ---------------------> This stickiness concept is called \"hysteresis\" by some DB researchers,> often when discussing UNDO stuff [8]. Having *far less* granularity> than FSM_CATEGORIES/255 seems essential to make that work as intended.> Pages need to be able to settle without being disturbed by noise-level> differences. That's all that super fine grained values buy you: more> noise, more confusion.I'm not sure it's essential to have \"far\" fewer categories, if the closed-to-open transition is made less granular through some other mechanism. We can certainly get by with fewer categories, freeing up bits -- it seems we'd need at least one bit to track a block's open-close state.> Visibility map> -------------->> If the logical database and natural locality are important to the FSM,> then what about the visibility map? And what about the relationship> between the FSM and the visibility map, in light of all this?>> Currently VACUUM doesn't care about how its FSM behavior interacts> with how it sets all-frozen/all-visible bits for the same heap page.> To me this seems completely unreasonable -- they're *obviously*> related! We're probably only gaining a minimal amount of free space on> one occasion by ignoring the VM/FSM relationship, for which we pay a> high cost. Worst of all we're *perpetuating the cycle* of dirtying and> redirtying the same pages over time. Maybe we should go as far as> merging the FSM and VM, even -- that seems like a natural consequence> of logical-ish/qualitative definitions of \"page is full\".> [...]> I now wonder if the FSM is fundamentally doing the wrong thing by> keeping track of all \"free space\" in every page over time. Why> wouldn't we just have a free space management strategy that is> generally only concerned with recent events? If we find a way to make> almost all newly allocated heap pages become \"closed\" quickly (maybe> they're marked all-frozen quickly too), and make sure that that> condition is sticky, then this can work out well. We may not even need> to store explicit freespace information for most heap pages in the> database -- a page being \"closed\" can be made implicit by the FSM> and/or VM. Making heap pages age-out like this (and mostly stay that> way over time) has obvious benefits in many different areas.The second paragraph here is an interesting idea and makes a great deal of sense. It would lead to smaller FSMs that are navigated more quickly and locked for shorter durations.Implicit \"closure\" seems riskier in my view if you want to bring VM qualities into it, however. Currently, setting an all-visible or all-frozen flag must be correct and crash-safe, but clearing those is just a lost optimization. If either of those qualities are implicit by lack of reference, it seems more vulnerable to bugs.On Tue, Aug 17, 2021 at 12:48 PM Robert Haas <robertmhaas@gmail.com> wrote:>> On Tue, Aug 17, 2021 at 9:18 AM Andres Freund <andres@anarazel.de> wrote:>> > To me this seems like it'd be better addressed by a shared, per-relfilenode,> > in-memory datastructure. Thomas Munro has been working on keeping accurate> > per-relfilenode relation size information. ISTM that that that'd be a better> > place to hook in for this.>> +1. I had this same thought reading Peter's email. I'm not sure if it> makes sense to hook that into Thomas's work, but I think it makes a> ton of sense to use shared memory to coordinate transient state like> \"hey, right now I'm inserting into this block, you guys leave it> alone\" while using the disk for durable state like \"here's how much> space this block has left.\"This makes sense as well. Shared memory for more recent / highly contended state, and disk for less recent / less contended / stickier state. This also might have the advantage of smaller, more focused projects from a coding standpoint.--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Tue, 17 Aug 2021 15:11:03 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Tue, Aug 17, 2021 at 6:18 AM Andres Freund <andres@anarazel.de> wrote:\n> I suspect that one other fairly fundamental issue is that we are very\n> reticent updating the FSM with information about free space. As long as\n> that's the case a smarter placement logic would often not have a better\n> place to choose from.\n\nI think so too. But that is made a lot harder by the supposed need to\nrepresent the amount of freespace in FSM_CATEGORIES (255) distinct\nincrements. As opposed to maybe 4 distinct increments per page, like\nin other systems. You only have to update the externally stored\nmetadata when a threshold is crossed.\n\n(This isn't the main reason why I don't like that; more on that later.)\n\n> I think the design of the current bulk extension mechanism is quite backward\n> (it only takes contention into account not other needs for bulk work, it does\n> expensive stuff like finding victim buffers under lock, it doesn't release\n> locks until all blocks are extended, ...). But: I don't think a bulk\n> extension mechanism should be tasked with doing grouping or anything like\n> that.\n\nMaybe I'm just drawing the boundaries differently in my head, which\ndoesn't seem like a real difference of opinion.\n\n> > Take DB2's version of the FSM, FSIP [7]. This design usually doesn't\n> > ever end up inserting *any* new logical rows on a heap page after the\n> > page first fills -- it is initially \"open\" when first allocated, and\n> > then quickly becomes \"closed\" to inserts of new logical rows, once it\n> > crosses a certain almost-empty space threshold.\n\n> I suspect that we'd get a *LOT* of complaints if we introduced that degree of\n> stickiness.\n\nMaybe. It would be very different to our current behavior, which would\nundoubtedly have many consequences. Maybe this will be a big problem,\nmaybe it barely matters. I make no specific claims about it, either\nway. Not just yet.\n\n> Why is that directly tied to FSM_CATEGORIES? ISTM that there's ways to benefit\n> from a fairly granular FSM_CATEGORIES, while still achieving better\n> locality. You could e.g. search for free space for an out-of-page update in\n> nearby pages with a lower free-percentage threshold, while having a different\n> threshold and selection criteria for placement of inserts.\n\nAgain, it's all about *systemic* effects. A FSM request is basically a\nchoice *among* blocks that could in principle satisfy the request --\noften the number of basically-satisfactory blocks is huge (way too\nlarge, even). You have to bear in mind that concurrent requests are in\ncompetition with each other in much of the time. They are usually all\nlooking for exactly the same thing (e.g., same free space\nrequirement), or close to the same thing -- tuples within a given\ntable tend to all be about as wide as each other.\n\nI can clearly sometimes see very high contention cases, where backends\ndo way too much spinning inside the RelationGetBufferForTuple() loop.\nThey're all more or less chasing the same scraps of free space, in a\nhighly inefficient way. Even though there is probably an abundance of\nfree space. Right now the heap pages that have the most free space are\nalso the ones that are least likely to be used.\n\nThough I think that these backends should cooperate more, some amount\nof competition is probably necessary. If FSM_CATEGORIES used 3 bits\ninstead of 8, then the backends could fall back on caring about some\nother thing that distinguished heap pages from each other that\nactually matters. Leading to less contention, and maybe better space\nutilization.\n\nI have presented this FSM_CATEGORIES contention issue as a distinct\nproblem to the first one (the locality problem), though honestly that\nwas a bit arbitrary -- it's just blurry. Thank you for putting up with\nthat.\n\n> The density of the VM is fairly crucial for efficient IOS, so I'm doubtful\n> merging FSM and VM is a good direction to go to. Additionally we need to make\n> sure that the VM is accurately durable, which isn't the case for the FSM\n> (which I think we should use to maintain it more accurately).\n\nI explained this part badly. I don't think that we should literally\nunite the VM and FSM data structures. I was really just pointing out\nthat a logical-ish notion of a page being full (to use the term of art\nI've seen, a \"closed\" page) is almost the same thing as a page that is\nmarked all-visible/all-frozen. Presumably VACUUM does that with the\noptimistic assumption that it will probably never again need to touch\nthe same page. And while that can never be guaranteed, it certainly\nseems like we might want to weigh things in favor of that happening.\n\nI'm pretty sure that carelessly remembering 200 bytes of free space in\nthe FSM for an all-frozen page is practically guaranteed to be a bad\nidea. While I don't have a great idea of where the break-even point is\njust yet, I am prepared to say that I'm sure that it's not 0 bytes,\nwhich is how it works today. A squishy logical definition of \"page is\nfull\" seems pretty natural to me.\n\n> But perhaps I'm just missing something here. What is the strong interlink\n> between FSM and all-frozen/all-visible you see on the side of VACUUM? ISTM\n> that the main linkage is on the side of inserts/update that choose a target\n> page from the FSM. Isn't it better to make that side smarter?\n\nI'll respond to Robert about this separately.\n\n> To me this seems like it'd be better addressed by a shared, per-relfilenode,\n> in-memory datastructure. Thomas Munro has been working on keeping accurate\n> per-relfilenode relation size information. ISTM that that that'd be a better\n> place to hook in for this.\n\nActually, that's the approach that I'm taking in my current\nprototyping. I would like to have a WAL-logged component to this as\nwell, but I haven't got that far.\n\nI think that it's possible that I'll eventually conclude that the\nwhole idea of a FSM is just the wrong idea. Remembering anything at\nall about most pages may just be unnecessary in a world where we fix\neverything. Maybe the end result is that the common case is that most\nindividual heap pages are \"closed\". Perhaps that can just be implicit\n-- there is no information to remember.\n\n> > would be quite natural for the leader backend to say to each individual\n> > follower backend: thank you for waiting for me, here is a big contiguous\n> > range of heap pages (e.g., as many as 50 heap pages or more per xact when\n> > things truly ramp up), which should be enough to allow you to avoid going to\n> > the FSM again for quite a long time.\n>\n> That'd end up badly if we did for a relation that's hotly inserted into by a\n> lot of connections, but where each connection only inserts a few rows. I\n> suspect we'd either need information from the inserting backends about the\n> number of pages they're likely going to need (e.g. a smarter \"extension queue\"\n> where each entry lists the number of pages requested) and/or stats about the\n> number of consecutive insertions a relation typically gets.\n\nThat's a part of it, certainly. The heuristics would mostly be driven\nby recent information. In particular, we would probably only ramp\nthings up based on a clear observed failure to keep up with demand. We\ncould be very aggressive indeed this way, without too much extra risk.\nWe'd only ramp up because we *knew* that the most recent batch/set of\nfree lists for the last bulk request was inadequate.\n\nFor that you need the context, the recent history.\n\n> > But the leader backend doesn't do that at all -- it just puts all of\n> > the pages (up to 512 total) in the FSM. All of the waiting follower\n> > backends are left to senselessly fight it out for free space by simply\n> > going back to the FSM when they wake up again. Why can't they\n> > cooperate intelligently? What stops that today?\n>\n> The lack of suitable in-memory coordination facilities.\n>\n> It turns out that I looked a bunch at this area because of AIO + DIO: With DIO\n> the typical linux filesystems (ext4, xfs) do not perform any delayed\n> allocation, which means that the non-bulk extension leads to *horrible*\n> filesystem fragmentation.\n\nIt's the coordination facilities -- agreed. The only way that I seem\nto be going further than what you've said here is the logical database\nstuff. That is, I intend to specifically involve metadata like XIDs,\nas well as a general understanding of things like commit/abort\nboundaries for said XIDs. Ownership of a free space lease shouldn't be\nstrictly tied to an XID, but that seems like a good starting point to\nme. This is the kind of thing that an OS engineer would never think\nof, that other database systems seem to do a lot of.\n\nThis design involving waiting on XIDs could also be reused for nbtree\npage deletion, where page recycling is deferred (same with GiST page\ndeletion). We could model this problem as: the\nphysically-deleted-by-VACUUM page's safexid value should be treated as\n\"the maybe-still-ongoing transaction that owns this page\". This is\nkind of a lie, but close enough to the truth. That way we can put\nevery deleted page in the FSM/whatever immediately, while reusing the\nsame XID-wait stuff to solve the recycle safety problem.\n\nWe push the recycle safety stuff on to the consumer side this way.\nThis is currently a problem that mostly belongs to VACUUM itself (the\nproducer side) -- which makes zero sense. I think that the only reason\nwe do it that way is because the current FSM doesn't care at all about\nXID boundaries. It's almost the same problem, maybe even exactly the\nsame.\n\n> I addressed (or rather sidestepped) this to a small degree in the AIO+DIO\n> patchset, by making extension faster and doing a few improvements around\n> locking. But it's not good enough.\n>\n> If the relation extension infrastructure instead had information about the\n> number of blocks each waiter wants and we had Thomas' \"accurate shared\n> relation size\" infrastructure, we could do a lot better:\n\nSounds great to me!\n\n> 1) Whenever a backend needs new space and most of the previously bulk-extended\n> space is used opportunistically try to bulk-extend. In the happy path this\n> avoids the thundering herd issue because other backends can continue\n> inserting while extension is in progress.\n\nRight -- my thoughts exactly.\n\n> 2) Whenever bulk extending, release pages to individual backends by looking in\n> the queue of backends needing extension and wake up backends individually\n> whenever we've bulk extended sufficiently for that backend.\n\nThis is also exactly what I was thinking of, albeit for slightly\ndifferent reasons.\n\nI want to more or less say directly to each backend at the point it\nwakes up: here you go, here are those pages you asked for. Somebody\nmight check in about this free space lease later on, but in general\nyou can think of these pages as your exclusive property.\n\nMaking it backend/XID specific is probably helpful in many ways. Like\nmaybe there is a natural variation in demand among backends, even\nthough they're all bulk inserting into the same table. Who knows?\n\n> I think the fundamental issue of bulk extension issue is more that bulk\n> extension shouldn't actually get pages from the FSM at all. That's just an\n> ugly implementation detail of the hack we have currently, rather than\n> something that should live on.\n\nActually, I agree. I was just trying to use our existing terms to\nintroduce my ideas.\n\n> We may want to decide to continue inserting\n> bulk extended pages into the FSM to handle edge cases of backends erroring out\n> before space is used, but the happy path should not touch the FSM at all.\n\nYou don't have to touch the FSM if you don't even have one in the\nfirst place. :-)\n\n> It sounds like you're thinking of using some global history, or at least a\n> backend local history? I think it might be better to have backend local,\n> per-command state. E.g. for a COPY aggressively increase the amount of space\n> reserved, but not for a single-row insert.\n\nThat seems quite possible. Not sure just yet.\n\nThis feels like the right general idea to me, even though many of the\ndetails are not worked out.\n\n> I guess it depends on what you define as recent, but I don't see a way to\n> bound the timeframe usefully. We need to deal with cases where table sizes go\n> up and down over time, e.g. because there's periodic batch activity and\n> ongoing activity. What's the time bound for unused space somewhere in a\n> relation? I don't see any, unless we add compaction logic to vacuum.\n\nI don't want to bound the timeframe, exactly. I want to look at what\nhappened during the last bulk operation, and compare that to what I\nsee for the current/ongoing operation -- which could involve a fair\namount of details. The idea is to make decisions based on inferences\nabout what is *changing*. What's working, what's not working -- the\n*direction* of things is at least as important as the state of things\nat this exact point in time.\n\nThis does mean that you have to accept that some number of heap pages\ncan be \"leaked\" if inserts against a table that was being\nbulk-extended suddenly go away completely. Of course it should be\npossible to get this so-called leaked space back, just as soon as the\ntable receives more inserts (any inserts should do that). My current\nbest guess is that this will work fine in practice.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Tue, 17 Aug 2021 15:11:11 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Tue, Aug 17, 2021 at 9:48 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> I don't know what the right degree of stickiness is, but I can easily\n> believe that we want to have more than none. Part of Peter's point, at\n> least as I understand it, is that if a page has 100 tuples and you\n> delete 1 or 2 or 3 of them, it is not smart to fill up the space thus\n> created with 1 or 2 or 3 new tuples. You should instead hope that\n> space will optimize future HOT updates, or else wait for the page to\n> lose some larger number of tuples and then fill up all the space at\n> the same time with tuples that are, hopefully, related to each other\n> in some useful way.\n\nThat is a big part of it. But it gets worse than that. It is truly\ninsidious, once you follow the chain of problems over time -- maybe\nover hours and hours. BenchmarkSQL makes this a lot easier.\n\nRight now when we set heap fill factor to 85 (which is what\nBenchmarkSQL does), we effectively have this chunk of special reserved\nfree space left behind on each page. The remaining 15% of tuple space\nis of course reserved for successor versions of the same logical rows\n-- those rows from the time that the page first fills (presumably they\nall come from straight inserts). That's our starting point -- simple\nenough.\n\nThe approach we take effectively gives up on the *whole entire page*\nat literally the first sign of trouble -- the first time we fail to\nhold a successor version on that same page. Even though it just well\nhave been a once-off perturbation. What we might call bad luck, as\nopposed to an inevitability. For example, maybe ANALYZE ran that\nsecond, which made the crucial difference for that one heap page that\none time. That's kind of enough to make the implementation assume all\nbets are off, for the entire page -- it's as if we pessimistically\nassume that there is no chance of keeping anything like the original\nrows on the heap page, so we might as well let it all get mixed up\neven more. This is way too pessimistic -- it's black and white\nthinking.\n\nWhile in general that level of pessimism might turn out to be\njustified (anything is possible), we should hold the line and find out\nfor sure how bad it is. I happen to know that our problematic\nBenchmarkSQL/TPC-C tables just don't have any skew, so this pessimism\nis particularly wrong-headed there.\n\nBear in mind that the new unrelated tuples that ultimately replace our\noriginal couldn't-fit tuples (probably after the next VACUUM) are\nprobably not \"average tuples\". Maybe they're newly inserted tuples,\nwhich is bad in the BenchmarkSQL case, because they're all\n*guaranteed* to be updated in the future (owing to the details of the\nworkload). With some other typical workload they might often be\nsuccessor versions from updates instead -- most likely for rows that\nare disproportionately likely to be updated many times. It's truly\npernicious.\n\nIf we only accepted the original row migration, and didn't throw good\nmoney after bad, then the cycle would be broken. To me this is a bit\nlike certain heuristic algorithms, where you technically accept a\nsuboptimal outcome to avoid getting stuck in a local maxima.\n\n> Now what's the threshold? 20 out of 100? 50? 80?\n\nI'm not going to pretend to know the answer. But I will point out that\none DB system whose heap fill factor defaults to 90 seems to have a\nsymmetric setting for the \"open up page again\" point -- the default\nfor that is 40. Not sure that that really matters to us, but that does\nseem pretty low to me. It's very sticky indeed.\n\n> Yeah, I don't think that reducing FSM_CATEGORIES is likely to have\n> much value for its own sake. But it might be useful as a way of\n> accomplishing some other goal. For example if we decided that we need\n> a bit per page to track \"open\" vs. \"closed\" status or something of\n> that sort, I don't think we'd lose much by having fewer categories.\n\nThis is probably one of my less important points. I addressed this\npoint in my remarks on this to Andres from earlier.\n\n> I don't have a well-formed opinion on this point yet. I am also\n> skeptical of the idea of merging the FSM and VM, because it seems to\n> me that which pages are all-visible and which pages are full are two\n> different things.\n\nAs I clarified in my email to Andres, this was just a bad choice of\nwords. I meant that they're at least conceptually much closer,\nprovided you're willing to accept my general view of things.\n\n> However, there's something to Peter's point too. An\n> empty page is all-visible but still valid as an insertion target, but\n> this is not as much of a contradiction to the idea of merging them as\n> it might seem, because marking the empty page as all-visible is not\n> nearly as useful as marking a full page all-visible. An index-only\n> scan can't care about the all-visible status of a page that doesn't\n> contain any tuples, and we're also likely to make the page non-empty\n> in the near future, in which case the work we did to set the\n> all-visible bit and log the change was wasted. The only thing we're\n> accomplishing by making the page all-visible is letting VACUUM skip\n> it, which will work out to a win if it stays empty for multiple VACUUM\n> cycles, but not otherwise.\n\nThat's a big part of it. The other thing is systemic effects, which is\nrelated to the part of this email above about chain of events. I'll\ntalk about that some more now.\n\nLets say that VACUUM puts a non-zero usable amount of free space in\nthe FSM for a page that it marks all-visible/all-frozen at the same\ntime -- this is possible today, of course. To me this seems\ncontradictory, at least when there isn't much space -- which I believe\nis common. It's at least a minor waste to set the VM bit.\n\nNow let's say we change VACUUM to not waste effort on setting the heap\npage -- we're now avoiding minor waste, which is an okay goal. But\nwe're also doing something else, that I find very objectionable: we're\neffectively betting that the situation will improve for the same page\nat some point in the future, during a future VACUUM. It is possible\nthat we could get just one or two inserts on the same page, and then\nsee it again, and then we're done. If that happens, we win our bet.\nOtherwise, we lose our bet.\n\nHere's the problem with making that bet: it's typically an awful bet.\nThe potential upside is clearly pretty low. And more importantly,\nthere is a decent chance that we'll actually get some row that is\ngoing to mess everything up -- not an \"average row\" (whatever that may\nmean). Again, very frequently updated rows are often what'll end up on\nthe page, which are enough to make the page never have its all-visible\nbit set.\n\nHere is why I find this *extremely* objectionable: we *actually* risk\nexperiencing a downside for the heap page by taking this awful bet\n*many many times* in the future -- it's not just a once-off downside,\nI believe. This is not in fact a choice about one heap page on one\noccasion -- it is actually a *policy* affecting the page again and\nagain (and every other heap page too). It is only by making a\nnot-quite-physically-full page \"closed\" in the way that I advocate we\navoid taking this awful bet -- that is how it's possible to artificially *make*\nthis a question about one page on one occasion. We're bounding the\ndownside, lessening our exposure to the worst case. Intuitively, I\nthink that the possible downside is essentially unlimited, if we\nassume systemic destabilization risks (which seems wise). Whereas the\npossible upside of taking that awful bet is clearly, measurably small.\nA once-off upside. Peanuts, really.\n\n(Of course my argument won't work if you assume that even with the\n\"closed\" page choice we naturally get more updates to one of the aged\nfrozen rows anyway. But we're counting on that not happening in either\nscenario/with *either* strategy, so I don't think that it invalidates\nanything I've said.)\n\n> Conceptually, you might think of the merged data structure as a\n> \"quiescence map.\" Pages that aren't being actively updated are\n> probably all-visible and are probably not great insertion targets.\n> Those that are being actively updated are probably not all-visible and\n> have better chances of being good insertion targets. However, there\n> are a lot of gremlins buried in the word \"probably.\" A page could get\n> full but still not be all-visible for a long time, due to long-running\n> transactions, and it doesn't seem likely to me that we can just ignore\n> that possibility.\n\nI think that we should opportunistically be setting the all-frozen bit\nin heap pages (and freezing tuples earlier than required) anyway. For\nexample, we could notice that a whole heap page is eligible to be\nmarked all-frozen, and freeze the tuples early -- we could restart\nprocessing of the page once we realized that freezing early is a good\nidea.\n\nWhy even have a distinct all-visible VM bit? The per-tuple overhead of\nthe WAL records for freezing are kind of bulky, but that could be\nfixed. It's not a good reason. (Of course I'm not arguing that we\nshould break pg_upgrade, just that there is no reason not to freeze\nearly when it's cheap to do so in passing.)\n\n> +1. I had this same thought reading Peter's email. I'm not sure if it\n> makes sense to hook that into Thomas's work, but I think it makes a\n> ton of sense to use shared memory to coordinate transient state like\n> \"hey, right now I'm inserting into this block, you guys leave it\n> alone\" while using the disk for durable state like \"here's how much\n> space this block has left.\"\n\nI agree that that's the best starting point for this.\n\n--\nPeter Geoghegan\n\n\n", "msg_date": "Tue, 17 Aug 2021 17:31:08 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Tue, Aug 17, 2021 at 11:24 AM Bruce Momjian <bruce@momjian.us> wrote:\n> OK, I am trying to think of something simple we could test to see the\n> benefit, with few downsides. I assume the case you are considering is\n> that you have a 10 8k-page table, and one page is 80% full and the\n> others are 81% full, and if several backends start adding rows at the\n> same time, they will all choose the 80%-full page.\n\nThat's one problem (there is so many). They start with that same page,\nand then fight each other over other pages again and again. This\nemergent behavior is a consequence of the heuristic that has the FSM\nlook for the heap page with the least space that still satisfies a\ngiven request. I mentioned this problem earlier.\n\n> For example:\n>\n> 1. page with most freespace is 95% free\n> 2. pages 2,4,6,8,10 have between 86%-95% free\n> 3. five pages\n> 4. proc id 14293 % 5 = 3 so use the third page from #2, page 6\n\nRight now my main concern is giving backends/XIDs their own space, in\nbulk. Mostly for concurrent bulk inserts, just so we can say that\nwe're getting the easy cases right -- that is a good starting point\nfor my prototype to target, I think. But I am also thinking about\nstuff like this, as one way to address contention.\n\n> This should spread out page usage to be more even, but still favor pages\n> with more freespace. Yes, this is simplistic, but it would seem to have\n> few downsides and I would be interested to see how much it helps.\n\nI thought about having whole free lists that were owned by XIDs, as\nwell as shared free lists that are determined by hashing MyProcPid --\nor something like that. So I agree that it might very well make\nsense.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Tue, 17 Aug 2021 18:32:24 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Tue, Aug 17, 2021 at 12:11 PM John Naylor\n<john.naylor@enterprisedb.com> wrote:\n> I'm not sure it's essential to have \"far\" fewer categories, if the closed-to-open transition is made less granular through some other mechanism.\n\nSee my remarks to Andres about FSM_CATEGORIES from earlier. (It may\nnot matter if you don't believe that it helps us to have such high\ngranularity -- that means it won't hurt to get rid of it, which might\nbe a good enough reason on its own.)\n\n> > I now wonder if the FSM is fundamentally doing the wrong thing by\n> > keeping track of all \"free space\" in every page over time. Why\n> > wouldn't we just have a free space management strategy that is\n> > generally only concerned with recent events?\n\n> The second paragraph here is an interesting idea and makes a great deal of sense. It would lead to smaller FSMs that are navigated more quickly and locked for shorter durations.\n\nMost importantly, the FSM/whatever doesn't have to be locked at all if\nyou don't go to it. And so going to the FSM much less often with space\nleases or whatever seems like it might be a big win for that reason\n(not just the locality stuff that I care about).\n\n> Implicit \"closure\" seems riskier in my view if you want to bring VM qualities into it, however.\n\nI didn't mean to imply that we'd be changing that data structure. As I\nclarified earlier, \"merging the FSM and the VM\" was meant in a\nconceptual way. Not the best choice of words on my part.\n\n> This makes sense as well. Shared memory for more recent / highly contended state, and disk for less recent / less contended / stickier state.\n\nI would like to also make it WAL-logged, which is easier this way.\nThat isn't my main goal, but why not do it? The way that the FSM works\nright now within VACUUM REDO routines is a problem.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Tue, 17 Aug 2021 18:39:09 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Tue, Aug 17, 2021 at 6:11 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> Again, it's all about *systemic* effects. A FSM request is basically a\n> choice *among* blocks that could in principle satisfy the request --\n> often the number of basically-satisfactory blocks is huge (way too\n> large, even). You have to bear in mind that concurrent requests are in\n> competition with each other in much of the time. They are usually all\n> looking for exactly the same thing (e.g., same free space\n> requirement), or close to the same thing -- tuples within a given\n> table tend to all be about as wide as each other.\n>\n> I can clearly sometimes see very high contention cases, where backends\n> do way too much spinning inside the RelationGetBufferForTuple() loop.\n> They're all more or less chasing the same scraps of free space, in a\n> highly inefficient way. Even though there is probably an abundance of\n> free space. Right now the heap pages that have the most free space are\n> also the ones that are least likely to be used.\n>\n> Though I think that these backends should cooperate more, some amount\n> of competition is probably necessary. If FSM_CATEGORIES used 3 bits\n> instead of 8, then the backends could fall back on caring about some\n> other thing that distinguished heap pages from each other that\n> actually matters. Leading to less contention, and maybe better space\n> utilization.\n\nTo me, it feels like the real issue here is that the free space map is\ncompletely deterministic. As it's currently designed, you can reduce\nthe number of bits as much as you want, and it doesn't change\nanything. Concurrent requests get the same answer, which is not what\nwe want. Just as a thought experiment, imagine that backends\npreferentially prefer pages whose block numbers are congruent to their\nPID module some integer. Now you have a reason - perhaps not the best\npossible reason, but *a* reason - for every single backend to pounce\non the same target page.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 18 Aug 2021 10:36:20 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Tue, Aug 17, 2021 at 8:31 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> Lets say that VACUUM puts a non-zero usable amount of free space in\n> the FSM for a page that it marks all-visible/all-frozen at the same\n> time -- this is possible today, of course. To me this seems\n> contradictory, at least when there isn't much space -- which I believe\n> is common. It's at least a minor waste to set the VM bit.\n\nIt seems to me that you are talking about the VM bit but making an\nargument that is more applicable to the FSM. If we think that the\nsmall amount of freespace in the page is going to result in the page\nbeing dirtied repeatedly as it cycles through a bunch of different\ntuples none of which stick around long term, then we might not want to\nadvertise the freespace in the FSM, or we might want the FSM to\ndisregard the fact that a small amount of freespace is present there.\nHowever, if we do that, then we certainly want to also set the VM bit.\nOtherwise, we've got a page that we've effectively quiesced, by\nrefusing to reuse the freespace, but the VM doesn't know that, so\nfuture index-only scans and VACUUM operations are penalized.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 18 Aug 2021 10:45:08 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Wed, Aug 18, 2021 at 7:36 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > Though I think that these backends should cooperate more, some amount\n> > of competition is probably necessary. If FSM_CATEGORIES used 3 bits\n> > instead of 8, then the backends could fall back on caring about some\n> > other thing that distinguished heap pages from each other that\n> > actually matters. Leading to less contention, and maybe better space\n> > utilization.\n>\n> To me, it feels like the real issue here is that the free space map is\n> completely deterministic.\n\nI agree. Though note the separate problem with FSM_CATEGORIES that I\nmentioned to Andres: if you want to maintain the FSM value for pages\neagerly within backends, then practically speaking a far lower\nFSM_CATEGORIES-like constant seems necessary.\n\nI'm really just saying that the fine granularity seems to me to be\nbasically the wrong approach. In general the single most important\nthing is the amount of free space available -- we agree on that.\nHowever, the only reason to remember very small *differences* in free\nspace between heap pages is because you intend to do *something* with\nthat extra information. But caring about noise-level differences seems\ninherently bad -- there is bound to be a better fall-back behavior\nthat reduces contention, and actually *increases* space utilization in\npractice (even though theoretically coarser-grained information might\nhurt utilization a little).\n\n> As it's currently designed, you can reduce\n> the number of bits as much as you want, and it doesn't change\n> anything. Concurrent requests get the same answer, which is not what\n> we want.\n\nI agree that reducing FSM_CATEGORIES alone will not buy us anything.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Wed, 18 Aug 2021 09:27:57 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Wed, Aug 18, 2021 at 7:45 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> On Tue, Aug 17, 2021 at 8:31 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> > Lets say that VACUUM puts a non-zero usable amount of free space in\n> > the FSM for a page that it marks all-visible/all-frozen at the same\n> > time -- this is possible today, of course. To me this seems\n> > contradictory, at least when there isn't much space -- which I believe\n> > is common. It's at least a minor waste to set the VM bit.\n>\n> It seems to me that you are talking about the VM bit but making an\n> argument that is more applicable to the FSM. If we think that the\n> small amount of freespace in the page is going to result in the page\n> being dirtied repeatedly as it cycles through a bunch of different\n> tuples none of which stick around long term, then we might not want to\n> advertise the freespace in the FSM, or we might want the FSM to\n> disregard the fact that a small amount of freespace is present there.\n\nI'm not quite sure if my argument applies to the VM or the FSM. It's a\nbit tricky to talk about because I'm imagining a world in which the\nconcepts have shifted. And because the exact details of the data\nstructures are less clear (even if they were clear to me, the lack of\na shared vocabulary might confuse our discussion).\n\nMaybe there isn't even a conventional FSM in this new world. Maybe\nfree space management works by focusing on recent events, and on\noutcomes. This means that we store much less information about the\nentire database, and much more information about very recent events.\nIn particular, I hope that free space management won't have to care\nabout how much free space most individual heap pages have. Perhaps\nmost heap pages are simply \"closed\", unavailable for reuse.\n\n> However, if we do that, then we certainly want to also set the VM bit.\n> Otherwise, we've got a page that we've effectively quiesced, by\n> refusing to reuse the freespace, but the VM doesn't know that, so\n> future index-only scans and VACUUM operations are penalized.\n\nI agree that if we do that we'd want to also set the VM bit.\n\nI'm imagining a world in which a \"closed page\" is synonymous with an\nall-visible/all-frozen page. That doesn't mean that they're exactly\nthe same thing. For example, maybe a closed page is a page that is at\nleast *expected* to have its all-visible/all-frozen set by VACUUM the\nnext time it runs -- though more often it'll have been set already.\n\nIf you're looking at the system in real time with this improved\ndesign, you'll see that pages that become closed will then also have\ntheir VM bit set on a predictable timeline. Maybe we even set the VM\nbit when some of the closed page's closed rows happen to be updated\n(Freeze cutoff permitting) -- there isn't that much downside to VACUUM\nbetting that these \"closed row updates\" will be the last such updates\nforever, or at least for a long time. This should at least be the case\nonce we add an optimized approach to freezing whole pages (pages whose\ntuples start out unfrozen).\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Wed, 18 Aug 2021 10:04:49 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Tue, Aug 17, 2021 at 5:31 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> > Now what's the threshold? 20 out of 100? 50? 80?\n>\n> I'm not going to pretend to know the answer. But I will point out that\n> one DB system whose heap fill factor defaults to 90 seems to have a\n> symmetric setting for the \"open up page again\" point -- the default\n> for that is 40. Not sure that that really matters to us, but that does\n> seem pretty low to me. It's very sticky indeed.\n\nCorrection: it's actually 60, not 40.\n\nIt's true that the actual default is 40, but it works the other way\naround relative to Postgres (as does the related fill factor like\nsetting, which defaults to 90 instead of 100). And so we would think\nof this other \"open up closed page once again\" setting as having a\ndefault of 60. (Or perhaps we'd think of it as having a default that\nis 2/3 of the closely related fill factor setting's default.)\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Wed, 18 Aug 2021 12:58:27 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Wed, Aug 18, 2021 at 3:58 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> On Tue, Aug 17, 2021 at 5:31 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> > > Now what's the threshold? 20 out of 100? 50? 80?\n> >\n> > I'm not going to pretend to know the answer. But I will point out that\n> > one DB system whose heap fill factor defaults to 90 seems to have a\n> > symmetric setting for the \"open up page again\" point -- the default\n> > for that is 40. Not sure that that really matters to us, but that does\n> > seem pretty low to me. It's very sticky indeed.\n>\n> Correction: it's actually 60, not 40.\n>\n> It's true that the actual default is 40, but it works the other way\n> around relative to Postgres (as does the related fill factor like\n> setting, which defaults to 90 instead of 100). And so we would think\n> of this other \"open up closed page once again\" setting as having a\n> default of 60. (Or perhaps we'd think of it as having a default that\n> is 2/3 of the closely related fill factor setting's default.)\n\nI don't know whether 60 is optimal or not, but it doesn't seem crazy.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 20 Aug 2021 10:32:48 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Wed, Aug 18, 2021 at 1:05 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> Maybe there isn't even a conventional FSM in this new world. Maybe\n> free space management works by focusing on recent events, and on\n> outcomes. This means that we store much less information about the\n> entire database, and much more information about very recent events.\n> In particular, I hope that free space management won't have to care\n> about how much free space most individual heap pages have. Perhaps\n> most heap pages are simply \"closed\", unavailable for reuse.\n\nI very much doubt that you can get away without some sort of free\nspace map. Even if in most cases most pages are closed to insertions,\nthere will be important corner cases where lots of pages are open for\ninsertions, like when you just deleted a ton of rows and then ran\nVACUUM. And we cannot lose track of even one of those open pages or,\nif the pre-8.4 state of the world is any indication, we will be super\nsad. I suppose technically it doesn't need to be a map; it could be\nstructured some other way. But it is going to have to be able to keep\ntrack of an arbitrary number of open pages without losing any, and a\nmap is one good way of doing that.\n\nRegarding the FSM_CATEGORIES question, I think the issue is big tuples\nvs. small tuples. You don't want to keep on finding pages with some\nfree space and then find out that they don't actually have enough for\nthe tuple you want to insert. Now that does become less of an issue\nwith this open/closed system because, at least initially, when a page\nis re-opened to inserts, more than a quarter of the page will be free\n(I presume) and so the details don't matter. But, as it gets closer to\nfilling up, it might matter again. Perhaps we don't want to waste time\nlooking through a bunch of pages with 1kB free when we're trying to\ninsert a 2kB tuple. We could close all those pages as we try them, to\nprevent repeating the same process over and over again, but maybe the\n2kB tuple we're now trying to insert is unusual, and most tuples are\n40 bytes. Then we look silly.\n\nOne idea might be to have a CLOSED state in the FSM and then a variety\nof OPEN states that are distinguished by amount of available free\nspace. For example, imagine something like CLOSED, OPEN (>2kb), OPEN\n(1.5-2kb), OPEN (1-1.5kB), OPEN (768-1023 byte), OPEN (512-767 bytes),\nOPEN (256-511 bytes), OPEN (128-255 bytes), OPEN (64-127 bytes), OPEN\n(<64 bytes). I think that would give us enough information to pack\nopen pages tightly full before having them become closed. I don't know\nif those are exactly the right boundaries, and 10 categories might be\nworse than 8 or 16, but I think it's likely correct to suppose that\n(a) we don't really care at all how much space is present in closed\npages, and (b) for open pages, exactitude is most important when the\namount of available space is small.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 20 Aug 2021 10:45:13 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Fri, Aug 20, 2021 at 7:32 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> I don't know whether 60 is optimal or not, but it doesn't seem crazy.\n\nUh, I had it right the first time. Only the fill factor setting is\n\"inverted relative to Postgres\". This other setting really does\ndefault to 40. So it's very low.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Fri, 20 Aug 2021 08:06:20 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Fri, Aug 20, 2021 at 11:06 AM Peter Geoghegan <pg@bowt.ie> wrote:\n> On Fri, Aug 20, 2021 at 7:32 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > I don't know whether 60 is optimal or not, but it doesn't seem crazy.\n>\n> Uh, I had it right the first time. Only the fill factor setting is\n> \"inverted relative to Postgres\". This other setting really does\n> default to 40. So it's very low.\n\nI expect they ran more than zero tests before selecting that value, so\nit's probably a decent choice in their system. However, that does seem\nrather low. I would have guessed that a good value would be in the\n50-80 percent range. It's hard to know, though, partly because\neverything is workload dependent, and partly because you're balancing\ntwo good things that are qualitatively different. A lower value\nfigures to reduce the degree of \"mixing\" of older and newer data\nwithin the same pages, but it also risks permanently wasting space\nthat could have been put to efficient use. Imagine a table that is\nwritten some number of times and then, all at once, you stop all\nwrites forever. You probably don't want to discover at that point in\ntime that you have a large number of pages that are not even close to\nfull, but you can't know when, if ever, such an event will happen for\nany given table.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 20 Aug 2021 11:34:23 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Fri, Aug 20, 2021 at 7:45 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> I very much doubt that you can get away without some sort of free\n> space map. Even if in most cases most pages are closed to insertions,\n> there will be important corner cases where lots of pages are open for\n> insertions, like when you just deleted a ton of rows and then ran\n> VACUUM. And we cannot lose track of even one of those open pages or,\n> if the pre-8.4 state of the world is any indication, we will be super\n> sad.\n\nI agree with all that. The point I was making is that this new FSM\ndesign will have an on-disk size that is \"a function of the workload\".\nThe new FSM can be required to store information about every single\npage, but that is the worst case. And a rather atypical case. I\nimagine that we'll find that the new FSM on-disk structure stores far\nless information than the current FSM in most cases, even though we're\noperating within the confines of what you've said.\n\nI think of this whole area as making heap pages a bit like B-Tree leaf\npages. TIDs are stable logical identifiers of rows (that happen to\nhave a physical component, a block number) in the other DB systems\nthat I have referenced -- the heap pages from these systems are\ntherefore intrinsically more like B-Tree leaf pages than those from\nPostgres heapam. ISTM that that's relevant to total space utilization.\nUsers with sparse deletion patterns in their heap structure will get\nlow space utilization -- an issue that we're familiar with as a\nproblem for B-Tree indexing.\n\nI don't think that having a smaller on-disk FSM should be a goal of\nthis project (though I suppose you could say that that aspect enables\nFSM WAL-logging, which would be nice). Smaller on-disk footprints seem\nlike a natural consequence of this whole direction -- that's all. I\nalso don't think that you're going to see huge space utilization\nbenefits. This project is mostly aimed at reducing fragmentation, and\nall of the many problems that stem from it.\n\n> I don't know\n> if those are exactly the right boundaries, and 10 categories might be\n> worse than 8 or 16, but I think it's likely correct to suppose that\n> (a) we don't really care at all how much space is present in closed\n> pages, and (b) for open pages, exactitude is most important when the\n> amount of available space is small.\n\nI really don't have a detailed opinion on the appropriate number of\ncategories just yet, except that it should be maybe 16 or 20 at the\nvery most -- only real testing is likely to help me to refine my\nthinking on that. Note that the paper \"Towards Effective and Efficient\nFree Space Management\" recommends logarithmic intervals (called\n\"buckets\"), with 15 total. Details are under \"4 Implementing Object\nPlacement\".\n\nI think that it's quite possible that the final scheme will not be a\nlinear scale. Plus we may have to account for fill factor settings.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Fri, 20 Aug 2021 08:48:40 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Fri, Aug 20, 2021 at 8:34 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> I expect they ran more than zero tests before selecting that value, so\n> it's probably a decent choice in their system. However, that does seem\n> rather low. I would have guessed that a good value would be in the\n> 50-80 percent range.\n\nThey don't have to deal with non-HOT updates, which effectively move\nthe row to another block. Actually, that's not quite true -- they do\nhave a concept called row migration. But it's the strategy of last\nresort, and is presumably very rare -- much rarer than a non-HOT\nupdate that moves a row.\n\nMy point is that it's easier to believe that you run into sparse\ndeletion patterns in a version of Postgres with open and closed heap\npages -- because it's not only deletes that you have to worry about.\n\n> It's hard to know, though, partly because\n> everything is workload dependent, and partly because you're balancing\n> two good things that are qualitatively different. A lower value\n> figures to reduce the degree of \"mixing\" of older and newer data\n> within the same pages, but it also risks permanently wasting space\n> that could have been put to efficient use.\n\nAll true -- to me this is all about adapting to workloads at a fine granularity.\n\nIf we have closed pages, then non-HOT updates that cannot keep the row\non the same heap page now actually \"relieve the pressure\", which is\nnot currently true. If we started out with a heap page that had 100\ntuples (say with fill factor 90), and then we find that we cannot keep\nthe entire page together...then maybe we'll have more luck with 99, or\njust 90, or even less. By firmly sticking with our original goal, then\nwe have some chance to learn what really will be stable for a given\nheap page. There is nothing wrong with learning that lesson through\ntrial and error, based on negative information from the workload.\n\nRight now we go ahead and reuse the space at the next opportunity (we\nparticularly favor pages like this, even). So we never learn from our\nmistakes.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Fri, 20 Aug 2021 09:00:36 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Fri, Aug 20, 2021 at 11:48 AM Peter Geoghegan <pg@bowt.ie> wrote:\n> On Fri, Aug 20, 2021 at 7:45 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > I very much doubt that you can get away without some sort of free\n> > space map. Even if in most cases most pages are closed to insertions,\n> > there will be important corner cases where lots of pages are open for\n> > insertions, like when you just deleted a ton of rows and then ran\n> > VACUUM. And we cannot lose track of even one of those open pages or,\n> > if the pre-8.4 state of the world is any indication, we will be super\n> > sad.\n>\n> I agree with all that. The point I was making is that this new FSM\n> design will have an on-disk size that is \"a function of the workload\".\n\nThat could be the right decision, but nothing said up to this point\nreally seems to suggest it. The open/closed distinction and the\nchanges in how to bin available space could all be done with the\npresent model.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 20 Aug 2021 12:03:36 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Fri, Aug 20, 2021 at 9:03 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> That could be the right decision, but nothing said up to this point\n> really seems to suggest it. The open/closed distinction and the\n> changes in how to bin available space could all be done with the\n> present model.\n\nI guess that's true. Isn't this just semantics, though?\n\nThe new FSM implementation certainly cannot forget about pages that it\ndeems open, or fail to have information about pages that should be\nconsidered open -- that would be absolutely unacceptable. And the\nimplementation cannot assume that it won't have to maintain\ninformation about every single heap page. All I'm saying is that in\npractice this will be very rare. Making the FSM structure smaller\nisn't really the goal, though.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Fri, 20 Aug 2021 09:16:58 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Fri, Aug 20, 2021 at 12:17 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> On Fri, Aug 20, 2021 at 9:03 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > That could be the right decision, but nothing said up to this point\n> > really seems to suggest it. The open/closed distinction and the\n> > changes in how to bin available space could all be done with the\n> > present model.\n>\n> I guess that's true. Isn't this just semantics, though?\n\nNot entirely. On one level, as long as we end up with an FSM\nimplementation that does good things, who cares how it works\ninternally? Well, the answer is, hackers care, and we're hackers, so\nit doesn't seem out of bounds to talk about thoughts and ideas around\nthat. My own opinion is that the multi-level implementation of the\ncurrent FSM is confusing and doesn't seem to do what we want, but the\nbasic idea of a direct-mapped data structure seems good to me. Life is\na lot simpler if you can update the status of your own page without\nhaving to do any complex calculation to figure out where that status\nis stored, let alone having to shuffle things around to make room to\ninsert your status. Now if you or someone else comes up with an\nabsolutely amazing new design that isn't direct-mapped and it's\nawesome, I'm not going to sit here and hold my breath; I like awesome\nas well as the next person. But if you or someone else said to me\n\"hey, Robert, I'm thinking of rewriting the FSM, what tips do you have\nfor maximizing the chances of success?\" I'd say \"well, you should try\nto make the replacement data structure as simple as it can be while\nstill having the other properties that you care about ... and in\nparticular I would suggest something that uses a fixed amount of state\nper heap page, because that seems much simpler to me.\" But nobody's\ngot to agree with that, and it doesn't have to be right. It's just\nwhat I think.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 20 Aug 2021 13:15:21 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Fri, Aug 20, 2021 at 10:15 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > I guess that's true. Isn't this just semantics, though?\n>\n> Not entirely. On one level, as long as we end up with an FSM\n> implementation that does good things, who cares how it works\n> internally?\n\n> I'd say \"well, you should try\n> to make the replacement data structure as simple as it can be while\n> still having the other properties that you care about ... and in\n> particular I would suggest something that uses a fixed amount of state\n> per heap page, because that seems much simpler to me.\" But nobody's\n> got to agree with that, and it doesn't have to be right. It's just\n> what I think.\n\nBut not storing information about a heap page implicitly means that\nthe page is closed. And so we effectively remember the state of every\nsingle heap page with the FSM design I am working on. Not storing any\ninformation in the data structure is just an optimization. In any case\nwe're obligated to have accurate information about all individual heap\npages.\n\nDoing it that way seems pretty natural to me, even though the overhead\nof maintaining the FSM data structure isn't a priority for me -- not\nat all. It might actually be easier to have that optimization than to\nnot have it. The starting point for the new FSM data structure is\nlists of blocks that are usable, that have free space. Whereas the\nstarting point for the existing FSM structure is every single extant\nheap page in the table -- it's strictly obligated to have explicit\ninformation about every single page (otherwise we get nasty smgr\nerrors). It's either a small difference or a big difference, depending\non how you think about it.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Fri, 20 Aug 2021 10:32:33 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Fri, Aug 20, 2021 at 10:32 AM Peter Geoghegan <pg@bowt.ie> wrote:\n> But not storing information about a heap page implicitly means that\n> the page is closed. And so we effectively remember the state of every\n> single heap page with the FSM design I am working on. Not storing any\n> information in the data structure is just an optimization.\n\n> Doing it that way seems pretty natural to me, even though the overhead\n> of maintaining the FSM data structure isn't a priority for me -- not\n> at all. It might actually be easier to have that optimization than to\n> not have it. The starting point for the new FSM data structure is\n> lists of blocks that are usable, that have free space.\n\nThere is one problem with what I've said here, which might be behind\nyour concern. That problem is: if a page being closed is treated as an\nimplicit thing, just from its absence in this new FSM structure, then\nwe need to tighten things up elsewhere. In particular, this code at\nthe end of RelationGetBufferForTuple() is now a problem:\n\n\"\"\"\n/*\n * Remember the new page as our target for future insertions.\n *\n * XXX should we enter the new page into the free space map immediately,\n * or just keep it for this backend's exclusive use in the short run\n * (until VACUUM sees it)? Seems to depend on whether you expect the\n * current backend to make more insertions or not, which is probably a\n * good bet most of the time. So for now, don't add it to FSM yet.\n */\nRelationSetTargetBlock(relation, BufferGetBlockNumber(buffer));\n\"\"\"\n\nNote that the relation bulk extension mechanism that you committed (in\ncommit 719c84c1be) will always allocate one more block, just for the\nleader backend (the backend that bulk extends for other backends) --\nwe don't tell the FSM about this same block, presumably because to do\nso would risk live lock inside the loop in the same function. We just\nassume that it's okay that the leader backend remembers this in its\nlocal relcache \"target block\".\n\nRight now it isn't so bad that we're kind of sloppy here, at least\nrelative to everything else. Although the leader backend may well\n\"leak\" the page before it has the opportunity to write very much to it\n(e.g., client disconnects), in the long run we should get that space\nback. At least we know that VACUUM will ultimately be able to find the\nspace again, and put it in the FSM for reuse. Since there is currently\nno question about \"closed vs open\" pages, there is no question about\nVACUUM/the FSM becoming confused about which state applies to which\npage in this scenario.\n\nIn short: yeah, this \"closed vs open\" page business more or less\nnecessitates tightening things up here. Though this new requirement\nseems to have always been a good idea. Just because we can lean on\nVACUUM like this (an option that other DB systems don't have) doesn't\nmean that we should do so.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Fri, 20 Aug 2021 12:12:47 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Fri, Aug 20, 2021 at 3:13 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> In short: yeah, this \"closed vs open\" page business more or less\n> necessitates tightening things up here. Though this new requirement\n> seems to have always been a good idea. Just because we can lean on\n> VACUUM like this (an option that other DB systems don't have) doesn't\n> mean that we should do so.\n\nThat's all true, but it's not what I was talking about.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 20 Aug 2021 15:20:16 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Fri, Aug 20, 2021 at 12:20 PM Robert Haas <robertmhaas@gmail.com> wrote:\n> On Fri, Aug 20, 2021 at 3:13 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> > In short: yeah, this \"closed vs open\" page business more or less\n> > necessitates tightening things up here. Though this new requirement\n> > seems to have always been a good idea. Just because we can lean on\n> > VACUUM like this (an option that other DB systems don't have) doesn't\n> > mean that we should do so.\n>\n> That's all true, but it's not what I was talking about.\n\nThen I am not sure that I have understood you fully. I would like to\nmake sure that I have the nuance of it. As long as we have the idea of\nopen vs closed pages then we cannot assume that we know that status\nfrom the page alone. Unless we're willing to go update the pages\nagain, and possibly dirty them again, which seems unappealing.\n\nMy concern here is really the data structure and its overall\ncomplexity. If there has to be an explicit state for every page on the\nFSM, then this new FSM needs to merge freelists that have been emptied\ninto that structure, and needs to handle the question of which\nstructure (map or free lists) is currently authoritative for a given\nheap page. That's a lot of complexity compared to just forgetting the\nfree lists that are known to be fully closed, which will probably be\nvery common. That can work a little like discarding old UNDO -- it can\nbe simple and cheap *because* it's largely logical and implicit at the\nlevel of the physical data structures.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Fri, 20 Aug 2021 12:40:08 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Fri, Aug 20, 2021 at 3:40 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> My concern here is really the data structure and its overall\n> complexity. If there has to be an explicit state for every page on the\n> FSM, then this new FSM needs to merge freelists that have been emptied\n> into that structure, and needs to handle the question of which\n> structure (map or free lists) is currently authoritative for a given\n> heap page. That's a lot of complexity compared to just forgetting the\n> free lists that are known to be fully closed, which will probably be\n> very common. That can work a little like discarding old UNDO -- it can\n> be simple and cheap *because* it's largely logical and implicit at the\n> level of the physical data structures.\n\nI don't think I understand the data structure that you have in mind\nwell enough to comment intelligently.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 20 Aug 2021 16:30:38 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Fri, Aug 20, 2021 at 1:30 PM Robert Haas <robertmhaas@gmail.com> wrote:\n> On Fri, Aug 20, 2021 at 3:40 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> > My concern here is really the data structure and its overall\n> > complexity.\n\n> I don't think I understand the data structure that you have in mind\n> well enough to comment intelligently.\n\nRight now my prototype has a centralized table in shared memory, with\na hash table. One entry per relation, generally multiple freelists per\nrelation. And with per-freelist metadata such as owner and original\nleader backend XID values. Plus of course the lists of free blocks\nthemselves. The prototype already clearly fixes the worst problems\nwith BenchmarkSQL, but that's only one of my goals. That's just the\nstarting point.\n\nI appreciate your input on this. And not just on the implementation\ndetails -- the actual requirements themselves are still in flux. This\nisn't so much a project to replace the FSM as it is a project that\nadds a new rich abstraction layer that goes between access methods and\nsmgr.c -- free space management is only one of the responsibilities.\n\nAccess methods like heapam can talk to the new abstraction layer,\nsometimes exploiting semantics from the logical database -- owning\ntransaction IDs for a given lease, things like that. The new\nabstraction may thereby help us when working on other problems,\nincluding problems in areas that might seem totally unrelated. That's\nthe big idea. Here are some (admittedly quite speculative) examples of\nplaces that the infrastructure could help with:\n\n* Parallel INSERT/COPY.\n\nI imagine parallel DML is hard because of coordination problems. With\nthe infrastructure I have in mind, a parallel DML implementation could\nrequest a large free space lease, and distribute blocks from that\nlease among parallel workers during execution, on demand. This\nnaturally avoids unnecessary buffer lock contention among concurrent\nwrites from the same transaction (but different workers).\n\nBut that's not all. I'm also thinking of things like LWLock/buffer\nlock deadlock avoidance -- issues of fundamental correctness. That\nstuff becomes easier, too. Individual parallel workers from a parallel\nINSERT could safely assume that the blocks that the parallel leader\ntells them about really is only going to be accessed by them, for as\nlong as the owning transaction is around (barring read-only access by\nVACUUM, things like that). There is simply no question of any other\nbackend/parallel worker thinking that it has the right to use the same\nblock before the transaction commits.\n\nThe transaction-scoped ownership semantics must be truly robust for\nthis to work at all, but that's a good idea anyway.\n\n* Truncate tables without a disruptive relation-level lock.\n\nAFAICT it isn't actually logically necessary to get a heavyweight\nrelation extension lock to truncate a relation during VACUUM. The only\nreason we need that right now is because it's really hard to nail down\nwhich backends might have a usable BlockNumber that they still expect\nto not point past the end of the physical relfilenode (or much worse,\npoint to new and logically unrelated data). Perhaps we can solve the\nunderlying problem using something like Lanin & Shasha's \"drain\ntechnique\", which is used inside nbtree for page deletion today.\n\nThe general idea is to defer the physical unlink/recycling until we\nknow for sure that any backends that might have had unsafe references\nhave gone away. This is a very broad technique.\n\n* Truncate-away empty heap table segments that happen to come before\nother segments that still have useful data.\n\n* Eager cleanup of aborted transactions by VACUUM (or some variation\nof VACUUM that just handles aborts).\n\nAgain, we're using information about the logical database to solve\nproblem with the physical database -- that information is what we seem\nto currently be missing in all these areas. That's really the central\nidea behind the new infrastructure.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Mon, 23 Aug 2021 14:54:51 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Mon, Aug 23, 2021 at 5:55 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> Right now my prototype has a centralized table in shared memory, with\n> a hash table. One entry per relation, generally multiple freelists per\n> relation. And with per-freelist metadata such as owner and original\n> leader backend XID values. Plus of course the lists of free blocks\n> themselves. The prototype already clearly fixes the worst problems\n> with BenchmarkSQL, but that's only one of my goals. That's just the\n> starting point.\n>\n> I appreciate your input on this. And not just on the implementation\n> details -- the actual requirements themselves are still in flux. This\n> isn't so much a project to replace the FSM as it is a project that\n> adds a new rich abstraction layer that goes between access methods and\n> smgr.c -- free space management is only one of the responsibilities.\n\nMakes sense. I think one of the big implementation challenges here is\ncoping with the scenario where there's not enough shared memory\navailable ... or else somehow making that impossible without reserving\nan unreasonable amount of shared memory. If you allowed space for\nevery buffer to belong to a different relation and have the maximum\nnumber of leases and whatever, you'd probably have no possibility of\nOOM, but you'd probably be pre-reserving too much memory. I also think\nthere are some implementation challenges around locking. You probably\nneed some, because the data structure is shared, but because it's\ncomplex, it's not easy to create locking that allows for good\nconcurrency. Or so I think.\n\nAndres has been working -- I think for years now -- on replacing the\nbuffer mapping table with a radix tree of some kind. That strikes me\nas very similar to what you're doing here. The per-relation data can\nthen include not only the kind of stuff you're talking about but very\nfundamental things like how long it is and where its buffers are in\nthe buffer pool. Hopefully we don't end up with dueling patches.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 25 Aug 2021 13:58:41 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Wed, Aug 25, 2021 at 10:58 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> Makes sense.\n\nI'm glad that the big picture stuff makes sense to you.\n\n> I think one of the big implementation challenges here is\n> coping with the scenario where there's not enough shared memory\n> available ... or else somehow making that impossible without reserving\n> an unreasonable amount of shared memory.\n\nYes, it'll definitely be necessary to nail that down.\n\n> If you allowed space for\n> every buffer to belong to a different relation and have the maximum\n> number of leases and whatever, you'd probably have no possibility of\n> OOM, but you'd probably be pre-reserving too much memory.\n\nI hope that we can control the shared memory space overhead by making\nit a function of max_connections, plus some configurable number of\nrelations that get modified within a single transaction. This approach\nmust behave in the same way when when the number of tables that each\ntransaction actually modifies is high -- perhaps a transaction that\ndoes this then pays a penalty in WAL logging within the FSM. I think\nthat that can be made manageable, especially if we can pretty much\nimpose the cost directly on those transactions that need to modify\nlots of relations all at once. (If we can reuse the shared memory over\ntime it'll help too.)\n\n> I also think\n> there are some implementation challenges around locking.\n\nThat seems likely.\n\n> You probably\n> need some, because the data structure is shared, but because it's\n> complex, it's not easy to create locking that allows for good\n> concurrency. Or so I think.\n\nMy hope is that this design more than makes up for it by relieving\ncontention in other areas. Like buffer lock contention, or relation\nextension lock contention.\n\n> Andres has been working -- I think for years now -- on replacing the\n> buffer mapping table with a radix tree of some kind. That strikes me\n> as very similar to what you're doing here. The per-relation data can\n> then include not only the kind of stuff you're talking about but very\n> fundamental things like how long it is and where its buffers are in\n> the buffer pool. Hopefully we don't end up with dueling patches.\n\nI agree that there is definitely some overlap. I see no risk of a real\nconflict, though. I have mostly been approaching this project as an\neffort to fix the locality problems, mostly by looking for fixes to\nthe BenchmarkSQL workload's problems. I have to admit that the big\npicture stuff about exploiting transactional semantics with free space\nmanagement is still pretty aspirational. The resource management parts\nof my prototype patch are by far the kludgiest parts.\n\nI hope that I can benefit from whatever work Andres has already done\non this, particularly when it comes to managing per-relation metadata\nin shared memory.\n\n--\nPeter Geoghegan\n\n\n", "msg_date": "Thu, 26 Aug 2021 16:37:08 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Mon, Aug 16, 2021 at 5:15 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> This is actually quite simple -- the chaos that follows is where it\n> gets truly complicated (and not necessarily worth getting into just\n> yet). The update of a given order and its order lines entries takes\n> place hours later, within a delivery transaction.\n\nUpdate on this: aborted transactions play an important role in the\nchaos that we see with BenchmarkSQL/TPC-C.\n\nThis is surprising, in one way. Only 1% of all transactions are\naborted (per the TPC-C spec). But in another way it's not surprising.\nIt's totally consistent with what I've been saying about open and\nclosed pages. When a page that's initially allocated and opened by a\nbackend becomes closed following some inserts, the page should be left\nin a more or less pristine state -- owning backends that open and\nclose pages need to be \"good citizens.\n\nThe definition of \"pristine\" must also include \"no already-aborted\ntuples\" -- aborted xact tuples are a problem that we can and should\nnip in the bud. This is really an extension of what I've been saying\nabout not disrupting naturally occuring temporal and spatial locality.\nWe're far better off if the space reused by freeing aborted heap\ntuples is reused by the very next transaction running in the very same\nbackend. Plus it's not that hard; we can know for sure that this space\nis immediately available, which is not generally true of pruning. And\nso this free space from aborted xact tuples is quite special.\n\nEven with the master branch the problems with the FSM are much less\nnoticeable once you configure BenchmarkSQL to not abort any\ntransactions [1]. You need to consider the whole picture to understand\nhow the issue of aborted transactions has such an outsized negative\nimpact on performance and space efficiency.\n\nIt's a whole *chain* of events:\n\n* If just 1% of all transactions abort, that's enough to leave an\naverage of about 1 aborted tuple on every \"order\" table page (which\nnaturally has small heap tuples [2]), and about 10 on a minority of\nthe really big \"new order\" table's pages. Maybe 1 in 10 or 12 \"order\nline\" table heap pages are affected in this way.\n\n* The overall impact is that small (but not tiny) pockets of free\nspace are left randomly strewn all over the place. Not just LP_DEAD\nline pointer stubs -- whole entire aborted heap tuples.\n\n* In theory we could address this problem using opportunistic pruning.\nBut in practice that simply cannot happen today, because we don't\ntouch the inserted rows until literally hours later.\n\nThe same rows will eventually have updates and selects, but that won't\nhelp -- too little, too late. That's just how opportunistic pruning\nworks: currently you need some kind of scan node for opportunistic\npruning to kick in, so continually inserting transactions (from new\norders) are currently fundamentally unable to do any opportunistic\npruning. Much less opportunistic pruning that kicks in at exactly the\nright time.\n\n* When an autovacuum worker runs against these tables, it will of\ncourse notice this diffuse free space from aborted tuples, and put it\nin the FSM.\n\nThat free space will be reused, but by totally unrelated logical rows.\n\nWhat we really seem to need here is some rudimentary form of \"eager\nphysical rollback\"; the really important thing seems to be to not\nallow the problem to happen in the first place. I have a basic\nprototype implementation, built on top of the larger prototype patch.\nIt opportunistically prunes-away aborted heap tuples on target/open\npages, bypassing the usual pd_prune_xid check we have in\nheap_page_prune_opt() -- that doesn't make sense with the new form of\ntargeted, abort-orientated pruning. The new pruning mechanism makes a\nreally big difference on its own, without even involving the FSM. The\nbest cure for all kinds of bloat is prevention, which this comes\npretty close to.\n\nI think that this general idea can be pushed further. I've talked\nabout aborts, but what about the commit path? I don't see why we can't\nmake inserting backends responsible for setting hint bits on recently\ninserted rows -- the cost of putting off that work can only go up, no\nmatter what (unless maybe the user drops the table). Again, the\nmissing piece seems to be a general sense of ownership of heap pages\nby transactions and/or backends. In order for a backend to be able to\nclean up its own mess after itself while it's still cheap, it has to\nunderstand what that actually means.\n\nDon't forget that the TPC-C workload doesn't have that many updates\n(at least not for the tables I'm focussed on here). Nothing that we\ntend to think of as an adversarial case for Postgres, except perhaps\nthe updates against the \"order\" table, which are always non-HOT\nupdates due to an issue with the indexes. That's the extent of it,\nthough -- every other table easily has 99%+ of all updates use HOT\n(albeit with some heap fill factor tuning). We should *expect* long\nterm stability here, based on the particulars of the workload; we only\nneed to update every \"order\" row and every \"order lines\" row exactly\nonce. After that they can just age out of shared_buffers forever\n(actually they might be read again, but never modified again, but\nreads were never the problem). The big \"order line\" table is by far\nthe biggest problem, even though it manages to use HOT for practically\nall updates.\n\n[1] https://github.com/wieck/benchmarksql/commit/66b8db073545026dc76ef513d2b0e318d2f3d5a2\n[2] https://apps.dtic.mil/dtic/tr/fulltext/u2/a264793.pdf -- \"Table 1:\nSummary of Logical Database\"\n--\nPeter Geoghegan\n\n\n", "msg_date": "Mon, 6 Sep 2021 14:58:53 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "When I have been thinking of this type of problem it seems that the\nlatest -- and correct :) -- place which should do all kinds of\ncleanup like removing aborted tuples, freezing committed tuples and\nsetting any needed hint bits would be background writer or CHECKPOINT.\n\nThis would be more PostgreSQL-like, as it moves any work not\nimmediately needed from the critical path, as an extension of how MVCC\nfor PostgreSQL works in general.\n\nAnother option could be one more background cleaner with \"needs\ncleanup\" bitmap which is updated by \"real work\" backends to let the\ncleaner know what needs to be done.\n\nBut doing it as part of checkpoint probably ends up with less WAL\nwrites in the end.\n\nThat said, CHECKPOINT can efficiently clean up only Heap pages, unless\nwe do some extra work to ensure buffercache eviction ordering so that\nHeap is (almost) always cleaaned worst and has thus an option to also\nclean index pointers which point to it.\n\nThere could be a possibility to do a small amount of cleanup -- enough\nfor TPC-C-like workloads, but not larger ones -- while waiting for the\nnext command to arrive from the client over the network. This of\ncourse assumes that we will not improve our feeder mechanism to have\nback-to-back incoming commands, which can already be done today, but\nwhich I have seen seldom used.\n\nCheers,\n-----\nHannu Krosing\nGoogle Cloud - We have a long list of planned contributions and we are hiring.\nContact me if interested.\n\n\n\n\n\n\nOn Mon, Sep 6, 2021 at 11:59 PM Peter Geoghegan <pg@bowt.ie> wrote:\n>\n> On Mon, Aug 16, 2021 at 5:15 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> > This is actually quite simple -- the chaos that follows is where it\n> > gets truly complicated (and not necessarily worth getting into just\n> > yet). The update of a given order and its order lines entries takes\n> > place hours later, within a delivery transaction.\n>\n> Update on this: aborted transactions play an important role in the\n> chaos that we see with BenchmarkSQL/TPC-C.\n>\n> This is surprising, in one way. Only 1% of all transactions are\n> aborted (per the TPC-C spec). But in another way it's not surprising.\n> It's totally consistent with what I've been saying about open and\n> closed pages. When a page that's initially allocated and opened by a\n> backend becomes closed following some inserts, the page should be left\n> in a more or less pristine state -- owning backends that open and\n> close pages need to be \"good citizens.\n>\n> The definition of \"pristine\" must also include \"no already-aborted\n> tuples\" -- aborted xact tuples are a problem that we can and should\n> nip in the bud. This is really an extension of what I've been saying\n> about not disrupting naturally occuring temporal and spatial locality.\n> We're far better off if the space reused by freeing aborted heap\n> tuples is reused by the very next transaction running in the very same\n> backend. Plus it's not that hard; we can know for sure that this space\n> is immediately available, which is not generally true of pruning. And\n> so this free space from aborted xact tuples is quite special.\n>\n> Even with the master branch the problems with the FSM are much less\n> noticeable once you configure BenchmarkSQL to not abort any\n> transactions [1]. You need to consider the whole picture to understand\n> how the issue of aborted transactions has such an outsized negative\n> impact on performance and space efficiency.\n>\n> It's a whole *chain* of events:\n>\n> * If just 1% of all transactions abort, that's enough to leave an\n> average of about 1 aborted tuple on every \"order\" table page (which\n> naturally has small heap tuples [2]), and about 10 on a minority of\n> the really big \"new order\" table's pages. Maybe 1 in 10 or 12 \"order\n> line\" table heap pages are affected in this way.\n>\n> * The overall impact is that small (but not tiny) pockets of free\n> space are left randomly strewn all over the place. Not just LP_DEAD\n> line pointer stubs -- whole entire aborted heap tuples.\n>\n> * In theory we could address this problem using opportunistic pruning.\n> But in practice that simply cannot happen today, because we don't\n> touch the inserted rows until literally hours later.\n>\n> The same rows will eventually have updates and selects, but that won't\n> help -- too little, too late. That's just how opportunistic pruning\n> works: currently you need some kind of scan node for opportunistic\n> pruning to kick in, so continually inserting transactions (from new\n> orders) are currently fundamentally unable to do any opportunistic\n> pruning. Much less opportunistic pruning that kicks in at exactly the\n> right time.\n>\n> * When an autovacuum worker runs against these tables, it will of\n> course notice this diffuse free space from aborted tuples, and put it\n> in the FSM.\n>\n> That free space will be reused, but by totally unrelated logical rows.\n>\n> What we really seem to need here is some rudimentary form of \"eager\n> physical rollback\"; the really important thing seems to be to not\n> allow the problem to happen in the first place. I have a basic\n> prototype implementation, built on top of the larger prototype patch.\n> It opportunistically prunes-away aborted heap tuples on target/open\n> pages, bypassing the usual pd_prune_xid check we have in\n> heap_page_prune_opt() -- that doesn't make sense with the new form of\n> targeted, abort-orientated pruning. The new pruning mechanism makes a\n> really big difference on its own, without even involving the FSM. The\n> best cure for all kinds of bloat is prevention, which this comes\n> pretty close to.\n>\n> I think that this general idea can be pushed further. I've talked\n> about aborts, but what about the commit path? I don't see why we can't\n> make inserting backends responsible for setting hint bits on recently\n> inserted rows -- the cost of putting off that work can only go up, no\n> matter what (unless maybe the user drops the table). Again, the\n> missing piece seems to be a general sense of ownership of heap pages\n> by transactions and/or backends. In order for a backend to be able to\n> clean up its own mess after itself while it's still cheap, it has to\n> understand what that actually means.\n>\n> Don't forget that the TPC-C workload doesn't have that many updates\n> (at least not for the tables I'm focussed on here). Nothing that we\n> tend to think of as an adversarial case for Postgres, except perhaps\n> the updates against the \"order\" table, which are always non-HOT\n> updates due to an issue with the indexes. That's the extent of it,\n> though -- every other table easily has 99%+ of all updates use HOT\n> (albeit with some heap fill factor tuning). We should *expect* long\n> term stability here, based on the particulars of the workload; we only\n> need to update every \"order\" row and every \"order lines\" row exactly\n> once. After that they can just age out of shared_buffers forever\n> (actually they might be read again, but never modified again, but\n> reads were never the problem). The big \"order line\" table is by far\n> the biggest problem, even though it manages to use HOT for practically\n> all updates.\n>\n> [1] https://github.com/wieck/benchmarksql/commit/66b8db073545026dc76ef513d2b0e318d2f3d5a2\n> [2] https://apps.dtic.mil/dtic/tr/fulltext/u2/a264793.pdf -- \"Table 1:\n> Summary of Logical Database\"\n> --\n> Peter Geoghegan\n>\n>\n\n\n", "msg_date": "Tue, 7 Sep 2021 01:33:28 +0200", "msg_from": "Hannu Krosing <hannuk@google.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Mon, Sep 6, 2021 at 4:33 PM Hannu Krosing <hannuk@google.com> wrote:\n> When I have been thinking of this type of problem it seems that the\n> latest -- and correct :) -- place which should do all kinds of\n> cleanup like removing aborted tuples, freezing committed tuples and\n> setting any needed hint bits would be background writer or CHECKPOINT.\n>\n> This would be more PostgreSQL-like, as it moves any work not\n> immediately needed from the critical path, as an extension of how MVCC\n> for PostgreSQL works in general.\n\nI think it depends. There is no need to do work in the background\nhere, with TPC-C. With my patch series each backend can know that it\njust had an aborted transaction that affected a page that it more or\nless still owns. And has very close at hand, for further inserts. It's\nvery easy to piggy-back the work once you have that sense of ownership\nof newly allocated heap pages by individual backends/transactions.\n\n> This would be more PostgreSQL-like, as it moves any work not\n> immediately needed from the critical path, as an extension of how MVCC\n> for PostgreSQL works in general.\n\nI think that it also makes sense to have what I've called \"eager\nphysical rollback\" that runs in the background, as you suggest.\n\nI'm thinking of a specialized form of VACUUM that targets a specific\naborted transaction's known-dirtied pages. That's my long term goal,\nactually. Originally I wanted to do this as a way of getting rid of\nSLRUs and tuple freezing, by representing that all heap pages must\nonly have committed tuples implicitly. That seemed like a good enough\nreason to split VACUUM into specialized \"eager physical rollback\nfollowing abort\" and \"garbage collection\" variants.\n\nThe insight that making abort-related cleanup special will help free\nspace management is totally new to me -- it emerged from working\ndirectly on this benchmark. But it nicely complements some of my\nexisting ideas about improving VACUUM.\n\n> But doing it as part of checkpoint probably ends up with less WAL\n> writes in the end.\n\nI don't think that checkpoints are special in any way. They're very\nimportant in determining the total number of FPIs we'll generate, and\nso have huge importance today. But that seems accidental to me.\n\n> There could be a possibility to do a small amount of cleanup -- enough\n> for TPC-C-like workloads, but not larger ones -- while waiting for the\n> next command to arrive from the client over the network. This of\n> course assumes that we will not improve our feeder mechanism to have\n> back-to-back incoming commands, which can already be done today, but\n> which I have seen seldom used.\n\nThat's what I meant, really. Doing the work of cleaning up a heap page\nthat a transaction inserts into (say pruning away aborted tuples or\nsetting hint bits) should ideally happen right after commit or abort\n-- at least for OLTP like workloads, which are the common case for\nPostgres. This cleanup doesn't have to be done by exactly the same\ntransactions (and can't be in most interesting cases). It should be\nquite possible for the work to be done by approximately the same\ntransaction, though -- the current transaction cleans up inserts made\nby the previous (now committed/aborted) transaction in the same\nbackend (for the same table).\n\nThe work of setting hint bits and pruning-away aborted heap tuples has\nto be treated as a logical part of the cost of inserting heap tuples\n-- backends pay this cost directly. At least with workloads where\ntransactions naturally only insert a handful of rows each in almost\nall cases -- very much the common case.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Mon, 6 Sep 2021 17:29:24 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Thu, Aug 26, 2021 at 5:59 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> Andres has been working -- I think for years now -- on replacing the\n> buffer mapping table with a radix tree of some kind. That strikes me\n> as very similar to what you're doing here. The per-relation data can\n> then include not only the kind of stuff you're talking about but very\n> fundamental things like how long it is and where its buffers are in\n> the buffer pool. Hopefully we don't end up with dueling patches.\n\nFTR I have a patch in development that adds a demand-paged (though\nAnastasia recently suggested reconsidering that) per-SMGR relation\nshmem object pool that initially tracks precisely \"how long it is\",\nbut I hope it would provide a hook to hang many other things on in\nfuture that need coordination at the relation level, such as\nsynchronized scan position, and I hope, radix-based buffer mappings.\nCould be relevant? https://commitfest.postgresql.org/34/2933/ (I'll\nrebase it soon).\n\n\n", "msg_date": "Tue, 7 Sep 2021 14:08:24 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Mon, Sep 6, 2021 at 7:09 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> FTR I have a patch in development that adds a demand-paged (though\n> Anastasia recently suggested reconsidering that) per-SMGR relation\n> shmem object pool that initially tracks precisely \"how long it is\",\n> but I hope it would provide a hook to hang many other things on in\n> future that need coordination at the relation level, such as\n> synchronized scan position, and I hope, radix-based buffer mappings.\n\nCool!\n\n> Could be relevant? https://commitfest.postgresql.org/34/2933/ (I'll\n> rebase it soon).\n\nI think that it is relevant. You're coming at the same thing from\nroughly the opposite direction, at least in my mind. But that seems\nlike it might be a very good thing, given the specifics. I think that\nwe can meet each other in the middle, without there being any\nparticular risk of overlapping work or conflicting requirements. The\nresource management aspects of my own prototype are the least worked\nout and shakiest parts overall, so this seems likely. You've probably\nalready solved numerous problems for me.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Mon, 6 Sep 2021 19:22:11 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Tue, Sep 7, 2021 at 2:29 AM Peter Geoghegan <pg@bowt.ie> wrote:\n>\n> On Mon, Sep 6, 2021 at 4:33 PM Hannu Krosing <hannuk@google.com> wrote:\n> > When I have been thinking of this type of problem it seems that the\n> > latest -- and correct :) -- place which should do all kinds of\n> > cleanup like removing aborted tuples, freezing committed tuples and\n> > setting any needed hint bits would be background writer or CHECKPOINT.\n> >\n> > This would be more PostgreSQL-like, as it moves any work not\n> > immediately needed from the critical path, as an extension of how MVCC\n> > for PostgreSQL works in general.\n>\n> I think it depends. There is no need to do work in the background\n> here, with TPC-C. With my patch series each backend can know that it\n> just had an aborted transaction that affected a page that it more or\n> less still owns. And has very close at hand, for further inserts. It's\n> very easy to piggy-back the work once you have that sense of ownership\n> of newly allocated heap pages by individual backends/transactions.\n\nAre you speaking of just heap pages here or also index pages ?\n\nIt seems indeed easy for heap, but for index pages can be mixed up by\nother parallel work, especially things like Serial Primary Keys .\n\nOr are you expecting these to be kept in good-enoug shape by your\nearlier index manager work ?\n\n> > This would be more PostgreSQL-like, as it moves any work not\n> > immediately needed from the critical path, as an extension of how MVCC\n> > for PostgreSQL works in general.\n>\n> I think that it also makes sense to have what I've called \"eager\n> physical rollback\" that runs in the background, as you suggest.\n>\n> I'm thinking of a specialized form of VACUUM that targets a specific\n> aborted transaction's known-dirtied pages. That's my long term goal,\n> actually. Originally I wanted to do this as a way of getting rid of\n> SLRUs and tuple freezing, by representing that all heap pages must\n> only have committed tuples implicitly. That seemed like a good enough\n> reason to split VACUUM into specialized \"eager physical rollback\n> following abort\" and \"garbage collection\" variants.\n>\n> The insight that making abort-related cleanup special will help free\n> space management is totally new to me -- it emerged from working\n> directly on this benchmark. But it nicely complements some of my\n> existing ideas about improving VACUUM.\n\nA minimal useful patch emerging from that understanding could be\nsomething which just adds hysteresis to FSM management. (TBH, I\nactually kind of expected some hysteresis to be there already, as it\nis in my mental model of \"how things should be done\" for managing\nalmost any resource :) )\n\nAdding hysteresis to FSM management can hopefully be done independent\nof all the other stuff and also seems to be something that is\nunobtrusive and non-controversial enough to fit in current release and\npossibly be even back-ported .\n\n> > But doing it as part of checkpoint probably ends up with less WAL\n> > writes in the end.\n>\n> I don't think that checkpoints are special in any way. They're very\n> important in determining the total number of FPIs we'll generate, and\n> so have huge importance today. But that seems accidental to me.\n\nI did not mean CHECKPOINT as a command, but more the concept of\nwriting back / un-dirtying the page. In this sense it *is* special\nbecause it is the last point in time where you are guaranteed to have\nthe page available in buffercache and thus cheap to access for\nmodifications plus you will avoid a second full-page writeback because\nof cleanup. Also you do not want to postpone the cleanup to actual\npage eviction, as that is usually in the critical path for some user\nquery or command.\n\nOf course this becomes most important for workloads where the active\nworking set is larger than fits in memory and this is not a typical\ncase for OLTP any more. But at least freezing the page before\nwrite-out could have a very big impact on the need to freeze \"old\"\npages available only on disk and thus would be a cheap way to improve\nthe problems around running out of transaction ids.\n\n> > There could be a possibility to do a small amount of cleanup -- enough\n> > for TPC-C-like workloads, but not larger ones -- while waiting for the\n> > next command to arrive from the client over the network. This of\n> > course assumes that we will not improve our feeder mechanism to have\n> > back-to-back incoming commands, which can already be done today, but\n> > which I have seen seldom used.\n>\n> That's what I meant, really. Doing the work of cleaning up a heap page\n> that a transaction inserts into (say pruning away aborted tuples or\n> setting hint bits) should ideally happen right after commit or abort\n> -- at least for OLTP like workloads, which are the common case for\n> Postgres. This cleanup doesn't have to be done by exactly the same\n> transactions (and can't be in most interesting cases). It should be\n> quite possible for the work to be done by approximately the same\n> transaction, though -- the current transaction cleans up inserts made\n> by the previous (now committed/aborted) transaction in the same\n> backend (for the same table).\n\nAgain, do I assume correctly that you are here mainly targeting heap\nand not indexes ?\n\n> The work of setting hint bits and pruning-away aborted heap tuples has\n> to be treated as a logical part of the cost of inserting heap tuples\n> -- backends pay this cost directly. At least with workloads where\n> transactions naturally only insert a handful of rows each in almost\n> all cases -- very much the common case.\n\nI know that in general we are very reluctant to add threads to\npostgresql, but this looks a very valid case for having a\n\"microthread\" running on the same core as the DML as it will share all\nthe CPU caches and can thus be really cheap without being actually in\nthe critical path.\n\n Cheers,\n-----\nHannu Krosing\nGoogle Cloud - We have a long list of planned contributions and we are hiring.\nContact me if interested.\n\n\n", "msg_date": "Tue, 7 Sep 2021 14:24:56 +0200", "msg_from": "Hannu Krosing <hannuk@google.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Mon, Sep 6, 2021 at 8:29 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> On Mon, Sep 6, 2021 at 4:33 PM Hannu Krosing <hannuk@google.com> wrote:\n> > When I have been thinking of this type of problem it seems that the\n> > latest -- and correct :) -- place which should do all kinds of\n> > cleanup like removing aborted tuples, freezing committed tuples and\n> > setting any needed hint bits would be background writer or CHECKPOINT.\n> >\n> > This would be more PostgreSQL-like, as it moves any work not\n> > immediately needed from the critical path, as an extension of how MVCC\n> > for PostgreSQL works in general.\n>\n> I think it depends. There is no need to do work in the background\n> here, with TPC-C. With my patch series each backend can know that it\n> just had an aborted transaction that affected a page that it more or\n> less still owns. And has very close at hand, for further inserts. It's\n> very easy to piggy-back the work once you have that sense of ownership\n> of newly allocated heap pages by individual backends/transactions.\n\nDoing work in the background has some advantages, though. In\nparticular, it has the possibly-large advantage of not slowing down\nforeground work.\n\nFor me the key insight here is that HOT-pruning a heap page is a lot\ncheaper if you do it before you write the page. Once you've written\nthe page, the eventual HOT-prune is going to need to dirty it, which\nwill cause it to be written again. If you prune before writing it the\nfirst time, that cost is avoided. I'm not sure that it really matters\nwhether the space consumed by aborted tuples gets reused by \"the very\nnext transaction\" or, say, 10 transactions after that, or even 1000\ntransactions after that. If you wait for a million transactions,\nyou've quite possibly lost enough temporality to matter, but at 10 or\n1000 that's much less likely. The exact threshold is fuzzy: every\nmoment you wait makes it less likely that you have sufficient\nlocality, but you can always find a workload where even a very long\nwait is acceptable, and another one where even a tiny delay is\ncatastrophic, and it's hard to say what the \"real world\" looks like.\n\nOn the other hand, there's nothing fuzzy about the expense incurred by\nwriting the page before it's HOT-pruned. That is essentially certain\nto incur an extra page write, except in the corner case where the\nrelation gets dropped or truncated before then. So I think you might\nfind that if you found a way to ensure that HOT-pruning -- and entry\ninto the FSM -- always happens for every heap page just before it's\nwritten, if it hasn't already happened sooner and might be needed, you\nmight end up in a pretty good spot. It wouldn't even be ignoring\ntemporal locality, since at minimum dirty pages are written once per\ncheckpoint cycle.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 7 Sep 2021 15:31:09 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Tue, Sep 7, 2021 at 12:31 PM Robert Haas <robertmhaas@gmail.com> wrote:\n> Doing work in the background has some advantages, though. In\n> particular, it has the possibly-large advantage of not slowing down\n> foreground work.\n\nWhat I really like about the idea of doing the work in the foreground\n(when it's clearly not going to be too much of a latency hit) is that\nit would act as a natural form of backpressure. Sometimes slowing\nthings down is a good thing -- fundamentally inefficient and\nunsustainable use of the system's resources ought to be slowed down by\nimposing the cost on the transaction that performs the relevant insert\nqueries. To me this seems like a problem of negative externalities.\nWith small transactions we can pretty much know for sure that the\nbenefit of not leaving pages in good shape at the moment they become\n\"closed\" is fixed and low, while the cost to the system as a whole\nover time is potentially far higher. It seems almost unbounded, in a\nway, so we're bound to lose in the long run, regardless of workload.\n(The work can be piggybacked across transactions to make it more\nefficient, but that's mostly an implementation detail.)\n\nUpdaters might actually be much less of a problem than inserters. They\nalready keep costs down by pruning opportunistically -- they at least\ntry. Most individual logical rows that are inserted have exactly zero\nchance of ever being updated, but a ~100% chance of needing to have\nhint bits set sooner or later. We know very little about workload\ncharacteristics, but these are some of the few things that we really\ndo know for sure.\n\n> For me the key insight here is that HOT-pruning a heap page is a lot\n> cheaper if you do it before you write the page. Once you've written\n> the page, the eventual HOT-prune is going to need to dirty it, which\n> will cause it to be written again. If you prune before writing it the\n> first time, that cost is avoided.\n\nRight. The difficulty with applying that insight before now has been\nmaking the prune operation take place at the level of whole pages\nsystematically. I believe that it's quite valuable to set all the hint\nbits on a page as we \"close it out\" for the first time. But setting\nhint bits for all of the heap tuples on the page except one or two is\npretty much useless. You might as well not bother at all.\n\nIt follows that concurrent inserters clobbering the same page\nsenselessly are more or less not okay if we're going to pursue this\ntechnique. You might still have a concurrent update of one of the\ninserted rows shortly after the original inserting transaction\ncommits, but before the page is closed -- that might make the idea not\nwork out for that one page (obviously it depends on the specifics).\nThat seems like something we can live with, though.\n\n> I'm not sure that it really matters\n> whether the space consumed by aborted tuples gets reused by \"the very\n> next transaction\" or, say, 10 transactions after that, or even 1000\n> transactions after that. If you wait for a million transactions,\n> you've quite possibly lost enough temporality to matter, but at 10 or\n> 1000 that's much less likely.\n\nI didn't mean to suggest that it had to happen in perfect lockstep.\nBut I do think that it should be pretty close to perfect. What I\nactually do right now is prune an open page when it *appears* to be\nfull inside the loop in RelationGetBufferForTuple(). As crude as that\nis, it sets hint bits and prunes away aborted transactions in mostly\nthe right way, at least as far as TPC-C is concerned. (This only works\nbecause it fits into the wider framework of my much larger patch,\nwhich introduces ownership semantics, open and closed pages, empty\npage freelists, etc.)\n\n> The exact threshold is fuzzy: every\n> moment you wait makes it less likely that you have sufficient\n> locality, but you can always find a workload where even a very long\n> wait is acceptable, and another one where even a tiny delay is\n> catastrophic, and it's hard to say what the \"real world\" looks like.\n\nI agree that offloading work in the background can be very useful, and\nthat technique needs to be possible as future work (I actually really\nwant this myself). But most individual apps probably won't really\nnotice the latency hit from pruning if it's well managed -- as with\npruning by updates today. We can make a decision about which strategy\nto use (lightweight foreground processing with a potential latency\nhit, or background batch cleanup?) at a very late point in the cycle,\nbased on the specifics in each case. Offhand, I don't think that we\nneed to characterize this fuzzy threshold in too much detail. I\nsuspect that the main determinative question can be simple enough.\nSomething like: Does this transaction (or this group of transactions)\ninvolve only trivial changes to maybe 3 - 5 heap pages at the most, or\nnot?\n\nThere is a separate question about what happens if our background\ncleanup process cannot keep up over time. I think that we can handle\nthat by falling back on foreground processing (within reason). Let's\nsay we have transactions that each insert on to dozens or perhaps even\nhundreds of heap pages each -- these are \"medium sized'' write\ntransactions. If we're already doing way too much background\nprocessing for similar transactions from earlier on, and if it's clear\nwe just can't keep up, maybe we can fall back and force foreground\nprocessing, to keep the debt under control. (In general I think that\nthis back pressure, negative externalities business will be\nimportant.)\n\nIt seems to me that this leaves one harder question unanswered: at\nwhat point does a \"medium sized\" transaction become so large that it\njust doesn't make sense to do either? What's the crossover point at\nwhich background processing and foreground processing like this should\nbe assumed to be not worth it? That I won't speculate about just yet.\nI suspect that at some point it really does make sense to leave it all\nup to a true table-level batch operation, like a conventional VACUUM.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Tue, 7 Sep 2021 18:37:30 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Tue, Sep 7, 2021 at 5:25 AM Hannu Krosing <hannuk@google.com> wrote:\n> Are you speaking of just heap pages here or also index pages ?\n\nMostly heap pages, but FWIW I think it could work for index tuples\ntoo, with retail index tuple deletion. Because that allows you to even\nremove would-be LP_DEAD item pointers.\n\n> Or are you expecting these to be kept in good-enoug shape by your\n> earlier index manager work ?\n\nIt's very workload dependent. Some things were very much improved by\nbottom-up index deletion in Postgres 14, for example (non-hot updates\nwith lots of logically unchanged indexes). Other things weren't helped\nat all, or were barely helped. I think it's important to cover or\ncases.\n\n> A minimal useful patch emerging from that understanding could be\n> something which just adds hysteresis to FSM management. (TBH, I\n> actually kind of expected some hysteresis to be there already, as it\n> is in my mental model of \"how things should be done\" for managing\n> almost any resource :) )\n\nI think that you need to do the FSM before the aborted-heap-tuple\ncleanup. Otherwise you don't really know when or where to apply the\nspecial kind of pruning that the patch invents, which targets aborts\nspecifically.\n\n> Adding hysteresis to FSM management can hopefully be done independent\n> of all the other stuff and also seems to be something that is\n> unobtrusive and non-controversial enough to fit in current release and\n> possibly be even back-ported .\n\nI don't know about that! Seems kind of an invasive patch to me.\n\n> I did not mean CHECKPOINT as a command, but more the concept of\n> writing back / un-dirtying the page. In this sense it *is* special\n> because it is the last point in time where you are guaranteed to have\n> the page available in buffercache and thus cheap to access for\n> modifications plus you will avoid a second full-page writeback because\n> of cleanup. Also you do not want to postpone the cleanup to actual\n> page eviction, as that is usually in the critical path for some user\n> query or command.\n\nI intend to do some kind of batching, but only at the level of small\ngroups of related transactions. Writing a page that was quickly opened\nfor new inserts, filled with newly inserted heap tuples, then closed,\nand finally cleaned up doesn't seem like it needs to take any direct\nresponsibility for writeback.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Tue, 7 Sep 2021 21:52:21 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Wed, Sep 8, 2021 at 6:52 AM Peter Geoghegan <pg@bowt.ie> wrote:\n>\n> On Tue, Sep 7, 2021 at 5:25 AM Hannu Krosing <hannuk@google.com> wrote:\n> > Are you speaking of just heap pages here or also index pages ?\n>\n> Mostly heap pages, but FWIW I think it could work for index tuples\n> too, with retail index tuple deletion. Because that allows you to even\n> remove would-be LP_DEAD item pointers.\n\nBut it does need info from the heap page(s) the index entry points to,\nwhich can become quite expensive if that heap page is locked by other\nprocesses or even not cached at all.\n\nAlso, parallel processes may have moved the index entry to other pages etc.\n\n> > Or are you expecting these to be kept in good-enoug shape by your\n> > earlier index manager work ?\n>\n> It's very workload dependent. Some things were very much improved by\n> bottom-up index deletion in Postgres 14, for example (non-hot updates\n> with lots of logically unchanged indexes). Other things weren't helped\n> at all, or were barely helped. I think it's important to cover or\n> cases.\n>\n> > A minimal useful patch emerging from that understanding could be\n> > something which just adds hysteresis to FSM management. (TBH, I\n> > actually kind of expected some hysteresis to be there already, as it\n> > is in my mental model of \"how things should be done\" for managing\n> > almost any resource :) )\n>\n> I think that you need to do the FSM before the aborted-heap-tuple\n> cleanup. Otherwise you don't really know when or where to apply the\n> special kind of pruning that the patch invents, which targets aborts\n> specifically.\n\nAlternative is to not actually prune the page at all at this time (to\navoid re-dirtying it and/or WAL write) but just inspect and add the\n*potential* free space in FSM.\nAnd then do the pruning at the time of next INSERT or UPDATE when the\npage is ditied and WAL written anyway.\n\n> > Adding hysteresis to FSM management can hopefully be done independent\n> > of all the other stuff and also seems to be something that is\n> > unobtrusive and non-controversial enough to fit in current release and\n> > possibly be even back-ported .\n>\n> I don't know about that! Seems kind of an invasive patch to me.\n\nWhy do you think that changing the calculation when a page is added\nback to FSM is \"kind of invasive\" ?\n\nNot having looked at the code I would assume from the discussion here\nthat we remove the page from FSM when free space goes above FILLFACTOR\nand we add it back when it goes back below FILLFACTOR.\n\nThe code change would just change the \"add id back\" code to use\nFILLFACTOR - HYSTERESIS_FACTOR instead.\n\nWhat other parts does this need to touch ? Or is it just that the\ncalculation source code is not localised well in code and written\nmultiple times all over the place ?\n\n> > I did not mean CHECKPOINT as a command, but more the concept of\n> > writing back / un-dirtying the page. In this sense it *is* special\n> > because it is the last point in time where you are guaranteed to have\n> > the page available in buffercache and thus cheap to access for\n> > modifications plus you will avoid a second full-page writeback because\n> > of cleanup. Also you do not want to postpone the cleanup to actual\n> > page eviction, as that is usually in the critical path for some user\n> > query or command.\n>\n> I intend to do some kind of batching, but only at the level of small\n> groups of related transactions. Writing a page that was quickly opened\n> for new inserts, filled with newly inserted heap tuples, then closed,\n> and finally cleaned up doesn't seem like it needs to take any direct\n> responsibility for writeback.\n\nAgreed that this code does not need to care about writeback.\n\nI approached it from the other end and proposed the \"just before\nwriteback\" as a strategy which is easy to understand conceptually and\nalso is mostly \"already there\" codewise, that is there is a location\nin write-back code to plug the call to cleanup in .\n\nCheers\n-----\nHannu Krosing\nGoogle Cloud - We have a long list of planned contributions and we are hiring.\nContact me if interested.\n\n\n", "msg_date": "Wed, 8 Sep 2021 12:01:50 +0200", "msg_from": "Hannu Krosing <hannuk@google.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Tue, Sep 7, 2021 at 9:37 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> What I really like about the idea of doing the work in the foreground\n> (when it's clearly not going to be too much of a latency hit) is that\n> it would act as a natural form of backpressure.\n\nRight, that's fair. But, prune-before-evict can be done in the first\ninstance by the bgwriter and then by the foreground process doing the\neviction if the bgwriter doesn't keep up. At least, assuming we had a\nbgwriter that worked, which I think right now we don't, but fixing\nthat might be a good idea anyway.\n\n> I didn't mean to suggest that it had to happen in perfect lockstep.\n> But I do think that it should be pretty close to perfect. What I\n> actually do right now is prune an open page when it *appears* to be\n> full inside the loop in RelationGetBufferForTuple().\n\nThat seems like a good idea.\n\n> As crude as that\n> is, it sets hint bits and prunes away aborted transactions in mostly\n> the right way, at least as far as TPC-C is concerned. (This only works\n> because it fits into the wider framework of my much larger patch,\n> which introduces ownership semantics, open and closed pages, empty\n> page freelists, etc.)\n\nI don't know, I'm not really convinced that \"much larger patches\" that\nchange a lot of loosely related things all at once are good for the\nproject. It seems to me that there's a reasonably good chance of\nreplacing an annoying set of problems that existing PostgreSQL users\nhave worked around to some degree, knowing or unknowingly, with a\ndifferent annoying set of problems that may cause fewer or more\nproblems in practice. Sometimes there's no way to improve something\nshort of a giant project that changes a lot of things at the same\ntime, but a series of incremental changes is a lot less risky.\n\n> It seems to me that this leaves one harder question unanswered: at\n> what point does a \"medium sized\" transaction become so large that it\n> just doesn't make sense to do either? What's the crossover point at\n> which background processing and foreground processing like this should\n> be assumed to be not worth it? That I won't speculate about just yet.\n> I suspect that at some point it really does make sense to leave it all\n> up to a true table-level batch operation, like a conventional VACUUM.\n\nI doubt it makes sense to define a limit here explicitly. At some\npoint strategies will naturally start to fail, e.g. prune-before-evict\nwon't work once the operation becomes large enough that pages have to\nbe evicted while the transaction is still running.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 8 Sep 2021 11:20:35 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Wed, Sep 8, 2021 at 8:20 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > I didn't mean to suggest that it had to happen in perfect lockstep.\n> > But I do think that it should be pretty close to perfect. What I\n> > actually do right now is prune an open page when it *appears* to be\n> > full inside the loop in RelationGetBufferForTuple().\n>\n> That seems like a good idea.\n\n> I don't know, I'm not really convinced that \"much larger patches\" that\n> change a lot of loosely related things all at once are good for the\n> project. It seems to me that there's a reasonably good chance of\n> replacing an annoying set of problems that existing PostgreSQL users\n> have worked around to some degree, knowing or unknowingly, with a\n> different annoying set of problems that may cause fewer or more\n> problems in practice. Sometimes there's no way to improve something\n> short of a giant project that changes a lot of things at the same\n> time, but a series of incremental changes is a lot less risky.\n\nBut these things are *highly* related.\n\nThe RelationGetBufferForTuple() prune mechanism I described (that\ntargets aborted xact tuples and sets hint bits) is fundamentally built\non top of the idea of ownership of heap pages by backends/transactions\n-- that was what I meant before. We *need* to have context. This isn't an\nordinary heap prune -- it doesn't have any of the prechecks to avoid\nuseless pruning that you see at the top of heap_page_prune_opt(). It's\npossible that we won't be able to get a super-exclusive lock in the\nspecialized prune code path, but that's considered a rare corner case.\nThere is no question of concurrent inserters senselessly blocking the\nprune, which is not at all true with the current approach to free\nspace management. So there is no way I could extract a minimal \"prune\ninside RelationGetBufferForTuple()\" patch that would actually work.\n\nSystems that follow ARIES closely and have UNDO *must* treat free\nspace as a qualitative thing, something that is meaningful only with\nassociated information about a deleting or inserting transaction, and\nits status. There is logical UNDO for the free space management\nstructure, and even getting free space from a page can involve\nheavyweight locking. Postgres works differently, but there is no\nreason why Postgres should not do a lightweight approximate version of\nthe same thing - the laws of physics favor carefully grouping\nlogically related data, and working to keep the physical database\nrepresentation as clean a representation of the logical database as\npossible, right from the start.\n\n> > It seems to me that this leaves one harder question unanswered: at\n> > what point does a \"medium sized\" transaction become so large that it\n> > just doesn't make sense to do either? What's the crossover point at\n> > which background processing and foreground processing like this should\n> > be assumed to be not worth it? That I won't speculate about just yet.\n> > I suspect that at some point it really does make sense to leave it all\n> > up to a true table-level batch operation, like a conventional VACUUM.\n>\n> I doubt it makes sense to define a limit here explicitly. At some\n> point strategies will naturally start to fail, e.g. prune-before-evict\n> won't work once the operation becomes large enough that pages have to\n> be evicted while the transaction is still running.\n\nPerhaps. As you know I'm generally in favor of letting things fail\nnaturally, and then falling back on an alternative strategy.\n\n\n--\nPeter Geoghegan\n\n\n", "msg_date": "Wed, 8 Sep 2021 09:27:32 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Wed, Sep 8, 2021 at 12:27 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> But these things are *highly* related.\n>\n> The RelationGetBufferForTuple() prune mechanism I described (that\n> targets aborted xact tuples and sets hint bits) is fundamentally built\n> on top of the idea of ownership of heap pages by backends/transactions\n> -- that was what I meant before. We *need* to have context. This isn't an\n> ordinary heap prune -- it doesn't have any of the prechecks to avoid\n> useless pruning that you see at the top of heap_page_prune_opt(). It's\n> possible that we won't be able to get a super-exclusive lock in the\n> specialized prune code path, but that's considered a rare corner case.\n> There is no question of concurrent inserters senselessly blocking the\n> prune, which is not at all true with the current approach to free\n> space management. So there is no way I could extract a minimal \"prune\n> inside RelationGetBufferForTuple()\" patch that would actually work.\n\nI'm not trying to argue for slimming down your patches to a size that\nis so small that they no longer work.\n\nHowever, I *am* arguing that, like bottom-up index deletion and the\nemergency vacuum mechanism, this change sounds like something that\ncould *easily* have unforeseen consequences. And therefore a lot of\ncaution is needed. And part of that caution is not changing more\nthings at the same time than is really necessary. And that it's worth\nthinking *hard* about how much change is *really* necessary.\n\nIt's very easy to convince oneself that everything is connected to\neverything else and therefore we have to change a lot of things all at\nonce, but that's often not true.\n\n--\nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 8 Sep 2021 12:35:46 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" }, { "msg_contents": "On Wed, Sep 8, 2021 at 9:35 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> I'm not trying to argue for slimming down your patches to a size that\n> is so small that they no longer work.\n\nI was just explaining how the \"eager physical rollback by pruning\" thing works.\n\n> However, I *am* arguing that, like bottom-up index deletion and the\n> emergency vacuum mechanism, this change sounds like something that\n> could *easily* have unforeseen consequences. And therefore a lot of\n> caution is needed.\n\nI agree that a lot of caution is needed. One can justify aggressive\nintervention when the likely alternative is a severe and irreversible\nadverse event, like a version-driven page split. On the other hand we\nreally should be very conservative when that isn't what we see.\nContext is very important.\n\n> And part of that caution is not changing more\n> things at the same time than is really necessary. And that it's worth\n> thinking *hard* about how much change is *really* necessary.\n\nFor the record bottom-up index deletion had very little code in the\ngrand scheme of things. Without documentation changes and comments it\nis probably less than 1000 lines of C. And the emergency mechanism\n(considered separately from the refactoring work) had very little\ncode. So I don't know what you mean about changing lots of things all\ntogether at once. Huge big-bang style patches really aren't my style\nat all. Don't expect that to change.\n\n> It's very easy to convince oneself that everything is connected to\n> everything else and therefore we have to change a lot of things all at\n> once, but that's often not true.\n\nThere is compelling empirical evidence for my \"chain of events\"\nexplanation. You can make things much better for BenchmarkSQL on the\nmaster branch today, either by artificially disabling the FSM\naltogether (which hurts a little but helps a lot), *or* by configuring\nthe benchmark to not abort transactions in the first place (which\neffectively simulates eager physical rollback of aborted xacts).\n\nI don't want to change very much. Despite everything I've said, I\nthink it's true that the system does the right thing in most\nsituations -- even with BenchmarkSQL/TPC-C! I just find it useful to\nfocus on the exceptions, the cases where the system clearly does the\nwrong thing.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Wed, 8 Sep 2021 10:46:14 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: The Free Space Map: Problems and Opportunities" } ]
[ { "msg_contents": "Hey, hackers!\n\nWhile working with some foreign keys, I noticed some mildly unexpected\nbehavior. The columns referenced by a unique constraint must naturally\nhave a unique constraint on them:\n\nCREATE TABLE foo (a integer);\nCREATE TABLE bar (x integer REFERENCES foo(a));\n> ERROR: there is no unique constraint matching given keys for referenced\n table \"foo\"\n\nBut Postgres doesn't allow a foreign key to reference a set of columns\nwithout a unique constraint, even if there a unique constraint on a\nsubset of those columns (i.e., it doesn't allow referencing a superset\nof a unique constraint).\n\nCREATE TABLE foo (a integer PRIMARY KEY, b integer);\nCREATE TABLE bar (x integer, y integer, FOREIGN KEY (x, y) REFERENCES\nfoo(a, b));\n> ERROR: there is no unique constraint matching given keys for referenced\n table \"foo\"\n\nIt seems to me like there would be nothing wrong in this case to allow this\nforeign key constraint to exist. Because there is a unique constraint on foo(a),\nfoo(a, b) will also be unique. And it doesn't seem like it would be too complex\nto implement.\n\nNeither MATCH SIMPLE nor MATCH FULL constraints would have any issues\nwith this. MATCH PARTIAL may, but, alas, it's not implemented. (I've had\na few ideas about foreign keys, and MATCH PARTIAL seems to always come\nup, and I still don't understand what its use case is.)\n\n\n\n\nA real-world use case that uses denormalization could run into this. Imagine a\nnaive music database that has a list of artists, albums, and songs, where each\nalbum is by one artist and each song is on one album, but we still store a\nreference to the artist on each song:\n\nCREATE TABLE artists (id serial PRIMARY KEY, name text);\nCREATE TABLE albums (id serial PRIMARY KEY, artist_id REFERENCES\nartists(id) name text);\nCREATE TABLE songs (\n id serial PRIMARY KEY,\n artist_id REFERENCES artists(id) ON DELETE CASCADE,\n album_id REFERENCES albums(id) ON DELETE CASCADE,\n name text,\n);\n\nTo ensure that artist deletions are fast, we need to create an index on\nsongs(artist_id) and songs(album_id). But, suppose we wanted to save on index\nspace, and we never needed to query JUST by album_id. We could then do:\n\nCREATE TABLE songs (\n id serial PRIMARY KEY,\n artist_id REFERENCES artists(id) ON DELETE CASCADE,\n album_id integer,\n name text,\n FOREIGN KEY (artist_id, album_id) REFERENCES albums(artist_id, id)\nON DELETE CASCADE\n);\n\nAnd then we could have a single index on songs(artist_id, album_id) that would\nserve both ON CASCADE DELETE triggers:\n\n-- Delete artist\nDELETE FROM songs WHERE artist_id = <artist.id>;\n-- Delete artist\nDELETE FROM songs\n WHERE artist_id = <album.artist_id> AND album_id = <album.id>;\n\nBut Postgres wouldn't let us create the composite foreign key described.\n\n\n\nIt seems like a somewhat useful feature. If people think it would be useful to\nimplement, I might take a stab at it when I have time.\n\n- Paul\n\n\n", "msg_date": "Mon, 16 Aug 2021 16:36:40 -0700", "msg_from": "Paul Martinez <hellopfm@gmail.com>", "msg_from_op": true, "msg_subject": "Allow composite foreign keys to reference a superset of unique\n constraint columns?" }, { "msg_contents": "On Mon, Aug 16, 2021 at 4:37 PM Paul Martinez <hellopfm@gmail.com> wrote:\n\n>\n> It seems like a somewhat useful feature. If people think it would be\n> useful to\n> implement, I might take a stab at it when I have time.\n>\n>\nThis doesn't seem useful enough for us to be the only implementation to go\nabove and beyond the SQL Standard's specification for the references\nfeature (I assume that is what this proposal suggests).\n\nThis example does a good job of explaining but its assumptions aren't that\nimpactful and thus isn't that good at inducing desirability.\n\nDavid J.\n\nOn Mon, Aug 16, 2021 at 4:37 PM Paul Martinez <hellopfm@gmail.com> wrote:\nIt seems like a somewhat useful feature. If people think it would be useful to\nimplement, I might take a stab at it when I have time.This doesn't seem useful enough for us to be the only implementation to go above and beyond the SQL Standard's specification for the references feature (I assume that is what this proposal suggests).This example does a good job of explaining but its assumptions aren't that impactful and thus isn't that good at inducing desirability.David J.", "msg_date": "Mon, 16 Aug 2021 17:00:58 -0700", "msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow composite foreign keys to reference a superset of unique\n constraint columns?" }, { "msg_contents": "On Mon, Aug 16, 2021 at 7:01 PM David G. Johnston <\ndavid.g.johnston@gmail.com> wrote:\n\n> On Mon, Aug 16, 2021 at 4:37 PM Paul Martinez <hellopfm@gmail.com> wrote:\n>\n>>\n>> It seems like a somewhat useful feature. If people think it would be\n>> useful to\n>> implement, I might take a stab at it when I have time.\n>>\n>>\n> This doesn't seem useful enough for us to be the only implementation to go\n> above and beyond the SQL Standard's specification for the references\n> feature (I assume that is what this proposal suggests).\n>\n> This example does a good job of explaining but its assumptions aren't that\n> impactful and thus isn't that good at inducing desirability.\n>\n>\n\nI have no opinion on the broader concerns about this proposed feature, but\nspeaking simply as a user I have wanted this on multiple occasions. In my\ncase, it is usually because of the need to maintain consistency in a\ndiamond table relationship. For example:\n\ncreate table tenants (\n id serial primary key\n);\n\ncreate table users (\n id serial primary key,\n tenant_id int references tenants\n);\n\ncreate table user_groups (\n id serial primary key,\n tenant_id int references tenants\n);\n\ncreate table user_group_memberships (\n tenant_id int,\n user_id int,\n user_group_id,\n primary key (user_id, user_group_id),\n foreign key (user_id, tenant_id) references users (id, tenant_id),\n foreign key (user_group_id, tenant_id) references user_groups (id,\ntenant_id)\n);\n\nThe only way to ensure a user can only be a member of a group in the same\ntenant is to user_group_memberships.tenant_id be part of the foreign key.\nAnd that will only work with a unique key on id and tenant_id in both users\nand user_groups. It's a bit inelegant to create multiple extra indexes to\nensure consistency when existing indexes are enough to ensure uniqueness.\n\nJack\n\nOn Mon, Aug 16, 2021 at 7:01 PM David G. Johnston <david.g.johnston@gmail.com> wrote:On Mon, Aug 16, 2021 at 4:37 PM Paul Martinez <hellopfm@gmail.com> wrote:\nIt seems like a somewhat useful feature. If people think it would be useful to\nimplement, I might take a stab at it when I have time.This doesn't seem useful enough for us to be the only implementation to go above and beyond the SQL Standard's specification for the references feature (I assume that is what this proposal suggests).This example does a good job of explaining but its assumptions aren't that impactful and thus isn't that good at inducing desirability. I have no opinion on the broader concerns about this proposed feature, but speaking simply as a user I have wanted this on multiple occasions. In my case, it is usually because of the need to maintain consistency in a diamond table relationship. For example:create table tenants (  id serial primary key);create table users (  id serial primary key,  tenant_id int references tenants);create table user_groups (  id serial primary key,  tenant_id int references tenants);create table user_group_memberships (  tenant_id int,  user_id int,  user_group_id,  primary key (user_id, user_group_id),  foreign key (user_id, tenant_id) references users (id, tenant_id),  foreign key (user_group_id, tenant_id) references user_groups (id, tenant_id));The only way to ensure a user can only be a member of a group in the same tenant is to user_group_memberships.tenant_id be part of the foreign key. And that will only work with a unique key on id and tenant_id in both users and user_groups. It's a bit inelegant to create multiple extra indexes to ensure consistency when existing indexes are enough to ensure uniqueness.Jack", "msg_date": "Tue, 17 Aug 2021 10:41:00 -0500", "msg_from": "Jack Christensen <jack@jncsoftware.com>", "msg_from_op": false, "msg_subject": "Re: Allow composite foreign keys to reference a superset of unique\n constraint columns?" }, { "msg_contents": "On Tue, Aug 17, 2021 at 8:41 AM Jack Christensen <jack@jncsoftware.com> wrote:\n>\n> The only way to ensure a user can only be a member of a group in the same\n> tenant is to user_group_memberships.tenant_id be part of the foreign key. And\n> that will only work with a unique key on id and tenant_id in both users and\n> user_groups. It's a bit inelegant to create multiple extra indexes to ensure\n> consistency when existing indexes are enough to ensure uniqueness.\n>\n> Jack\n\nYou could accomplish this by using composite primary keys on the users and\nuser_groups tables:\n\nCREATE TABLE users (\n id serial,\n tenant_id int REFERENCES tenants(id),\n PRIMARY KEY (tenant_id, id)\n);\n\nThis approach works pretty well for multi-tenant databases, because then your\nindexes all start with tenant_id, which should help with performance, and, in\ntheory, would make your database easier to shard. But then it requires\nincluding a tenant_id in *every* query (and subquery!), which may be difficult\nto enforce in a codebase.\n\nOne downside of the composite primary/foreign key approach is that ON DELETE\nSET NULL foreign keys no longer work properly because they try to set both\ncolumns to NULL, the true foreign key id, AND the shared tenant_id that is part\nof the referencing table's primary key. I have a patch [1] out to add new\nfunctionality to solve this problem though.\n\n- Paul\n\n[1]: https://www.postgresql.org/message-id/flat/CACqFVBZQyMYJV%3DnjbSMxf%2BrbDHpx%3DW%3DB7AEaMKn8dWn9OZJY7w%40mail.gmail.com\n\n\n", "msg_date": "Tue, 17 Aug 2021 10:45:57 -0700", "msg_from": "Paul Martinez <hellopfm@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow composite foreign keys to reference a superset of unique\n constraint columns?" }, { "msg_contents": "On Tue, 2021-08-17 at 10:45 -0700, Paul Martinez wrote:\n> On Tue, Aug 17, 2021 at 8:41 AM Jack Christensen <jack@jncsoftware.com> wrote:\n> > The only way to ensure a user can only be a member of a group in the same\n> > tenant is to user_group_memberships.tenant_id be part of the foreign key. And\n> > that will only work with a unique key on id and tenant_id in both users and\n> > user_groups. It's a bit inelegant to create multiple extra indexes to ensure\n> > consistency when existing indexes are enough to ensure uniqueness.\n> \n> You could accomplish this by using composite primary keys on the users and\n> user_groups tables:\n> \n> CREATE TABLE users (\n> id serial,\n> tenant_id int REFERENCES tenants(id),\n> PRIMARY KEY (tenant_id, id)\n> );\n\nThat is not a proper solution, because it does not guarantee uniqueness of\nthe \"id\" column, which is typically what you want.\n\nSo I think Jack's example illustrates the benefit of this proposal well.\n\nOn the other hand, the SQL standard requires that a foreign key references\na unique constraint, see chapter 11.8 <referential constraint definition>,\nSyntax Rules 3) a):\n\n \"If the <referenced table and columns> specifies a <reference column list>,\n then there shall be a one-to-one correspondence between the set of\n <column name>s contained in that <reference column list> and the set of\n <column name>s contained in the <unique column list> of a unique constraint\n of the referenced table such that corresponding <column name>s are equivalent.\"\n\nSo while I personally agree that the proposed feature is useful, I am not\nsure if it is useful enough to break the standard in a way that may be\nincompatible with future extensions of the standard.\n\nYours,\nLaurenz Albe\n\n\n\n", "msg_date": "Wed, 18 Aug 2021 04:25:56 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: Allow composite foreign keys to reference a superset of unique\n constraint columns?" } ]
[ { "msg_contents": "Hi hackers,\nRecently, I noticed a great patch in pg 14.\n\"Rework planning and execution of UPDATE and DELETE. (86dc90056dfdbd9d1b891718d2e5614e3e432f35)\"\nThis changes the DML execution of the partitioned table and makes it more friendly.\n But I am very confused about the following changes:\n```\n+ relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;\n+ if (relkind == RELKIND_RELATION ||\n+ relkind == RELKIND_MATVIEW ||\n+ relkind == RELKIND_PARTITIONED_TABLE)\n {\n- char relkind;\n- Datum datum;\n- bool isNull;\n-\n- relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;\n- if (relkind == RELKIND_RELATION || relkind == RELKIND_MATVIEW)\n- {\n- datum = ExecGetJunkAttribute(slot,\n- junkfilter->jf_junkAttNo,\n- &isNull);\n- /* shouldn't ever get a null result... */```\nAccording to my understanding, the parent table of a partitioned table does not store any tuples. \nThen why is \"relkind = = RELKIND_PARTITIONED_TABLE\" suddenly added here ?\n\nThere is no comment on this point in the code. \nCan you answer my confusion? Be deeply grateful.\n\nRegards & Thanks Adger\n\n\n \n\n\n\nHi hackers,    Recently, I noticed a great patch in pg 14.\"Rework planning and execution of UPDATE and DELETE. (86dc90056dfdbd9d1b891718d2e5614e3e432f35)\"This changes the DML execution of the partitioned table and makes it more friendly. But I am very confused about the following changes:```+           relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;+           if (relkind == RELKIND_RELATION ||+               relkind == RELKIND_MATVIEW ||+               relkind == RELKIND_PARTITIONED_TABLE)            {-               char        relkind;-               Datum       datum;-               bool        isNull;--               relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;-               if (relkind == RELKIND_RELATION || relkind == RELKIND_MATVIEW)-               {-                   datum = ExecGetJunkAttribute(slot,-                                                junkfilter->jf_junkAttNo,-                                                &isNull);-                   /* shouldn't ever get a null result... */```According to my understanding, the parent table of a partitioned table does not store any tuples. Then why is \"relkind = = RELKIND_PARTITIONED_TABLE\" suddenly added here ?There is no comment on this point in the code. Can you answer my confusion? Be deeply grateful.Regards & Thanks Adger", "msg_date": "Tue, 17 Aug 2021 11:56:33 +0800", "msg_from": "\"=?UTF-8?B?5p2O5p2wKOaFjui/vSk=?=\" <adger.lj@alibaba-inc.com>", "msg_from_op": true, "msg_subject": "=?UTF-8?B?QSBwcm9ibGVtIGluIEV4ZWNNb2RpZnlUYWJsZQ==?=" }, { "msg_contents": "On Tue, 17 Aug 2021 at 15:56, 李杰(慎追) <adger.lj@alibaba-inc.com> wrote:\n> According to my understanding, the parent table of a partitioned table does not store any tuples.\n> Then why is \"relkind = = RELKIND_PARTITIONED_TABLE\" suddenly added here ?\n\nWe'll need some sort of ResultRelInfo in the case that all partitions\nare pruned. Using the one for the partitioned table is convenient. I\nbelieve that's required if there are any statement-level triggers on\nthe partitioned table or if there's a RETURNING clause.\n\n> There is no comment on this point in the code.\n> Can you answer my confusion? Be deeply grateful.\n\nYeah maybe. It's not exactly close by, but one in grouping_planner\nmentions this:\n\n/*\n* We managed to exclude every child rel, so generate a\n* dummy one-relation plan using info for the top target\n* rel (even though that may not be a leaf target).\n* Although it's clear that no data will be updated or\n* deleted, we still need to have a ModifyTable node so\n* that any statement triggers will be executed. (This\n* could be cleaner if we fixed nodeModifyTable.c to allow\n* zero target relations, but that probably wouldn't be a\n* net win.)\n*/\n\nDavid\n\n\n", "msg_date": "Tue, 17 Aug 2021 17:41:16 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem in ExecModifyTable" }, { "msg_contents": "Hi, David\n\n Your answer explains that we still need to ModifyTable node without Leaf partitions.\n You are right about this.\n\n But you can review the source code again, \n ```\n /*\n * Fetch rows from subplan, and execute the required table modification\n * for each row. */\n for (;;) {\n ...\n /* No more tuples to process? */\n if (TupIsNull(planSlot)) break;\n\n ....\n/*\n * For UPDATE/DELETE, fetch the row identity info for the tuple to be\n * updated/deleted. For a heap relation, that's a TID; otherwise we\n * may have a wholerow junk attr that carries the old tuple in toto.\n * Keep this in step with the part of ExecInitModifyTable that sets up\n * ri_RowIdAttNo.\n */\n if (operation == CMD_UPDATE || operation == CMD_DELETE)\n {\n char relkind;\n Datum datum;\n bool isNull;\n relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;\n if (relkind == RELKIND_RELATION ||\n relkind == RELKIND_MATVIEW || relkind == RELKIND_PARTITIONED_TABLE)\n\n ...\n }\n\n ```\n We can see that if the scanned tuple is NULL, it will break.\n Therefore, this step will never be achieved that is to extract ctid.\n\n >We'll need some sort of ResultRelInfo in the case that all partitions\n >are pruned. \n\n In this case, the tuple returned should be null. \n\n >Using the one for the partitioned table is convenient. I\n >believe that's required if there are any statement-level triggers on\n >the partitioned table or if there's a RETURNING clause.\n\n If the tuple to be modified is null, you do not need to process RETURNING clause.\n statement-level triggers cannot use tuple, and triggers on partitioned tables cannot have transition tables.\n I set Assert(relkind! = RELKIND_PARTITIONED_TABLE); in the code, But it never arrives.\n\n Did I not understand your expression clearly?\n Could you provide me with a case to verify it? \n\n Thank you very much for your answer.\n \n Regards & Thanks Adger\n \n\n \n\n  Hi, David    Your answer explains that we still need to ModifyTable node without Leaf partitions.    You are right about this.             But you can review the source code again,          ```        /*         * Fetch rows from subplan, and execute the required table modification         * for each row.         */        for (;;)        {            ...            /* No more tuples to process? */            if (TupIsNull(planSlot))                break;            ....            /*              * For UPDATE/DELETE, fetch the row identity info for the tuple to be             * updated/deleted.  For a heap relation, that's a TID; otherwise we             * may have a wholerow junk attr that carries the old tuple in toto.             * Keep this in step with the part of ExecInitModifyTable that sets up             * ri_RowIdAttNo.             */            if (operation == CMD_UPDATE || operation == CMD_DELETE)            {                char        relkind;                Datum       datum;                bool        isNull;                relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;                if (relkind == RELKIND_RELATION ||                    relkind == RELKIND_MATVIEW ||                relkind == RELKIND_PARTITIONED_TABLE)        ...        }        ```        We can see that if the scanned tuple is NULL, it will break.        Therefore, this step will never be achieved that is to extract ctid.        >We'll need some sort of ResultRelInfo in the case that all partitions        >are pruned.            In this case, the tuple returned should be null.         >Using the one for the partitioned table is convenient.  I        >believe that's required if there are any statement-level triggers on        >the partitioned table or if there's a RETURNING clause.                 If the tuple to be modified is null, you do not need to process RETURNING clause.        statement-level triggers cannot use tuple, and triggers on partitioned tables cannot have transition tables.        I set Assert(relkind! = RELKIND_PARTITIONED_TABLE);  in the code, But it never arrives.        Did I not understand your expression clearly?         Could you provide me with a case to verify it?         Thank you very much for your answer.            Regards & Thanks Adger", "msg_date": "Tue, 17 Aug 2021 15:06:09 +0800", "msg_from": "\"=?UTF-8?B?5p2O5p2wKOaFjui/vSk=?=\" <adger.lj@alibaba-inc.com>", "msg_from_op": true, "msg_subject": "=?UTF-8?B?5Zue5aSN77yaQSBwcm9ibGVtIGluIEV4ZWNNb2RpZnlUYWJsZQ==?=" }, { "msg_contents": "On Tue, 17 Aug 2021 at 19:06, 李杰(慎追) <adger.lj@alibaba-inc.com> wrote:\n> Your answer explains that we still need to ModifyTable node without Leaf partitions.\n> You are right about this.\n>\n> But you can review the source code again,\n\nI'd been looking at the code in ExecInitModifyTable() that's the same\nas what you pasted thinking you meant that. I think for the check for\npartitioned tables in ExecModifyTable() then it's likely just dead\ncode. It seems to be causing a bit of confusion though, so might be\nworth doing something about. Copied in Tom to see what he thinks as\nit's one of his.\n\nDavid\n\n\n", "msg_date": "Tue, 17 Aug 2021 23:54:51 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem in ExecModifyTable" }, { "msg_contents": "David Rowley <dgrowleyml@gmail.com> writes:\n> I'd been looking at the code in ExecInitModifyTable() that's the same\n> as what you pasted thinking you meant that. I think for the check for\n> partitioned tables in ExecModifyTable() then it's likely just dead\n> code. It seems to be causing a bit of confusion though, so might be\n> worth doing something about. Copied in Tom to see what he thinks as\n> it's one of his.\n\nYeah, it's dead code in the sense that we should never reach these\nif-blocks with a partitioned table. I believe the reason I made it\nlike that is that the logic is concerned with which style of row identity\napplies to a particular relkind, and in the planner we treat partitioned\ntables as requiring this style of row identity, so that the right things\nhappen for their children. So the answer is basically \"for consistency\nwith add_row_identity_columns\".\n\nMaybe we could instead have add_row_identity_columns do nothing for\na partitioned table, but I'm unconvinced of that.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 17 Aug 2021 10:13:55 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: A problem in ExecModifyTable" } ]
[ { "msg_contents": "Hi\n\nI created some roles in extension. I will try to implement some security\nchecks. When I dropped this extension, the roles were not dropped.\n\nIs it expected behaviour?\n\nRegards\n\nPavel\n\nHiI created some roles in extension. I will try to implement some security checks.  When I dropped this extension, the roles were not dropped.Is it expected behaviour?RegardsPavel", "msg_date": "Tue, 17 Aug 2021 21:02:01 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": true, "msg_subject": "dependency between extension and roles" } ]
[ { "msg_contents": "Hello.\n\npg_veryfybackup can fail with a valid backup when the backup was taken\nfrom TLI > 1.\n\n=====\n# initdb\n$ pg_ctl start (just to make sure)\n$ pg_ctl stop\n$ touch $PGDATA/standby.signal\n$ pg_ctl start\n$ pg_ctl promote\n$ psql\npostgres=# select pg_switch_wal();\n pg_switch_wal \n---------------\n 0/14FE340\n(1 row)\npostgres=# checkpoint;\npostgres=# ^D\n$ pg_basebackup -Fp -h /tmp -D tmpbk\n$ pg_veryfybackup tmpbk\n(thinking.. thiking.. zzz.. for several seconds)\npg_waldump: fatal: could not find file \"000000020000000000000001\": No such file or directory\npg_verifybackup: error: WAL parsing failed for timeline 2\n=====\n\nThis is bacause the backup_manifest has the wrong values as below.\n\n> \"WAL-Ranges\": [\n> { \"Timeline\": 2, \"Start-LSN\": \"0/14FE248\", \"End-LSN\": \"0/3000100\" }\n> ],\n\nThe \"Start-LSN\" above is the beginning of timeline 2, not the\nbackup-start LSN. The segment had been removed by the checkpoint.\n\n\nThe comment for AddWALInfoToBackupManifest() says:\n> * Add information about the WAL that will need to be replayed when restoring\n> * this backup to the manifest.\n\nSo I concluded that it's a thinko.\n\nPlease see the attached. It needs to be back-patched to 13 but 13\ndoesn't accept the patch as is due to wording chages in TAP tests.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Wed, 18 Aug 2021 14:30:31 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": true, "msg_subject": "pg_veryfybackup can fail with a valid backup for TLI > 1" }, { "msg_contents": "On Wed, Aug 18, 2021 at 02:30:31PM +0900, Kyotaro Horiguchi wrote:\n> The \"Start-LSN\" above is the beginning of timeline 2, not the\n> backup-start LSN. The segment had been removed by the checkpoint.\n\nGood catch. That's broken, and I find cleaner the logic to compare\nthe TLI numbers rather than the start or end position of the TLI to\ncheck if a TLI should have a parent one.\n\n> The comment for AddWALInfoToBackupManifest() says:\n> > * Add information about the WAL that will need to be replayed when restoring\n> > * this backup to the manifest.\n\nYes, backup manifests include one array with all the timelines that\nrequire coverage. This case would only impact backups taken from\nstandbys, which have timeline jumps while the backup is taken with\nparent nodes promoted. That's easy enough to test with a chain of\nstandbys, some pgbench and pg_basebackup --max-rate to slow down the\nwhole. \n\n> So I concluded that it's a thinko.\n> \n> Please see the attached. It needs to be back-patched to 13 but 13\n> doesn't accept the patch as is due to wording chages in TAP tests.\n\n+ if (starttli == entry->tli)\n tl_beginptr = startptr;\n+ else\n+ {\n+ tl_beginptr = entry->begin;\n\nI would add a comment here. This does not need to be complicated,\nsay:\n\"If this timeline entry matches with the timeline on which the backup\nstarted, WAL needs to be checked from the start LSN of the backup. If\nthis entry refers to a newer timeline, WAL needs to be checked since\nthe beginning of this timeline, so use the LSN where the timeline\nbegan.\"\n\nThe TAP test is fancy, I like it. So let's keep it.\n\n+# base-backup runs a checkpoint but just to make sure.\n+$primary->safe_psql('postgres', 'SELECT pg_switch_wal();\nCHECKPOINT;');\nI don't think you need this part to get a failure as the checkpoint\nfrom the base backup will be sufficient.\n--\nMichael", "msg_date": "Thu, 19 Aug 2021 15:51:38 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: pg_veryfybackup can fail with a valid backup for TLI > 1" }, { "msg_contents": "Thank you for the comment.\n\nAt Thu, 19 Aug 2021 15:51:38 +0900, Michael Paquier <michael@paquier.xyz> wrote in \n> On Wed, Aug 18, 2021 at 02:30:31PM +0900, Kyotaro Horiguchi wrote:\n> > The \"Start-LSN\" above is the beginning of timeline 2, not the\n> > backup-start LSN. The segment had been removed by the checkpoint.\n> \n> Good catch. That's broken, and I find cleaner the logic to compare\n> the TLI numbers rather than the start or end position of the TLI to\n> check if a TLI should have a parent one.\n> \n> > The comment for AddWALInfoToBackupManifest() says:\n> > > * Add information about the WAL that will need to be replayed when restoring\n> > > * this backup to the manifest.\n> \n> Yes, backup manifests include one array with all the timelines that\n> require coverage. This case would only impact backups taken from\n> standbys, which have timeline jumps while the backup is taken with\n> parent nodes promoted. That's easy enough to test with a chain of\n> standbys, some pgbench and pg_basebackup --max-rate to slow down the\n> whole. \n\n(I was very annoyed that pg_basbackup responds to --max-rate=1 only by\n\"out of range\" without informing of the valid range..)\n\nThat's looks like a domino falling. I had the following result, which\nlooks fine.\n\n\"WAL-Ranges\": [\n{ \"Timeline\": 6, \"Start-LSN\": \"0/630C7E8\", \"End-LSN\": \"0/630C850\" },\n{ \"Timeline\": 5, \"Start-LSN\": \"0/630C780\", \"End-LSN\": \"0/630C7E8\" },\n{ \"Timeline\": 4, \"Start-LSN\": \"0/630C718\", \"End-LSN\": \"0/630C780\" },\n{ \"Timeline\": 3, \"Start-LSN\": \"0/630C6B0\", \"End-LSN\": \"0/630C718\" },\n{ \"Timeline\": 2, \"Start-LSN\": \"0/5000028\", \"End-LSN\": \"0/630C6B0\" }\n],\n\n00000006.history:\n1\t0/173F268\tno recovery target specified\n2\t0/630C6B0\tno recovery target specified\n3\t0/630C718\tno recovery target specified\n4\t0/630C780\tno recovery target specified\n5\t0/630C7E8\tno recovery target specified\n\n> > So I concluded that it's a thinko.\n> > \n> > Please see the attached. It needs to be back-patched to 13 but 13\n> > doesn't accept the patch as is due to wording chages in TAP tests.\n> \n> + if (starttli == entry->tli)\n> tl_beginptr = startptr;\n> + else\n> + {\n> + tl_beginptr = entry->begin;\n> \n> I would add a comment here. This does not need to be complicated,\n> say:\n> \"If this timeline entry matches with the timeline on which the backup\n> started, WAL needs to be checked from the start LSN of the backup. If\n> this entry refers to a newer timeline, WAL needs to be checked since\n> the beginning of this timeline, so use the LSN where the timeline\n> began.\"\n\nThanks for your help! I wanted to write something like that\nthere. Added it as-is.\n\n> The TAP test is fancy, I like it. So let's keep it.\n> \n> +# base-backup runs a checkpoint but just to make sure.\n> +$primary->safe_psql('postgres', 'SELECT pg_switch_wal();\n> CHECKPOINT;');\n> I don't think you need this part to get a failure as the checkpoint\n> from the base backup will be sufficient.\n\nYes, it is just redandunt as (I tried to) said in the comment. (I\nmeant by the \"just to make sure\" \"just to let readers of the test code\nnotice that a checkpoint is crucial there\", but it doesn't seem\nworking:() Instead, I added a comment just before pg_basebackup.\n\n# base-backup below runs a checkpoint, which removes the first segment\n# of the current timeline\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Fri, 20 Aug 2021 15:33:37 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": true, "msg_subject": "Re: pg_veryfybackup can fail with a valid backup for TLI > 1" }, { "msg_contents": "On Fri, Aug 20, 2021 at 03:33:37PM +0900, Kyotaro Horiguchi wrote:\n> That's looks like a domino falling. I had the following result, which\n> looks fine.\n> \n> \"WAL-Ranges\": [\n> { \"Timeline\": 6, \"Start-LSN\": \"0/630C7E8\", \"End-LSN\": \"0/630C850\" },\n> { \"Timeline\": 5, \"Start-LSN\": \"0/630C780\", \"End-LSN\": \"0/630C7E8\" },\n> { \"Timeline\": 4, \"Start-LSN\": \"0/630C718\", \"End-LSN\": \"0/630C780\" },\n> { \"Timeline\": 3, \"Start-LSN\": \"0/630C6B0\", \"End-LSN\": \"0/630C718\" },\n> { \"Timeline\": 2, \"Start-LSN\": \"0/5000028\", \"End-LSN\": \"0/630C6B0\" }\n> ],\n> \n> 00000006.history:\n> 1\t0/173F268\tno recovery target specified\n> 2\t0/630C6B0\tno recovery target specified\n> 3\t0/630C718\tno recovery target specified\n> 4\t0/630C780\tno recovery target specified\n> 5\t0/630C7E8\tno recovery target specified\n\nAnd your backup_label shows 0/5000028 as start LSN for the backup,\nright? I see the same result.\n--\nMichael", "msg_date": "Fri, 20 Aug 2021 16:23:56 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: pg_veryfybackup can fail with a valid backup for TLI > 1" }, { "msg_contents": "At Fri, 20 Aug 2021 16:23:56 +0900, Michael Paquier <michael@paquier.xyz> wrote in \n> On Fri, Aug 20, 2021 at 03:33:37PM +0900, Kyotaro Horiguchi wrote:\n> > That's looks like a domino falling. I had the following result, which\n> > looks fine.\n> > \n> > \"WAL-Ranges\": [\n> > { \"Timeline\": 6, \"Start-LSN\": \"0/630C7E8\", \"End-LSN\": \"0/630C850\" },\n> > { \"Timeline\": 5, \"Start-LSN\": \"0/630C780\", \"End-LSN\": \"0/630C7E8\" },\n> > { \"Timeline\": 4, \"Start-LSN\": \"0/630C718\", \"End-LSN\": \"0/630C780\" },\n> > { \"Timeline\": 3, \"Start-LSN\": \"0/630C6B0\", \"End-LSN\": \"0/630C718\" },\n> > { \"Timeline\": 2, \"Start-LSN\": \"0/5000028\", \"End-LSN\": \"0/630C6B0\" }\n> > ],\n> > \n> > 00000006.history:\n> > 1\t0/173F268\tno recovery target specified\n> > 2\t0/630C6B0\tno recovery target specified\n> > 3\t0/630C718\tno recovery target specified\n> > 4\t0/630C780\tno recovery target specified\n> > 5\t0/630C7E8\tno recovery target specified\n> \n> And your backup_label shows 0/5000028 as start LSN for the backup,\n> right? I see the same result.\n\nYes, backup_label looks correct.\n\nbackup_label (extract):\nSTART WAL LOCATION: 0/5000028 (file 000000020000000000000005)\nCHECKPOINT LOCATION: 0/5000060\nSTART TIMELINE: 2\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 20 Aug 2021 16:47:15 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": true, "msg_subject": "Re: pg_veryfybackup can fail with a valid backup for TLI > 1" }, { "msg_contents": "On Fri, Aug 20, 2021 at 04:47:15PM +0900, Kyotaro Horiguchi wrote:\n> Yes, backup_label looks correct.\n> \n> backup_label (extract):\n> START WAL LOCATION: 0/5000028 (file 000000020000000000000005)\n> CHECKPOINT LOCATION: 0/5000060\n> START TIMELINE: 2\n\nOkay. I have worked on that today, did more manual tests, and applied\nthis fix down to 13. The cherry-pick from 14 to 13 only required a\ns/$master/$primary/ in the test, which was straight-forward. Your\npatch for 13 did that though:\n- if (starttli != entry->tli)\n+ if (!XLogRecPtrIsInvalid(entry->begin))\n\nSo it would have caused a failure with parent TLIs that have a correct\nbegin location, but we expect the opposite. The patch for 14/HEAD had\nthat right.\n--\nMichael", "msg_date": "Mon, 23 Aug 2021 15:46:37 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: pg_veryfybackup can fail with a valid backup for TLI > 1" }, { "msg_contents": "At Mon, 23 Aug 2021 15:46:37 +0900, Michael Paquier <michael@paquier.xyz> wrote in \n> On Fri, Aug 20, 2021 at 04:47:15PM +0900, Kyotaro Horiguchi wrote:\n> > Yes, backup_label looks correct.\n> > \n> > backup_label (extract):\n> > START WAL LOCATION: 0/5000028 (file 000000020000000000000005)\n> > CHECKPOINT LOCATION: 0/5000060\n> > START TIMELINE: 2\n> \n> Okay. I have worked on that today, did more manual tests, and applied\n> this fix down to 13. The cherry-pick from 14 to 13 only required a\n> s/$master/$primary/ in the test, which was straight-forward. Your\n> patch for 13 did that though:\n> - if (starttli != entry->tli)\n> + if (!XLogRecPtrIsInvalid(entry->begin))\n> \n> So it would have caused a failure with parent TLIs that have a correct\n> begin location, but we expect the opposite. The patch for 14/HEAD had\n> that right.\n\nMmm. Sorry for the silly mistake, and thanks for commiting this!\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Mon, 23 Aug 2021 16:09:04 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": true, "msg_subject": "Re: pg_veryfybackup can fail with a valid backup for TLI > 1" } ]
[ { "msg_contents": "The attached fixes s/atleast/at least/ in the logical decoding examples\nsection in the docs, will push in a bit.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/", "msg_date": "Wed, 18 Aug 2021 11:38:44 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": true, "msg_subject": "Small typo fix in logical decoding example" } ]
[ { "msg_contents": "Hello dear hackers. I understand the position of the developers community\nabout NAMEDATALEN length - and, in fact, 63 bytes is more than enough - but\nonly if we speak about latin languages.\n\nPostgresql has wonderful support for unicode in table and column names. And\nit looks like very good idea to create table with names on native language\nfor databases across the world. But when I want to create, for example,\ntable with name \"Catalog_Контрагенты_КонтактнаяИнформация\" (that stands in\nRussian for catalog of counteragent contacts) it will be auto-shrinked to\n\"Catalog_Контрагенты_КонтактнаяИнформ\". And this is not a fictional problem\n- many words in Russian are just longer than it's English counterparts and\nI have many examples like this.\n\nAlthough recompiling the source is not so hard, updating is hard. I know\nthat is not free for disk space because of storing table names and field\nnames but, from my point of view, in 2021 year convenience is more\nimportant than disk space.\n\nI ask you to consider increasing NAMEDATALEN for maybe 128 bytes in future\nreleases.\n\nSorry for wasted time for this message if this topic is not match with\ndirection of postgresql development (and thank you for your hard work)\n\nHello dear hackers. I understand the position of the developers community about NAMEDATALEN length - and, in fact, 63 bytes is more than enough - but only if we speak about latin languages. Postgresql has wonderful support for unicode in table and column names. And it looks like very good idea to create table with names on native language for databases across the world. But when I want to create, for example, table with name \"Catalog_Контрагенты_КонтактнаяИнформация\" (that stands in Russian for catalog of counteragent contacts) it will be auto-shrinked to \"Catalog_Контрагенты_КонтактнаяИнформ\". And this is not a fictional problem - many words in Russian are just longer than it's English counterparts and I have many examples like this.Although recompiling the source is not so hard, updating is hard. I know that is not free for disk space because of storing table names and field names but, from my point of view, in 2021 year convenience is more important than disk space. I ask you to consider increasing NAMEDATALEN for maybe 128 bytes in future releases. Sorry for wasted time for this message if this topic is not match with direction of postgresql development (and thank you for your hard work)", "msg_date": "Wed, 18 Aug 2021 18:07:46 +0700", "msg_from": "=?UTF-8?B?0JTQtdC90LjRgSDQoNC+0LzQsNC90LXQvdC60L4=?=\n <deromanenko@gmail.com>", "msg_from_op": true, "msg_subject": "NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Wed, Aug 18, 2021 at 7:08 PM Денис Романенко <deromanenko@gmail.com> wrote:\n>\n> Hello dear hackers. I understand the position of the developers community about NAMEDATALEN length - and, in fact, 63 bytes is more than enough - but only if we speak about latin languages.\n>\n> Postgresql has wonderful support for unicode in table and column names. And it looks like very good idea to create table with names on native language for databases across the world. But when I want to create, for example, table with name \"Catalog_Контрагенты_КонтактнаяИнформация\" (that stands in Russian for catalog of counteragent contacts) it will be auto-shrinked to \"Catalog_Контрагенты_КонтактнаяИнформ\". And this is not a fictional problem - many words in Russian are just longer than it's English counterparts and I have many examples like this.\n>\n> Although recompiling the source is not so hard, updating is hard. I know that is not free for disk space because of storing table names and field names but, from my point of view, in 2021 year convenience is more important than disk space.\n\nUnfortunately, the problem isn't really the additional disk space it\nwould require. The problem is the additional performance hit and\nmemory overhead, as the catalog names are part of the internal\nsyscache.\n\nI understand your frustration, but given those problems I don't think\nthat postgres will increase the default NAMEDATALEN value any time\nsoon, even though it's in contradiction with the SQL standard.\n\n\n", "msg_date": "Wed, 18 Aug 2021 19:15:37 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Em qua., 18 de ago. de 2021 às 08:08, Денис Романенко <deromanenko@gmail.com>\nescreveu:\n\n> Hello dear hackers. I understand the position of the developers community\n> about NAMEDATALEN length - and, in fact, 63 bytes is more than enough - but\n> only if we speak about latin languages.\n>\n> Postgresql has wonderful support for unicode in table and column names.\n> And it looks like very good idea to create table with names on native\n> language for databases across the world. But when I want to create, for\n> example, table with name \"Catalog_Контрагенты_КонтактнаяИнформация\" (that\n> stands in Russian for catalog of counteragent contacts) it will be\n> auto-shrinked to \"Catalog_Контрагенты_КонтактнаяИнформ\". And this is not a\n> fictional problem - many words in Russian are just longer than it's English\n> counterparts and I have many examples like this.\n>\n> Although recompiling the source is not so hard, updating is hard. I know\n> that is not free for disk space because of storing table names and field\n> names but, from my point of view, in 2021 year convenience is more\n> important than disk space.\n>\n> I ask you to consider increasing NAMEDATALEN for maybe 128 bytes in future\n> releases.\n>\n+1 once that Oracle Database 12.2 and higher, has support for 128 bytes\nnames.\nWhat possibly, in the future, could impact some migration from Oracle to\nPostgres.\n\nregards,\nRanier Vilela\n\nEm qua., 18 de ago. de 2021 às 08:08, Денис Романенко <deromanenko@gmail.com> escreveu:Hello dear hackers. I understand the position of the developers community about NAMEDATALEN length - and, in fact, 63 bytes is more than enough - but only if we speak about latin languages. Postgresql has wonderful support for unicode in table and column names. And it looks like very good idea to create table with names on native language for databases across the world. But when I want to create, for example, table with name \"Catalog_Контрагенты_КонтактнаяИнформация\" (that stands in Russian for catalog of counteragent contacts) it will be auto-shrinked to \"Catalog_Контрагенты_КонтактнаяИнформ\". And this is not a fictional problem - many words in Russian are just longer than it's English counterparts and I have many examples like this.Although recompiling the source is not so hard, updating is hard. I know that is not free for disk space because of storing table names and field names but, from my point of view, in 2021 year convenience is more important than disk space. I ask you to consider increasing NAMEDATALEN for maybe 128 bytes in future releases. +1 once that Oracle Database 12.2 and higher, has support for 128 bytes names.What possibly, in the future, could impact some migration from Oracle to Postgres.regards,Ranier Vilela", "msg_date": "Wed, 18 Aug 2021 08:16:52 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Wed, Aug 18, 2021 at 7:15 AM Julien Rouhaud <rjuju123@gmail.com> wrote:\n>\n> Unfortunately, the problem isn't really the additional disk space it\n> would require. The problem is the additional performance hit and\n> memory overhead, as the catalog names are part of the internal\n> syscache.\n\nSome actual numbers on recent hardware would show what kind of tradeoff is\ninvolved. No one has done that for a long time that I recall.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Wed, Aug 18, 2021 at 7:15 AM Julien Rouhaud <rjuju123@gmail.com> wrote:>> Unfortunately, the problem isn't really the additional disk space it> would require.  The problem is the additional performance hit and> memory overhead, as the catalog names are part of the internal> syscache.Some actual numbers on recent hardware would show what kind of tradeoff is involved. No one has done that for a long time that I recall.--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Wed, 18 Aug 2021 07:27:42 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Wed, Aug 18, 2021 at 7:27 PM John Naylor\n<john.naylor@enterprisedb.com> wrote:\n>\n> On Wed, Aug 18, 2021 at 7:15 AM Julien Rouhaud <rjuju123@gmail.com> wrote:\n> >\n> > Unfortunately, the problem isn't really the additional disk space it\n> > would require. The problem is the additional performance hit and\n> > memory overhead, as the catalog names are part of the internal\n> > syscache.\n>\n> Some actual numbers on recent hardware would show what kind of tradeoff is involved. No one has done that for a long time that I recall.\n\nAgreed, but I don't have access to such hardware. However this won't\ninfluence the memory overhead part, and there is already frequent\nproblems with that, especially since declarative partitioning, so I\ndon't see how we could afford that without some kind of cache TTL or\nsimilar. AFAIR the last discussion about it a few years ago didn't\nlead anywhere :(\n\n\n", "msg_date": "Wed, 18 Aug 2021 19:33:34 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Could we just make the limitation to be 64 (or 128) _characters_ not _bytes_ ?\n\nMemory sizes and processor speeds have grown by order(s) of magnitude\nsince the 64 byte limit was decided and supporting non-ASCII charsets\nproperly seems like a prudent thing to do.\n\nAlso - have we checked that at least the truncation does not cut utf-8\ncharacters in half ?\n\n-----\nHannu Krosing\nGoogle Cloud - We have a long list of planned contributions and we are hiring.\nContact me if interested.\n\nOn Wed, Aug 18, 2021 at 1:33 PM Julien Rouhaud <rjuju123@gmail.com> wrote:\n>\n> On Wed, Aug 18, 2021 at 7:27 PM John Naylor\n> <john.naylor@enterprisedb.com> wrote:\n> >\n> > On Wed, Aug 18, 2021 at 7:15 AM Julien Rouhaud <rjuju123@gmail.com> wrote:\n> > >\n> > > Unfortunately, the problem isn't really the additional disk space it\n> > > would require. The problem is the additional performance hit and\n> > > memory overhead, as the catalog names are part of the internal\n> > > syscache.\n> >\n> > Some actual numbers on recent hardware would show what kind of tradeoff is involved. No one has done that for a long time that I recall.\n>\n> Agreed, but I don't have access to such hardware. However this won't\n> influence the memory overhead part, and there is already frequent\n> problems with that, especially since declarative partitioning, so I\n> don't see how we could afford that without some kind of cache TTL or\n> similar. AFAIR the last discussion about it a few years ago didn't\n> lead anywhere :(\n>\n>\n\n\n", "msg_date": "Wed, 18 Aug 2021 14:03:21 +0200", "msg_from": "Hannu Krosing <hannuk@google.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Wed, Aug 18, 2021 at 7:33 AM Julien Rouhaud <rjuju123@gmail.com> wrote:\n> > Some actual numbers on recent hardware would show what kind of tradeoff\nis involved. No one has done that for a long time that I recall.\n>\n> Agreed, but I don't have access to such hardware. However this won't\n\nWell, by \"recent\" I had in mind something more recent than 2002, which is\nthe time where I see a lot of hits in the archives if you search for this\ntopic.\n\n> influence the memory overhead part, and there is already frequent\n> problems with that, especially since declarative partitioning, so I\n\nThat's a fair point.\n\n> don't see how we could afford that without some kind of cache TTL or\n> similar. AFAIR the last discussion about it a few years ago didn't\n> lead anywhere :(\n\nIf you mean the thread \"Protect syscache from bloating with negative cache\nentries\", it had activity earlier this year, so I wouldn't give up hope\njust yet. Progress has been slow, so I'll see about putting some effort\ninto that after concluding my attempt to speed up the syscaches first [1].\n\nThe main thing I'm worried about is the fact that a name would no longer\nfit in a Datum. The rest I think we can mitigate in some way.\n\n[1]\nhttps://www.postgresql.org/message-id/CAFBsxsE35VLJ3hHkjJARB3QWqJ0zWeDw-jzqrfzkzMPuD_Ctvw@mail.gmail.com\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Wed, Aug 18, 2021 at 7:33 AM Julien Rouhaud <rjuju123@gmail.com> wrote:> > Some actual numbers on recent hardware would show what kind of tradeoff is involved. No one has done that for a long time that I recall.>> Agreed, but I don't have access to such hardware.  However this won'tWell, by \"recent\" I had in mind something more recent than 2002, which is the time where I see a lot of hits in the archives if you search for this topic.> influence the memory overhead part, and there is already frequent> problems with that, especially since declarative partitioning, so IThat's a fair point.> don't see how we could afford that without some kind of cache TTL or> similar.  AFAIR the last discussion about it a few years ago didn't> lead anywhere :(If you mean the thread \"Protect syscache from bloating with negative cache entries\", it had activity earlier this year, so I wouldn't give up hope just yet. Progress has been slow, so I'll see about putting some effort into that after concluding my attempt to speed up the syscaches first [1].The main thing I'm worried about is the fact that a name would no longer fit in a Datum. The rest I think we can mitigate in some way.[1] https://www.postgresql.org/message-id/CAFBsxsE35VLJ3hHkjJARB3QWqJ0zWeDw-jzqrfzkzMPuD_Ctvw@mail.gmail.com--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Wed, 18 Aug 2021 08:04:06 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Wed, Aug 18, 2021 at 8:03 AM Hannu Krosing <hannuk@google.com> wrote:\n>\n> Could we just make the limitation to be 64 (or 128) _characters_ not\n_bytes_ ?\n\nThat couldn't work because characters are variable length. The limit has to\nbe a fixed length in bytes so we can quickly compute offsets in the\nattribute tuple.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Wed, Aug 18, 2021 at 8:03 AM Hannu Krosing <hannuk@google.com> wrote:>> Could we just make the limitation to be 64 (or 128) _characters_ not _bytes_ ?That couldn't work because characters are variable length. The limit has to be a fixed length in bytes so we can quickly compute offsets in the attribute tuple.--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Wed, 18 Aug 2021 08:07:23 -0400", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Wed, Aug 18, 2021 at 8:04 PM John Naylor\n<john.naylor@enterprisedb.com> wrote:\n>\n> >\n> > Agreed, but I don't have access to such hardware. However this won't\n>\n> Well, by \"recent\" I had in mind something more recent than 2002, which is the time where I see a lot of hits in the archives if you search for this topic.\n\nYeah, but my current laptop has a tendency to crash after a few minute\nif I stress it too much, so I'm still out.\n\n> If you mean the thread \"Protect syscache from bloating with negative cache entries\", it had activity earlier this year, so I wouldn't give up hope just yet.\n\nYes that's the thread I was thinking about. I'm not giving up hope\neither, but I also don't see it being solved for v15.\n\n> The main thing I'm worried about is the fact that a name would no longer fit in a Datum. The rest I think we can mitigate in some way.\n\nAgreed.\n\n\n", "msg_date": "Wed, 18 Aug 2021 20:20:08 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Wed, Aug 18, 2021 at 8:03 PM Hannu Krosing <hannuk@google.com> wrote:\n>\n> Also - have we checked that at least the truncation does not cut utf-8\n> characters in half ?\n\nYes, same for all other places that can truncate text (like the query\ntext in pg_stat_activity and similar). See usage of pg_mbcliplen() in\ntruncate_identifier.\n\n\n", "msg_date": "Wed, 18 Aug 2021 20:28:09 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Wed, 2021-08-18 at 08:16 -0300, Ranier Vilela wrote:\n> Em qua., 18 de ago. de 2021 às 08:08, Денис Романенко <deromanenko@gmail.com> escreveu:\n> > Hello dear hackers. I understand the position of the developers community about\n> > NAMEDATALEN length - and, in fact, 63 bytes is more than enough - but only if we\n> > speak about latin languages. \n> > \n> > Postgresql has wonderful support for unicode in table and column names. And it\n> > looks like very good idea to create table with names on native language for\n> > databases across the world. But when I want to create, for example, table with\n> > name \"Catalog_Контрагенты_КонтактнаяИнформация\" (that stands in Russian for\n> > catalog of counteragent contacts) it will be auto-shrinked to\n> > \"Catalog_Контрагенты_КонтактнаяИнформ\". And this is not a fictional problem -\n> > many words in Russian are just longer than it's English counterparts and I\n> > have many examples like this.\n> > \n> > Although recompiling the source is not so hard, updating is hard. I know that\n> > is not free for disk space because of storing table names and field names but,\n> > from my point of view, in 2021 year convenience is more important than disk space. \n> > \n> > I ask you to consider increasing NAMEDATALEN for maybe 128 bytes in future releases. \n\nMy stance here is that you should always use ASCII only for database identifiers,\nnot only because of this, but also to avoid unpleasant encoding problems if\nyou want to do something like\n\n pg_dump -t Catalog_Контрагенты_КонтактнаяИнформация mydb\n\non a shell with an encoding different from the database encoding.\n\nSo I am not too excited about this.\n\n> +1 once that Oracle Database 12.2 and higher, has support for 128 bytes names.\n> What possibly, in the future, could impact some migration from Oracle to Postgres.\n\nThat seems to be a better argument from my point of view.\n\nI have no idea as to how bad the additional memory impact for the catalog\ncaches would be...\n\nYours,\nLaurenz Albe\n\n\n\n", "msg_date": "Wed, 18 Aug 2021 14:33:08 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Em qua., 18 de ago. de 2021 às 09:33, Laurenz Albe <laurenz.albe@cybertec.at>\nescreveu:\n\n> On Wed, 2021-08-18 at 08:16 -0300, Ranier Vilela wrote:\n> > Em qua., 18 de ago. de 2021 às 08:08, Денис Романенко <\n> deromanenko@gmail.com> escreveu:\n> > > Hello dear hackers. I understand the position of the developers\n> community about\n> > > NAMEDATALEN length - and, in fact, 63 bytes is more than enough - but\n> only if we\n> > > speak about latin languages.\n> > >\n> > > Postgresql has wonderful support for unicode in table and column\n> names. And it\n> > > looks like very good idea to create table with names on native\n> language for\n> > > databases across the world. But when I want to create, for example,\n> table with\n> > > name \"Catalog_Контрагенты_КонтактнаяИнформация\" (that stands in\n> Russian for\n> > > catalog of counteragent contacts) it will be auto-shrinked to\n> > > \"Catalog_Контрагенты_КонтактнаяИнформ\". And this is not a fictional\n> problem -\n> > > many words in Russian are just longer than it's English counterparts\n> and I\n> > > have many examples like this.\n> > >\n> > > Although recompiling the source is not so hard, updating is hard. I\n> know that\n> > > is not free for disk space because of storing table names and field\n> names but,\n> > > from my point of view, in 2021 year convenience is more important\n> than disk space.\n> > >\n> > > I ask you to consider increasing NAMEDATALEN for maybe 128 bytes in\n> future releases.\n>\n> My stance here is that you should always use ASCII only for database\n> identifiers,\n> not only because of this, but also to avoid unpleasant encoding problems if\n> you want to do something like\n>\n> pg_dump -t Catalog_Контрагенты_КонтактнаяИнформация mydb\n>\n> on a shell with an encoding different from the database encoding.\n>\n> So I am not too excited about this.\n>\n> > +1 once that Oracle Database 12.2 and higher, has support for 128 bytes\n> names.\n> > What possibly, in the future, could impact some migration from Oracle to\n> Postgres.\n>\n> That seems to be a better argument from my point of view.\n>\n> I have no idea as to how bad the additional memory impact for the catalog\n> caches would be...\n>\nIt seems to me that this is a case for macro:\nHAS_SUPPORT_NAME_128_BYTES\nДеnis Романенко would like and would pay the price for regression in\nexchange for the convenience.\nWhat impacts him now is the difficulty of maintaining a private tree, with\nthis support.\n\nregards,\nRanier Vilela\n\nEm qua., 18 de ago. de 2021 às 09:33, Laurenz Albe <laurenz.albe@cybertec.at> escreveu:On Wed, 2021-08-18 at 08:16 -0300, Ranier Vilela wrote:\n> Em qua., 18 de ago. de 2021 às 08:08, Денис Романенко <deromanenko@gmail.com> escreveu:\n> > Hello dear hackers. I understand the position of the developers community about\n> >  NAMEDATALEN length - and, in fact, 63 bytes is more than enough - but only if we\n> >  speak about latin languages. \n> > \n> > Postgresql has wonderful support for unicode in table and column names. And it\n> >  looks like very good idea to create table with names on native language for\n> >  databases across the world. But when I want to create, for example, table with\n> >  name \"Catalog_Контрагенты_КонтактнаяИнформация\" (that stands in Russian for\n> >  catalog of counteragent contacts) it will be auto-shrinked to\n> >  \"Catalog_Контрагенты_КонтактнаяИнформ\". And this is not a fictional problem -\n> >  many words in Russian are just longer than it's English counterparts and I\n> >  have many examples like this.\n> > \n> > Although recompiling the source is not so hard, updating is hard. I know that\n> >  is not free for disk space because of storing table names and field names but,\n> >  from my point of view, in 2021 year convenience is more important than disk space. \n> > \n> > I ask you to consider increasing NAMEDATALEN for maybe 128 bytes in future releases. \n\nMy stance here is that you should always use ASCII only for database identifiers,\nnot only because of this, but also to avoid unpleasant encoding problems if\nyou want to do something like\n\n pg_dump -t Catalog_Контрагенты_КонтактнаяИнформация mydb\n\non a shell with an encoding different from the database encoding.\n\nSo I am not too excited about this.\n\n> +1 once that Oracle Database 12.2 and higher, has support for 128 bytes names.\n> What possibly, in the future, could impact some migration from Oracle to Postgres.\n\nThat seems to be a better argument from my point of view.\n\nI have no idea as to how bad the additional memory impact for the catalog\ncaches would be...It seems to me that this is a case for macro:HAS_SUPPORT_NAME_128_BYTESДеnis Романенко would like and would pay the price for regression in exchange for the convenience.What impacts him now is the difficulty of maintaining a private tree, with this support.regards,Ranier Vilela", "msg_date": "Wed, 18 Aug 2021 10:06:12 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "John Naylor <john.naylor@enterprisedb.com> writes:\n> The main thing I'm worried about is the fact that a name would no longer\n> fit in a Datum. The rest I think we can mitigate in some way.\n\nNot sure what you mean by that? name is a pass-by-ref data type.\n\nAnyway, this whole argument could be rendered moot if we could convert\nname to a variable-length type. That would satisfy *both* sides of\nthe argument, since those who need long names could have them, while\nthose who don't would see net reduction instead of growth in space usage.\n\nOf course, this is far far easier said than done; else we would have\ndone it years ago. But maybe it's not entirely out of reach.\nI do not think it'd be hard to change \"name\" to have the same on-disk\nstorage representation as cstring; the hard part is what about its\nusage in fixed-width catalog structures. Maybe we could finesse that\nby decreeing that the name column always has to be the last\nnon-CATALOG_VARLEN field. (This would require fixing up the couple of\nplaces where we let some other var-width field have that distinction;\nbut I suspect that would be small in comparison to the other work this\nimplies. If there are any catalogs having two name columns, one of them\nwould become more difficult to reach from C code.)\n\nAnother fun thing --- and, I fear, another good argument against just\nraising NAMEDATALEN --- is what about TupleDescs, which last I checked\nused an array of fixed-width pg_attribute images. But maybe we could\nreplace that with an array of pointers. Andres already did a lot of\nthe heavy code churn required to hide that data structure behind\nTupleDescAttr() macros, so changing the representation should be much\nless painful than it would once have been.\n\nI wonder if we'd get complaints from changing the catalog column layouts\nthat much. People are used to the name at the front, I think. OTOH,\nI expected a lot of bleating about the OID column becoming frontmost,\nbut there hasn't been much.\n\nAnyway, I have little desire to work on this myself, but I recommend that\nsomebody who is more affected by the name length restriction look into it.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 18 Aug 2021 10:21:03 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Wed, Aug 18, 2021 at 10:21 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Anyway, this whole argument could be rendered moot if we could convert\n> name to a variable-length type. That would satisfy *both* sides of\n> the argument, since those who need long names could have them, while\n> those who don't would see net reduction instead of growth in space usage.\n\nYeah it seems like the best way forward.\n\n> Of course, this is far far easier said than done; else we would have\n> done it years ago. But maybe it's not entirely out of reach.\n> I do not think it'd be hard to change \"name\" to have the same on-disk\n> storage representation as cstring; the hard part is what about its\n> usage in fixed-width catalog structures. Maybe we could finesse that\n> by decreeing that the name column always has to be the last\n> non-CATALOG_VARLEN field. (This would require fixing up the couple of\n> places where we let some other var-width field have that distinction;\n> but I suspect that would be small in comparison to the other work this\n> implies. If there are any catalogs having two name columns, one of them\n> would become more difficult to reach from C code.)\n\nHere is the list on some recent build (as of 17707c059c):\n\n relname | array_agg\n------------------+----------------------------------\n pg_collation | {collname,collctype,collcollate}\n pg_database | {datctype,datcollate,datname}\n pg_event_trigger | {evtevent,evtname}\n pg_subscription | {subname,subslotname}\n pg_trigger | {tgname,tgnewtable,tgoldtable}\n(5 rows)\n\n> I wonder if we'd get complaints from changing the catalog column layouts\n> that much. People are used to the name at the front, I think. OTOH,\n> I expected a lot of bleating about the OID column becoming frontmost,\n> but there hasn't been much.\n\nI don't think that would be comparable. Having an extra oid in the\n1st column doesn't really make a raw SELECT * harder to read. But\nhaving the XXXname column way behind, and not even at the end, means\nthat most people will have to type an extra \"xxxname,\" for each\nthrowaway query run to quickly verify something. I know that I often\ndo that, and while I could live with it I'd rather not have to do it.\n\n\n", "msg_date": "Wed, 18 Aug 2021 22:41:43 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On 18.08.21 13:33, Julien Rouhaud wrote:\n> Agreed, but I don't have access to such hardware. However this won't\n> influence the memory overhead part, and there is already frequent\n> problems with that, especially since declarative partitioning,\n\nOn the flip side, with partitioning you need room for longer table \nnames, since you need room for the real name plus some partition identifier.\n\n\n", "msg_date": "Wed, 18 Aug 2021 16:43:23 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Julien Rouhaud <rjuju123@gmail.com> writes:\n> On Wed, Aug 18, 2021 at 10:21 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> I wonder if we'd get complaints from changing the catalog column layouts\n>> that much. People are used to the name at the front, I think. OTOH,\n>> I expected a lot of bleating about the OID column becoming frontmost,\n>> but there hasn't been much.\n\n> I don't think that would be comparable. Having an extra oid in the\n> 1st column doesn't really make a raw SELECT * harder to read. But\n> having the XXXname column way behind, and not even at the end, means\n> that most people will have to type an extra \"xxxname,\" for each\n> throwaway query run to quickly verify something. I know that I often\n> do that, and while I could live with it I'd rather not have to do it.\n\nYeah, it would annoy the heck out of me too. Again there's a potential\ntechnical solution, which is to decouple the user-visible column order\nfrom the storage order. However, multiple people have tilted at that\nwindmill without much success, so making it a prerequisite for improving\nthe name-length situation doesn't seem like a smart plan.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 18 Aug 2021 10:53:58 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "\nOn 8/18/21 10:53 AM, Tom Lane wrote:\n> Julien Rouhaud <rjuju123@gmail.com> writes:\n>> On Wed, Aug 18, 2021 at 10:21 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>>> I wonder if we'd get complaints from changing the catalog column layouts\n>>> that much. People are used to the name at the front, I think. OTOH,\n>>> I expected a lot of bleating about the OID column becoming frontmost,\n>>> but there hasn't been much.\n>> I don't think that would be comparable. Having an extra oid in the\n>> 1st column doesn't really make a raw SELECT * harder to read. But\n>> having the XXXname column way behind, and not even at the end, means\n>> that most people will have to type an extra \"xxxname,\" for each\n>> throwaway query run to quickly verify something. I know that I often\n>> do that, and while I could live with it I'd rather not have to do it.\n> Yeah, it would annoy the heck out of me too. Again there's a potential\n> technical solution, which is to decouple the user-visible column order\n> from the storage order. However, multiple people have tilted at that\n> windmill without much success, so making it a prerequisite for improving\n> the name-length situation doesn't seem like a smart plan.\n>\n> \t\t\t\n\n\nThere might be other benefits, though. IIRC what we discussed years ago\nwas having for each attribute an immutable number (presumably attnum as\nnow) and a mutable display order and storage order. Previous patches\ndidn't implement this and so were rejected. I think part of the trouble\nis that we'd have to go through roughly 1700 mentions of attnum in the\nsource and decide if it's really attnum they want or if it's\nattnum_display_order or attnum_storage_order. So this has the potential\nto be extraordinarily invasive and potentially bug-prone. And then\nthere's the world of extensions to consider.\n\nI have a bit less sympathy for the argument that just moving it will\nbreak things that use 'select *' on the catalogs. In general, if you\ncare about the order of columns you should name the columns you want in\nthe order you want. I've seen 'select *' break for people on other\nchanges, like adding or dropping a column. It might cause Postgres\ndevelopers a bit of pain, but it should be manageable, so I kind of like\nyour suggestion.\n\n\ncheers\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Wed, 18 Aug 2021 11:55:26 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Andrew Dunstan <andrew@dunslane.net> writes:\n> On 8/18/21 10:53 AM, Tom Lane wrote:\n>> Yeah, it would annoy the heck out of me too. Again there's a potential\n>> technical solution, which is to decouple the user-visible column order\n>> from the storage order. However, multiple people have tilted at that\n>> windmill without much success, so making it a prerequisite for improving\n>> the name-length situation doesn't seem like a smart plan.\n\n> There might be other benefits, though. IIRC what we discussed years ago\n> was having for each attribute an immutable number (presumably attnum as\n> now) and a mutable display order and storage order. Previous patches\n> didn't implement this and so were rejected. I think part of the trouble\n> is that we'd have to go through roughly 1700 mentions of attnum in the\n> source and decide if it's really attnum they want or if it's\n> attnum_display_order or attnum_storage_order. So this has the potential\n> to be extraordinarily invasive and potentially bug-prone. And then\n> there's the world of extensions to consider.\n\nYeah, exactly: conceptually that's simple, but flushing all the bugs\nout would be a years-long nightmare. It'd make all the fun we had\nwith missed attisdropped checks look like a walk in the park. Unless\nsomebody can figure out a way to mechanically check for mistakes,\nI don't think I want to go there.\n\nI wonder though if we could fix the immediate problem with something\nless ambitious. The hard part of the full proposal, I think, is\nseparating permanent identity from physical position. If we were to\nsplit out *only* the display order from that, the patch footprint\nought to be far far smaller --- basically, I think, we'd need to fix\nstar-expansion and not a lot more in the backend. Of course,\nclient-side code like psql's \\d and pg_dump would need to be upgraded\ntoo, but any missed things there would be cosmetic that's-not-the-\nexpected-column-order bugs, not core dumps. Also, at least in the v1\npatch we could use this just for system catalogs without exposing it\nas a feature for user tables, which would greatly restrict the set of\nclient-side places that really need fixed.\n\n(I think Alvaro was the last person to mess with this issue, so I\nwonder what his take is on the feasibility of such a restricted\nsolution.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 18 Aug 2021 12:12:44 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On 2021-Aug-18, Tom Lane wrote:\n\n> I wonder though if we could fix the immediate problem with something\n> less ambitious. The hard part of the full proposal, I think, is\n> separating permanent identity from physical position. If we were to\n> split out *only* the display order from that, the patch footprint\n> ought to be far far smaller --- basically, I think, we'd need to fix\n> star-expansion and not a lot more in the backend. Of course,\n> client-side code like psql's \\d and pg_dump would need to be upgraded\n> too, but any missed things there would be cosmetic that's-not-the-\n> expected-column-order bugs, not core dumps. Also, at least in the v1\n> patch we could use this just for system catalogs without exposing it\n> as a feature for user tables, which would greatly restrict the set of\n> client-side places that really need fixed.\n> \n> (I think Alvaro was the last person to mess with this issue, so I\n> wonder what his take is on the feasibility of such a restricted\n> solution.)\n\nYeah, my impression is that the project of just changing star expansion\nis much, much easier than splitting out attribute identity from physical\nlocation. The former, as I recall, is a localized change in expandRTE\nand friends, and you don't have to touch anything else. The other part\nof the change is much more invasive and got me into territory that I\nwasn't able to navigate successfully.\n\n(I think we should consider keeping 'attnum' as the display-order\nattribute, and have the physical-and-identity attribute get a new name,\nsay attphysnum. That's so that you don't have to change psql and the\nwhole world -- the change is transparent to them. This means we need a\nfirst step that's very invasive, because every single current use of\n'attnum' has to be changed to attphysnum first, followed by a functional\npatch that changes a few of those back to attnum. It'd be a large\ninconvenience to backend developers to ease the lives of client-side\ndevelopers.)\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\n\n", "msg_date": "Wed, 18 Aug 2021 12:39:23 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "\nOn 8/18/21 12:39 PM, Alvaro Herrera wrote:\n> On 2021-Aug-18, Tom Lane wrote:\n>\n>> I wonder though if we could fix the immediate problem with something\n>> less ambitious. The hard part of the full proposal, I think, is\n>> separating permanent identity from physical position. If we were to\n>> split out *only* the display order from that, the patch footprint\n>> ought to be far far smaller --- basically, I think, we'd need to fix\n>> star-expansion and not a lot more in the backend. Of course,\n>> client-side code like psql's \\d and pg_dump would need to be upgraded\n>> too, but any missed things there would be cosmetic that's-not-the-\n>> expected-column-order bugs, not core dumps. Also, at least in the v1\n>> patch we could use this just for system catalogs without exposing it\n>> as a feature for user tables, which would greatly restrict the set of\n>> client-side places that really need fixed.\n>>\n>> (I think Alvaro was the last person to mess with this issue, so I\n>> wonder what his take is on the feasibility of such a restricted\n>> solution.)\n> Yeah, my impression is that the project of just changing star expansion\n> is much, much easier than splitting out attribute identity from physical\n> location. The former, as I recall, is a localized change in expandRTE\n> and friends, and you don't have to touch anything else. The other part\n> of the change is much more invasive and got me into territory that I\n> wasn't able to navigate successfully.\n>\n> (I think we should consider keeping 'attnum' as the display-order\n> attribute, and have the physical-and-identity attribute get a new name,\n> say attphysnum. That's so that you don't have to change psql and the\n> whole world -- the change is transparent to them. This means we need a\n> first step that's very invasive, because every single current use of\n> 'attnum' has to be changed to attphysnum first, followed by a functional\n> patch that changes a few of those back to attnum. It'd be a large\n> inconvenience to backend developers to ease the lives of client-side\n> developers.)\n\n\nCan we call it attid just in case we decide some day to break the nexus\non the other side?\n\n\nI like the idea of keeping it to the catalog to start with.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Wed, 18 Aug 2021 12:57:35 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Thu, Aug 19, 2021 at 12:12 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Yeah, exactly: conceptually that's simple, but flushing all the bugs\n> out would be a years-long nightmare. It'd make all the fun we had\n> with missed attisdropped checks look like a walk in the park. Unless\n> somebody can figure out a way to mechanically check for mistakes,\n> I don't think I want to go there.\n\nMaybe a silly idea, but we could have some shared_preload_libraries\nmodule with a command_utility_hook that intercept table creation and\nrandomize the logical column order. If we also have some GUC (assert\nonly if needed) to switch star expansion to physical-order rather than\nlogical-order, we could then use the regression test as a big hammer\nto see if anything breaks. That's clearly not ideal (it would\nobviously need some other hacks to avoid other breakage like \\d and\nother things) and not 100% coverage, but it should give some\nconfidence in any patch completeness.\n\n\n", "msg_date": "Thu, 19 Aug 2021 01:12:13 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Hi,\n\nOn 2021-08-18 10:21:03 -0400, Tom Lane wrote:\n> Anyway, this whole argument could be rendered moot if we could convert\n> name to a variable-length type. That would satisfy *both* sides of\n> the argument, since those who need long names could have them, while\n> those who don't would see net reduction instead of growth in space usage.\n\nYes, I think that's the best direction to go. We're loosing a fair bit\nof in-memory efficiency with current NAMEDATALEN already, it'd imo be\nbeneficial to go for variable length encoding from that angle alone.\n\n\n> Of course, this is far far easier said than done; else we would have\n> done it years ago. But maybe it's not entirely out of reach.\n> I do not think it'd be hard to change \"name\" to have the same on-disk\n> storage representation as cstring; the hard part is what about its\n> usage in fixed-width catalog structures.\n\nIndeed. ISTM that the hardest part of that is dealing with copying around\nForm* structs?\n\nI wonder if we're getting closer to the time where we should just give up on\nthe struct / ondisk layout mirroring for catalog tables, and generate explicit\ntransformation routines via Catalog.pm. If we have to touch places handling\nForm_* structs anyway, we could make that more worthwhile by doing away with\nCATALOG_VARLEN etc - the transformation routines would just make those fields\npointers which then can be accessed normally.\n\n\n> Maybe we could finesse that\n> by decreeing that the name column always has to be the last\n> non-CATALOG_VARLEN field. (This would require fixing up the couple of\n> places where we let some other var-width field have that distinction;\n> but I suspect that would be small in comparison to the other work this\n> implies. If there are any catalogs having two name columns, one of them\n> would become more difficult to reach from C code.)\n\nI wish we could find a way to make \"relative pointers\" (i.e. a variable offset\nfrom some base struct) work on the C level in a transparent and portable\nmanner. Just about any instruction set has them natively anyway, and for a lot\nof tasks like variable length members it can be considerably more\nefficient... It'd also make DSM using code simpler and faster. Oh well, one\ncan dream.\n\n\n\n> Another fun thing --- and, I fear, another good argument against just\n> raising NAMEDATALEN --- is what about TupleDescs, which last I checked\n> used an array of fixed-width pg_attribute images. But maybe we could\n> replace that with an array of pointers. Andres already did a lot of\n> the heavy code churn required to hide that data structure behind\n> TupleDescAttr() macros, so changing the representation should be much\n> less painful than it would once have been.\n\nI was recently wondering if we shouldn't go to a completely bespoke\ndatastructure for TupleDesc->attrs, rather than reusing FormData_pg_attribute.\n\nRight now every attribute uses nearly two cachelines (112 bytes). Given how\nfrequent a task tuple [de]forming is, and how often it's a bottleneck,\nincreasing the cache efficiency of tupledescs would worth quite a bit of\neffort - I do see tupledesc attr cache misses in profiles. A secondary benefit\nwould be that we do create a lot of short-lived descs in the executor,\nslimming those down obviously would be good on its own. A third benefit would\nbe that we could get rid of attcacheoff in pg_attribute, that always smelled\nfunny to me.\n\nOne possible way to structure such future tupledescs would be to have multiple\narrays in struct TupleDescData. With an array of just the data necessary for\n[de]forming at the place ->attrs is, and other stuff in one or more separate\narrays. The other option could perhaps be omitted for some tupledescs or\ncomputed lazily.\n\nFor deforming we just need attlen (2byte), attbyval (1 byte), attalign (1byte)\nand optionally attcacheoff (4 byte), for forming we also need attstorage (1\nbyte). Naively that ends up being 12 bytes - 5 attrs / cacheline is a heck of\na lot better than ~0.5.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 19 Aug 2021 04:44:35 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Thu, 19 Aug 2021 at 13:44, Andres Freund <andres@anarazel.de> wrote:\n>\n> > Another fun thing --- and, I fear, another good argument against just\n> > raising NAMEDATALEN --- is what about TupleDescs, which last I checked\n> > used an array of fixed-width pg_attribute images. But maybe we could\n> > replace that with an array of pointers. Andres already did a lot of\n> > the heavy code churn required to hide that data structure behind\n> > TupleDescAttr() macros, so changing the representation should be much\n> > less painful than it would once have been.\n>\n> I was recently wondering if we shouldn't go to a completely bespoke\n> datastructure for TupleDesc->attrs, rather than reusing FormData_pg_attribute.\n>\n> Right now every attribute uses nearly two cachelines (112 bytes). Given how\n> frequent a task tuple [de]forming is, and how often it's a bottleneck,\n> increasing the cache efficiency of tupledescs would worth quite a bit of\n> effort - I do see tupledesc attr cache misses in profiles. A secondary benefit\n> would be that we do create a lot of short-lived descs in the executor,\n> slimming those down obviously would be good on its own. A third benefit would\n> be that we could get rid of attcacheoff in pg_attribute, that always smelled\n> funny to me.\n>\n> One possible way to structure such future tupledescs would be to have multiple\n> arrays in struct TupleDescData. With an array of just the data necessary for\n> [de]forming at the place ->attrs is, and other stuff in one or more separate\n> arrays. The other option could perhaps be omitted for some tupledescs or\n> computed lazily.\n>\n> For deforming we just need attlen (2byte), attbyval (1 byte), attalign (1byte)\n> and optionally attcacheoff (4 byte), for forming we also need attstorage (1\n> byte). Naively that ends up being 12 bytes - 5 attrs / cacheline is a heck of\n> a lot better than ~0.5.\n\nI tried to implement this 'compact attribute access descriptor' a few\nmonths ago in my effort to improve btree index performance.\n\nI abandoned the idea at the time as I didn't find any measurable\ndifference for the (limited!) tests I ran, where the workload was\nmainly re-indexing, select * into, and similar items while\nbenchmarking reindexing in the 'pp-complete' dataset. But, seeing that\nthere might be interest outside this effort on a basis seperate from\njust plain performance, I'll share the results.\n\nAttached is the latest version of my patch that I could find; it might\nbe incorrect or fail, as this is something I sent to myself between 2\nof my systems during development of the patch. Also, attached as .txt,\nas I don't want any CFBot coverage on this (this is not proposed for\ninclusion, it is just a show of work, and might be basis for future\nwork).\n\nThe patch allocates an array of 'TupleAttrAlignData'-structs at the\nend of the attrs-array, fills it with the correct data upon\nTupleDesc-creation, and uses this TupleAttrAlign-data for constructing\nand destructing tuples.\n\nOne main difference from what you described was that I used a union\nfor storing attbyval and attstorage, as the latter is only applicable\nto attlen < 0, and the first only for attlen >= 0. This keeps the\nwhole structure in 8 bytes, whilst also being useable in both tuple\nforming and deforming.\n\nI hope this can is useful, otherwise sorry for the noise.\n\n\nKind regards,\n\nMatthias van de Meent", "msg_date": "Thu, 19 Aug 2021 14:47:42 +0200", "msg_from": "Matthias van de Meent <boekewurm+postgres@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Hi,\n\nOn 2021-08-19 14:47:42 +0200, Matthias van de Meent wrote:\n> I tried to implement this 'compact attribute access descriptor' a few\n> months ago in my effort to improve btree index performance.\n\ncool\n\n\n> The patch allocates an array of 'TupleAttrAlignData'-structs at the\n> end of the attrs-array, fills it with the correct data upon\n> TupleDesc-creation, and uses this TupleAttrAlign-data for constructing\n> and destructing tuples.\n\n> One main difference from what you described was that I used a union\n> for storing attbyval and attstorage, as the latter is only applicable\n> to attlen < 0, and the first only for attlen >= 0. This keeps the\n> whole structure in 8 bytes, whilst also being useable in both tuple\n> forming and deforming.\n\nThat's why I just talked about the naive way - it's clearly possible to\ndo better... ;)\n\n\n> I hope this can is useful, otherwise sorry for the noise.\n\nIt is!\n\n\nI haven't looked at your patch in detail, but I suspect that one reason\nthat you didn't see performance benefits is that you added overhead as\nwell. The computation of the \"compact\" memory location now will need a\nfew more instructions than before, and I suspect the compiler may not\neven be able to optimize out some of the redundant accesses in loops.\n\nIt'd be interesting to see what you'd get if you stored the compact\narray as the flexible-array and stored a pointer to the \"full\" attrs\narray (while still keeping it allocated together).\n\n\nAnother reason is that it looks like you didn't touch\nslot_deform_heap_tuple(), which is I think the hottest of the deforming\nroutines...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 19 Aug 2021 05:57:56 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Thu, 19 Aug 2021 at 14:58, Andres Freund <andres@anarazel.de> wrote:\n>\n> Hi,\n>\n> On 2021-08-19 14:47:42 +0200, Matthias van de Meent wrote:\n> > I tried to implement this 'compact attribute access descriptor' a few\n> > months ago in my effort to improve btree index performance.\n>\n> cool\n>\n>\n> > The patch allocates an array of 'TupleAttrAlignData'-structs at the\n> > end of the attrs-array, fills it with the correct data upon\n> > TupleDesc-creation, and uses this TupleAttrAlign-data for constructing\n> > and destructing tuples.\n>\n> > One main difference from what you described was that I used a union\n> > for storing attbyval and attstorage, as the latter is only applicable\n> > to attlen < 0, and the first only for attlen >= 0. This keeps the\n> > whole structure in 8 bytes, whilst also being useable in both tuple\n> > forming and deforming.\n>\n> That's why I just talked about the naive way - it's clearly possible to\n> do better... ;)\n>\n>\n> > I hope this can is useful, otherwise sorry for the noise.\n>\n> It is!\n\nGreat!\n\n> I haven't looked at your patch in detail, but I suspect that one reason\n> that you didn't see performance benefits is that you added overhead as\n> well. The computation of the \"compact\" memory location now will need a\n> few more instructions than before, and I suspect the compiler may not\n> even be able to optimize out some of the redundant accesses in loops.\n>\n> It'd be interesting to see what you'd get if you stored the compact\n> array as the flexible-array and stored a pointer to the \"full\" attrs\n> array (while still keeping it allocated together).\n\nYes, I remember testing swapping the order of the compact array with the\nFormData_pg_attribute array as well, with no clear results.\n\nI think this can partially be attributed to the split access methods of the\ndata in the attribute descriptor: some of it is 'give me the name', some of\nit is 'does this attribute exist, what type description does it have?'\n(atttypid, attnum, atttypmod, , and others are only interested in the\nphysical representation information. Prioritizing some over the other might\nwork, but I think to make full use of that it'd need a lot of work.\n\n> Another reason is that it looks like you didn't touch\n> slot_deform_heap_tuple(), which is I think the hottest of the deforming\n> routines...\n\nThat might be for normal operations, but I'm not certain that code is in\nthe hot path for (btree) indexing workloads, due to the relatively high\nnumber of operations on each tuple whilst sorting, or finding an insertion\npoint or scan start point.\n\nAnyway, after some digging I found the final state of this patch before I\nstopped working on it, and after polishing it up a bit with your\nsuggestions it now passes check-world on the latest head (8d2d6ec7).\n\n\nKind regards,\n\nMatthias van de Meent", "msg_date": "Fri, 20 Aug 2021 13:54:42 +0200", "msg_from": "Matthias van de Meent <boekewurm+postgres@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Hi,\n\nI wanted to revive this thread to summarize what was discussed and get\na sense of next steps we could take.\n\nThe idea that gained the most traction is to make identifiers\nvariable-length in the catalogs, which has the added benefit of\nreducing memory in syscaches in the common case. That presented two\nchallenges:\n\n1. That would require putting the name physically closer to the end of\nthe column list. To make this less annoying for users, we'd need to\nseparate physical order from display order (at least/at first only for\nsystem catalogs). This would require:\n\n- changing star expansion in SELECTs (expandRTE etc)\n- adjusting pg_dump, \\d, etc\n\nThat much seems clear and agreed upon.\n\n2. We'd need to change how TupleDescs are stored and accessed.\n\nFor this point, Matthias shared a prototype patch for a 'compact\nattribute access descriptor' and Andres wondered if we should \"give up\non the struct / ondisk layout mirroring for catalog tables, and\ngenerate explicit transformation routines via Catalog.pm\".\n\nAfter this discussion dropped off, and it's not quite clear to me what\nthe first logical step is to make progress on the thread subject, and\nwhat's nice to have for other reasons. Is Matthias's patch or\nsomething like it a good next step?\n\n-- \nJohn Naylor\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 3 Jun 2022 13:28:16 +0700", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Hi,\n\nOn Fri, Jun 03, 2022 at 01:28:16PM +0700, John Naylor wrote:\n> \n> I wanted to revive this thread to summarize what was discussed and get\n> a sense of next steps we could take.\n\nThanks for reviving this topic!\n\n> The idea that gained the most traction is to make identifiers\n> variable-length in the catalogs, which has the added benefit of\n> reducing memory in syscaches in the common case. That presented two\n> challenges:\n> \n> 1. That would require putting the name physically closer to the end of\n> the column list. To make this less annoying for users, we'd need to\n> separate physical order from display order (at least/at first only for\n> system catalogs). This would require:\n> \n> - changing star expansion in SELECTs (expandRTE etc)\n> - adjusting pg_dump, \\d, etc\n\nI tried to work on a physical / logical attribute position patch (more at the\nend of the mail). I based it on �lvaro's feedback at [1], which is:\n\n- rename current pg_attribute.attnum to attphysnum\n- add a new pg_attribute.attnum for the now logical position\n- tweak a few places to use attnum rather than attphysnum (which however isn't\n what I did)\n\nThe idea, IIUC, is to make a physical position reordering entirely transparent\nto clients.\n\nHowever, once you change the star expansion, things start to subtly break in a\nlot of places. I try to dig in a bit to see if things could be made to work\nthe same but it opened a whole can of worms. So before spending too much time\non something that could be a non-starter I'd like to get some feedback on the\ngeneral approach.\n\nWhile some problem wouldn't happen if we restricted the feature to system\ncatalogs only (e.g. with renamed / dropped attributes, inheritance...), a lot\nwould still exist and would have to be dealt with initially. However I'm not\nsure what behavior would be wanted or acceptable, especially if we want\nsomething that can eventually be used for user relations too, with possibly\ndynamic positions.\n\nI'll describe some of those problems, and just to make things easier I will use\na normal table \"ab\" with 2 attributes, a and b, with their physical / logical\nposition reversed.\n\nObviously\n\nSELECT * FROM ab\n\nshould return a and b in that order. The aliases should also probably match\nthe logical position, as in:\n\nSELECT * FROM ab ab(aa, bb)\n\nshould probably map aa to a and bb to b.\n\nBut should COPY FROM / COPY TO / INSERT INTO use the logical position too if\nnot column list is provided? I'd think so, but it goes further from the\noriginal \"only handle star expansion\" idea.\n\nAnd should record_in / record_out use the logical position, as in:\nSELECT ab::text FROM ab / SELECT (a, b)::ab;\n\nI would think not, as relying on a possibly dynamic order could break things if\nyou store the results somewhere, but YMMV.\n\nNote that there a variations of that, like\nSELECT ab::ab FROM (SELECT * FROM ab) ab;\n\nBut those should probably work as intended (for now it doesn't) as you can't\nstore a bare record, and storing a plain \"ab\" type wouldn't be problematic with\ndynamic changes.\n\n\nThen, what about joinrels expansion? I learned that the column ordering rules\nare far from being obvious, and I didn't find those in the documentation (note\nthat I don't know if that something actually described in the SQL standard).\nSo for instance, if a join is using an explicit USING clause rather than an ON\nclause, the merged columns are expanded first, so:\n\nSELECT * FROM ab ab1 JOIN ab ab2 USING (b)\n\nshould unexpectedly expand to (b, a, a). Is this order a strict requirement?\n\nFor now I sort the expanded columns by (varno, attnum) but that's clearly a\nnoticeable change.\n\nAnother problem (that probably wouldn't be a problem for system catalogs) is\nthat defaults are evaluated in the physical position. This example from the\nregression test will clearly have a different behavior if the columns are in a\ndifferent physical order:\n\n CREATE TABLE INSERT_TBL (\n \tx INT DEFAULT nextval('insert_seq'),\n \ty TEXT DEFAULT '-NULL-',\n \tz INT DEFAULT -1 * currval('insert_seq'),\n \tCONSTRAINT INSERT_TBL_CON CHECK (x >= 3 AND y <> 'check failed' AND x < 8),\n \tCHECK (x + z = 0));\n\nBut changing the behavior to rely on the logical position seems quite\ndangerous.\n\n\nI'm also attaching some few patches as a basis for an implementation\ndiscussion. Those are just POC level prototypes with the bare minimum changes\nto try to have a behavior based on the logical position, and absolutely no\neffort to optimize anything. I'm also not familiar with all the impacted\nplaces, so I'm definitely not claiming that this is a good approach. Any\nsuggestion on a better approach is welcome.\n\n0001 is the s/attphysnum/attnum/ suggested by �lvaro. Here again it's the bare\nminimum to make the code compile, a lot of the code still reference attnum in\nsome ways (attnameAttnum(), variables like attnums and so on) that would need\nto be cleaned up.\n\n0002 is the addition of the new pg_attribute.attnum with some changes trying to\nmake things work, but no infrastructure to change it anywhere.\n\nThe relevant changes are there. In expandNSItemAttrs and some other places,\nthe difference is that the used TupleDesc is first copied and sorted by logical\nposition, and then the attphysnum attributes are used rather than a loop\ncounter, or the targetlist are sorted and then the resno\" are computed . Other\nplaces (only the relation columns aliases I think for now) also builds an array\nfor the physical / logical mappings,.\n\nI also changed psql to display the column in logical position, and emit an\nextra line with the physical position in the verbose mode, but that's a clearly\npoor design which would need a lot more thoughts. No changes in pg_dump or any\nother tool.\n\n0003 adds some infrastructure to specify the logical position for system\ncatalogs. It also moves relname and attname near the end of the non-varlena\npart of pg_class / pg_attribute (just before the end so no change is needed in\nthe *_FIXED_PART_SIZE macros)\n\nI also added some patches I used for testing:\n\n0004 automatically reverses relation attributes order and preserves the\noriginal logical position, so you can run the whole regression tests and see\nwhat breaks.\n\n0005 adds an ORDER (column_name, [...]) clause in the simplest CREATE TABLE\ncommand form to declare the logical order and manually test things, something\nlike:\n\nCREATE TABLE ab (b int, a int) ORDER (a, b);\n\n[1] https://www.postgresql.org/message-id/202108181639.xjuovrpwgkr2@alvherre.pgsql", "msg_date": "Thu, 23 Jun 2022 18:11:55 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Hi,\n\nOn 2022-06-03 13:28:16 +0700, John Naylor wrote:\n> 1. That would require putting the name physically closer to the end of\n> the column list. To make this less annoying for users, we'd need to\n> separate physical order from display order (at least/at first only for\n> system catalogs).\n\nFWIW, it's not at all clear to me that this would be required. If I were to\ntackle this I'd look at breaking up the mirroring of C structs to catalog\nstruct layout, by having genbki (or such) generate functions to map to/from\ntuple layout. It'll be an annoying amount of changes, but feasible, I think.\n\n\n> This would require:\n> \n> - changing star expansion in SELECTs (expandRTE etc)\n> - adjusting pg_dump, \\d, etc\n> \n> That much seems clear and agreed upon.\n\nFWIW, I don't agree that this is a reasonable way to tackle changing\nNAMEDATALEN. It'd be nice to have, but it to me it seems a pretty small\nfraction of the problem of making Names variable length. You'll still have all\nthe problems of name fields being accessed all over, but now not being\nincluded in the part of the struct visible to C etc.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 23 Jun 2022 07:16:58 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Thu, Jun 23, 2022 at 6:13 AM Julien Rouhaud <rjuju123@gmail.com> wrote:\n> While some problem wouldn't happen if we restricted the feature to system\n> catalogs only (e.g. with renamed / dropped attributes, inheritance...), a lot\n> would still exist and would have to be dealt with initially. However I'm not\n> sure what behavior would be wanted or acceptable, especially if we want\n> something that can eventually be used for user relations too, with possibly\n> dynamic positions.\n\nI am not very convinced that this would make the project a whole lot\neasier, but it does seem like the result would be less nice.\n\n> I'll describe some of those problems, and just to make things easier I will use\n> a normal table \"ab\" with 2 attributes, a and b, with their physical / logical\n> position reversed.\n>\n> Obviously\n>\n> SELECT * FROM ab\n>\n> should return a and b in that order. The aliases should also probably match\n> the logical position, as in:\n>\n> SELECT * FROM ab ab(aa, bb)\n>\n> should probably map aa to a and bb to b.\n\nCheck.\n\n> But should COPY FROM / COPY TO / INSERT INTO use the logical position too if\n> not column list is provided? I'd think so, but it goes further from the\n> original \"only handle star expansion\" idea.\n\nI think yes.\n\n> And should record_in / record_out use the logical position, as in:\n> SELECT ab::text FROM ab / SELECT (a, b)::ab;\n>\n> I would think not, as relying on a possibly dynamic order could break things if\n> you store the results somewhere, but YMMV.\n\nI think here the answer is yes again. I mean, consider that you could\nalso ALTER TABLE DROP COLUMN and then ALTER TABLE ADD COLUMN with the\nsame name. That is surely going to affect the meaning of such things.\nI don't think we want to have one meaning if you reorder things that\nway and a different meaning if you reorder things using whatever\ncommands we create for changing the display column positions.\n\n> Note that there a variations of that, like\n> SELECT ab::ab FROM (SELECT * FROM ab) ab;\n>\n> But those should probably work as intended (for now it doesn't) as you can't\n> store a bare record, and storing a plain \"ab\" type wouldn't be problematic with\n> dynamic changes.\n\nIf the sub-SELECT and the cast both use the display order, which I\nthink they should, then there's no problem here, I believe.\n\n> Then, what about joinrels expansion? I learned that the column ordering rules\n> are far from being obvious, and I didn't find those in the documentation (note\n> that I don't know if that something actually described in the SQL standard).\n> So for instance, if a join is using an explicit USING clause rather than an ON\n> clause, the merged columns are expanded first, so:\n>\n> SELECT * FROM ab ab1 JOIN ab ab2 USING (b)\n>\n> should unexpectedly expand to (b, a, a). Is this order a strict requirement?\n\nI dunno, but I can't see why it creates a problem for this patch to\nmaintain the current behavior. I mean, just use the logical column\nposition instead of the physical one here and forget about the details\nof how it works beyond that.\n\n> Another problem (that probably wouldn't be a problem for system catalogs) is\n> that defaults are evaluated in the physical position. This example from the\n> regression test will clearly have a different behavior if the columns are in a\n> different physical order:\n>\n> CREATE TABLE INSERT_TBL (\n> x INT DEFAULT nextval('insert_seq'),\n> y TEXT DEFAULT '-NULL-',\n> z INT DEFAULT -1 * currval('insert_seq'),\n> CONSTRAINT INSERT_TBL_CON CHECK (x >= 3 AND y <> 'check failed' AND x < 8),\n> CHECK (x + z = 0));\n>\n> But changing the behavior to rely on the logical position seems quite\n> dangerous.\n\nWhy?\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 23 Jun 2022 10:19:44 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Thu, Jun 23, 2022 at 10:17 AM Andres Freund <andres@anarazel.de> wrote:\n> > This would require:\n> >\n> > - changing star expansion in SELECTs (expandRTE etc)\n> > - adjusting pg_dump, \\d, etc\n> >\n> > That much seems clear and agreed upon.\n>\n> FWIW, I don't agree that this is a reasonable way to tackle changing\n> NAMEDATALEN. It'd be nice to have, but it to me it seems a pretty small\n> fraction of the problem of making Names variable length. You'll still have all\n> the problems of name fields being accessed all over, but now not being\n> included in the part of the struct visible to C etc.\n\nYeah, I agree. I think that being able to reorder columns logically\nwithout changing anything physically would be cool, but I think we\ncould find some way of making the catalog columns variable-length\nwithout introducing that feature.\n\nI'm not sure whether your idea of creating translator functions is a\ngood one or not, but it doesn't seem too crazy. It'd be like a special\npurpose tuple deformer.\n\ndeform_pg_class_tuple(&pg_class_struct, pg_class_tuple);\n\nThe code in there could be automatically generated statements that\nmaybe look like this:\n\nmemcpy(&struct.relnamespace, tuple + Aoffset_pg_class_relnamespace,\nsizeof(Oid));\n\nOnce you hit the first variable-length field you'd need something more\nclever, but because the code would be specialized for each catalog, it\nwould probably be quite fast anyway.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 23 Jun 2022 10:27:03 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> On Thu, Jun 23, 2022 at 10:17 AM Andres Freund <andres@anarazel.de> wrote:\n>> FWIW, I don't agree that this is a reasonable way to tackle changing\n>> NAMEDATALEN. It'd be nice to have, but it to me it seems a pretty small\n>> fraction of the problem of making Names variable length. You'll still have all\n>> the problems of name fields being accessed all over, but now not being\n>> included in the part of the struct visible to C etc.\n\n> Yeah, I agree. I think that being able to reorder columns logically\n> without changing anything physically would be cool, but I think we\n> could find some way of making the catalog columns variable-length\n> without introducing that feature.\n\nAgreed. Bearing in mind that multiple smart people have tackled that idea\nand gotten nowhere, I think setting it as a prerequisite for this project\nis a good way of ensuring this won't happen.\n\n> I'm not sure whether your idea of creating translator functions is a\n> good one or not, but it doesn't seem too crazy. It'd be like a special\n> purpose tuple deformer.\n\nSounds worth investigating, anyway. It'd also get us out from under\nC-struct-related problems such as the nearby AIX alignment issue.\n\nThe extra cost of the deforming step could also be repaid, in some\ncases, by not having to use SysCacheGetAttr etc later on to fetch\nvariable-length fields. That is, I'm imagining that the deformer\nwould extract all the fields, even varlena ones, and drop pointers\nor whatever into fields of the C struct.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 23 Jun 2022 14:07:09 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Thu, Jun 23, 2022 at 2:07 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Sounds worth investigating, anyway. It'd also get us out from under\n> C-struct-related problems such as the nearby AIX alignment issue.\n\nYeah.\n\n> The extra cost of the deforming step could also be repaid, in some\n> cases, by not having to use SysCacheGetAttr etc later on to fetch\n> variable-length fields. That is, I'm imagining that the deformer\n> would extract all the fields, even varlena ones, and drop pointers\n> or whatever into fields of the C struct.\n\nYeah, if we were going to do something like this, I can't see why we\nwouldn't do it this way. It wouldn't make sense to do it for only some\nof the attributes.\n\nI'm not sure exactly where we would put this translation step, though.\nI think for the syscaches and relcache we'd want to translate when\npopulating the cache so that when you do a cache lookup you get the\ndata already translated. It's hard to be sure without testing, but\nthat seems like it would make this cheap enough that we wouldn't have\nto be too worried, since the number of times we build new cache\nentries should be small compared to the number of times we access\nexisting ones. The trickier thing might be code that uses\nsystable_beginscan() et. al. directly.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 23 Jun 2022 14:42:17 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Hi,\n\nOn 2022-06-23 14:42:17 -0400, Robert Haas wrote:\n> On Thu, Jun 23, 2022 at 2:07 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > The extra cost of the deforming step could also be repaid, in some\n> > cases, by not having to use SysCacheGetAttr etc later on to fetch\n> > variable-length fields. That is, I'm imagining that the deformer\n> > would extract all the fields, even varlena ones, and drop pointers\n> > or whatever into fields of the C struct.\n\nI was also thinking we'd translate all attributes. Not entirely sure whether\nwe'd want to use \"plain\" pointers though - there are some places where we rely\non being able to copy such structs around. That'd be a bit easier with\nrelative pointers, pointing to the end of the struct. But likely the\nnotational overhead of dealing with relative pointers would be far higher than\nthe notational overhead of having to invoke a generated \"tuple struct\" copy\nfunction. Which we'd likely need anyway, because some previously statically\nsized allocations would end up being variable sized?\n\n\n> Yeah, if we were going to do something like this, I can't see why we\n> wouldn't do it this way. It wouldn't make sense to do it for only some\n> of the attributes.\n\nAgreed.\n\n\n> I'm not sure exactly where we would put this translation step, though.\n> I think for the syscaches and relcache we'd want to translate when\n> populating the cache so that when you do a cache lookup you get the\n> data already translated. It's hard to be sure without testing, but\n> that seems like it would make this cheap enough that we wouldn't have\n> to be too worried, since the number of times we build new cache\n> entries should be small compared to the number of times we access\n> existing ones. The trickier thing might be code that uses\n> systable_beginscan() et. al. directly.\n\nI was thinking we'd basically do it wherever we do a GETSTRUCT() today.\n\nA first step could be to transform code like\n (Form_pg_attribute) GETSTRUCT(tuple)\ninto\n GETSTRUCT(pg_attribute, tuple)\n\nthen, in a subsequent step, we'd redefine GETSTRUCT as something\n#define GESTRUCT(catalog, tuple) tuple_to_struct_##catalog(tuple)\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 23 Jun 2022 14:49:09 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Thu, Jun 23, 2022 at 5:49 PM Andres Freund <andres@anarazel.de> wrote:\n> I was thinking we'd basically do it wherever we do a GETSTRUCT() today.\n>\n> A first step could be to transform code like\n> (Form_pg_attribute) GETSTRUCT(tuple)\n> into\n> GETSTRUCT(pg_attribute, tuple)\n>\n> then, in a subsequent step, we'd redefine GETSTRUCT as something\n> #define GESTRUCT(catalog, tuple) tuple_to_struct_##catalog(tuple)\n\nThat seems a little fraught, because you'd be turning what's now\nbasically a trivial operation into a non-trivial operation involving\nmemory allocation.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 23 Jun 2022 18:29:46 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> On Thu, Jun 23, 2022 at 5:49 PM Andres Freund <andres@anarazel.de> wrote:\n>> I was thinking we'd basically do it wherever we do a GETSTRUCT() today.\n\n> That seems a little fraught, because you'd be turning what's now\n> basically a trivial operation into a non-trivial operation involving\n> memory allocation.\n\nNonetheless, the presence of GETSTRUCT calls should be a good guide\nto where we need to do something.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 23 Jun 2022 18:43:40 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Thu, Jun 23, 2022 at 9:17 PM Andres Freund <andres@anarazel.de> wrote:\n>\n> Hi,\n>\n> On 2022-06-03 13:28:16 +0700, John Naylor wrote:\n> > 1. That would require putting the name physically closer to the end of\n> > the column list. To make this less annoying for users, we'd need to\n> > separate physical order from display order (at least/at first only for\n> > system catalogs).\n>\n> FWIW, it's not at all clear to me that this would be required. If I were to\n> tackle this I'd look at breaking up the mirroring of C structs to catalog\n> struct layout, by having genbki (or such) generate functions to map to/from\n> tuple layout. It'll be an annoying amount of changes, but feasible, I think.\n\nHmm, I must have misunderstood this aspect. In my mind I was thinking\nthat if a varlen attribute were at the end, these functions would make\nit easier to access them quickly. But from this and the follow-on\nresponses, these would be used to access varlen attributes wherever\nthey may be. I'll take a look at the current uses of GETSTRUCT().\n\n-- \nJohn Naylor\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 24 Jun 2022 10:10:55 +0700", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Thu, Jun 23, 2022 at 6:43 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Nonetheless, the presence of GETSTRUCT calls should be a good guide\n> to where we need to do something.\n\nIndubitably.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 24 Jun 2022 08:11:56 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Thu, Jun 23, 2022 at 11:11 PM John Naylor\n<john.naylor@enterprisedb.com> wrote:\n> Hmm, I must have misunderstood this aspect. In my mind I was thinking\n> that if a varlen attribute were at the end, these functions would make\n> it easier to access them quickly. But from this and the follow-on\n> responses, these would be used to access varlen attributes wherever\n> they may be. I'll take a look at the current uses of GETSTRUCT().\n\nI don't know whether we can or should move all the \"name\" columns to\nthe end of the catalog. It would be user-visible and probably not\nuser-desirable, but it would save something in terms of tuple\ndeforming cost. I'm just not sure how much.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 24 Jun 2022 08:21:56 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> I don't know whether we can or should move all the \"name\" columns to\n> the end of the catalog. It would be user-visible and probably not\n> user-desirable,\n\nI'm a strong -1 on changing that if we're not absolutely forced to.\n\n> but it would save something in terms of tuple\n> deforming cost. I'm just not sure how much.\n\nI'd guess nothing, if we are deforming all the fields.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 24 Jun 2022 10:08:41 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Thu, Jun 23, 2022 at 10:19:44AM -0400, Robert Haas wrote:\n> On Thu, Jun 23, 2022 at 6:13 AM Julien Rouhaud <rjuju123@gmail.com> wrote:\n>\n> > And should record_in / record_out use the logical position, as in:\n> > SELECT ab::text FROM ab / SELECT (a, b)::ab;\n> >\n> > I would think not, as relying on a possibly dynamic order could break things if\n> > you store the results somewhere, but YMMV.\n>\n> I think here the answer is yes again. I mean, consider that you could\n> also ALTER TABLE DROP COLUMN and then ALTER TABLE ADD COLUMN with the\n> same name. That is surely going to affect the meaning of such things.\n> I don't think we want to have one meaning if you reorder things that\n> way and a different meaning if you reorder things using whatever\n> commands we create for changing the display column positions.\n\nIt indeed would, but ALTER TABLE DROP COLUMN is a destructive operation, and\nI'm assuming that anyone doing that is aware that it will have an impact on\nstored data and such. I initially thought that changing the display order of\ncolumns shouldn't have the same impact with the stability of otherwise\nunchanged record definition, as it would make such reorder much more impacting.\nBut I agree that having different behaviors seems worse.\n\n> > Then, what about joinrels expansion? I learned that the column ordering rules\n> > are far from being obvious, and I didn't find those in the documentation (note\n> > that I don't know if that something actually described in the SQL standard).\n> > So for instance, if a join is using an explicit USING clause rather than an ON\n> > clause, the merged columns are expanded first, so:\n> >\n> > SELECT * FROM ab ab1 JOIN ab ab2 USING (b)\n> >\n> > should unexpectedly expand to (b, a, a). Is this order a strict requirement?\n>\n> I dunno, but I can't see why it creates a problem for this patch to\n> maintain the current behavior. I mean, just use the logical column\n> position instead of the physical one here and forget about the details\n> of how it works beyond that.\n\nI'm not that familiar with this part of the code so I may have missed\nsomething, but I didn't see any place where I could just simply do that.\n\nTo be clear, the approach I used is to change the expansion ordering but\notherwise keep the current behavior, to try to minimize the changes. This is\ndone by keeping the attribute in the physical ordering pretty much everywhere,\nincluding in the nsitems, and just logically reorder them during the expansion.\nIn other words all the code still knows that the 1st column is the first\nphysical column and so on.\n\nSo in that query, the ordering is supposed to happen when handling the \"SELECT\n*\", which makes it impossible to retain that order.\n\nI'm assuming that what you meant is to change the ordering when processing the\nJOIN and retain the old \"SELECT *\" behavior, which is to emit items in the\norder they're found. But IIUC the only way to do that would be to change the\norder when building the nsitems themselves, and have the code believe that the\nattributes are physically stored in the logical order. That's probably doable,\nbut that looks like a way more impacting change. Or did you mean to keep the\napproach I used, and just have some special case for \"SELECT *\" when referring\nto a joinrel and instead try to handle the logical expansion in the join?\nAFAICS it would require to add some extra info in the parsing structures, as it\ndoesn't really really store any position, just relies on array offset / list\nposition and maps things that way.\n\n> > Another problem (that probably wouldn't be a problem for system catalogs) is\n> > that defaults are evaluated in the physical position. This example from the\n> > regression test will clearly have a different behavior if the columns are in a\n> > different physical order:\n> >\n> > CREATE TABLE INSERT_TBL (\n> > x INT DEFAULT nextval('insert_seq'),\n> > y TEXT DEFAULT '-NULL-',\n> > z INT DEFAULT -1 * currval('insert_seq'),\n> > CONSTRAINT INSERT_TBL_CON CHECK (x >= 3 AND y <> 'check failed' AND x < 8),\n> > CHECK (x + z = 0));\n> >\n> > But changing the behavior to rely on the logical position seems quite\n> > dangerous.\n>\n> Why?\n\nIt feels to me like a POLA violation, and probably people wouldn't expect it to\nbehave this way (even if this is clearly some corner case problem). Even if\nyou argue that this is not simply a default display order but something more\nlike real column order, the physical position being some implementation detail,\nit still doesn't really feels right.\n\nThe main reason for having the possibility to change the logical position is to\nhave \"better looking\", easier to work with, relations even if you have some\nrequirements with the real physical order like trying to optimize things as\nmuch as possible (reordering columns to avoid padding space, put non-nullable\ncolumns first...). The order in which defaults are evaluated looks like the\nsame kind of requirements. How useful would it be if you could chose a logical\norder, but not being able to chose the one you actually want because it would\nbreak your default values?\n\nAnyway, per the nearby discussions I don't see much interest, especially not in\nthe context of varlena identifiers (I should have started a different thread,\nsorry about that), so I don't think it's worth investing more efforts into it.\n\n\n", "msg_date": "Sun, 26 Jun 2022 10:48:24 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Hi,\n\nOn 2022-06-26 10:48:24 +0800, Julien Rouhaud wrote:\n> Anyway, per the nearby discussions I don't see much interest, especially not in\n> the context of varlena identifiers (I should have started a different thread,\n> sorry about that), so I don't think it's worth investing more efforts into\n> it.\n\nFWIW, I still think it's a worthwhile feature - just, to me, unrelated to\nvarlena identifiers. I've seen tremendous amounts of space wasted in tables\njust because of alignment issues...\n\n- Andres\n\n\n", "msg_date": "Sat, 25 Jun 2022 20:00:04 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Sat, Jun 25, 2022 at 08:00:04PM -0700, Andres Freund wrote:\n>\n> On 2022-06-26 10:48:24 +0800, Julien Rouhaud wrote:\n> > Anyway, per the nearby discussions I don't see much interest, especially not in\n> > the context of varlena identifiers (I should have started a different thread,\n> > sorry about that), so I don't think it's worth investing more efforts into\n> > it.\n>\n> FWIW, I still think it's a worthwhile feature\n\nOh, ok, I will start a new thread then.\n\n> - just, to me, unrelated to varlena identifiers.\n\nYeah I get that and I agree.\n\n> I've seen tremendous amounts of space wasted in tables\n> just because of alignment issues...\n\nSame here unfortunately.\n\n\n", "msg_date": "Tue, 28 Jun 2022 11:27:38 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Fri, Jun 24, 2022 at 4:49 AM Andres Freund <andres@anarazel.de> wrote:\n> A first step could be to transform code like\n> (Form_pg_attribute) GETSTRUCT(tuple)\n> into\n> GETSTRUCT(pg_attribute, tuple)\n\nTo get the ball rolling, I've done this much in 0001. This is an easy\nmechanical change, although we'll next want a third argument to pass\nthe Form_* pointer.\n\n0002 changes this macro to\n\n#define GETSTRUCT(CAT, TUP) Deform_##CAT##_tuple((char *)\n((TUP)->t_data) + (TUP)->t_data->t_hoff)\n\n...where genbki.pl generates stub macros in the form of\n\n#define Deform_pg_am_tuple(TUP) (Form_pg_am) (TUP)\n\n...which live in pg_*_deform.h and are #included into each main\ncatalog header after the Form_* is defined. Feedback on whether a more\ntasteful way should be sought would be appreciated.\n\nWhile not very interesting on its own, it gives an idea of how the\nbuild would work. Next step would be to turn these into functions like\n\nstatic inline void\nDeform_pg_am_tuple(Form_pg_am, char * tuple)\n{...}\n\nthat just memcpy() things over as already discussed, adjusting the\ncallers of GETSTRUCT to match. This won't be quite as mechanical and\nwill require some manual work since some not least because some call\nsites mix declaration and assignment. I imagine there will also be a\nneed for the inverse operation, forming a tuple from a struct.\n\nWe will also have to take care to work around cases where the Form_*\npointer is currently used for in-place updates. I imagine there are\nnot many, but they will require extra care. The pseudo-catalog\npg_sequence_data is an example, and a bit of a special case anyway.\n\nOn Fri, Jun 24, 2022 at 1:07 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Sounds worth investigating, anyway. It'd also get us out from under\n> C-struct-related problems such as the nearby AIX alignment issue.\n\nGetting around that issue sounds like a good first goal for committing.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com", "msg_date": "Mon, 11 Jul 2022 12:39:48 +0700", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Thu, Jun 23, 2022 at 9:27 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> I'm not sure whether your idea of creating translator functions is a\n> good one or not, but it doesn't seem too crazy. It'd be like a special\n> purpose tuple deformer.\n>\n> deform_pg_class_tuple(&pg_class_struct, pg_class_tuple);\n>\n> The code in there could be automatically generated statements that\n> maybe look like this:\n>\n> memcpy(&struct.relnamespace, tuple + Aoffset_pg_class_relnamespace,\n> sizeof(Oid));\n\nI've made a small step in this direction.\n\n0001 is just boilerplate, same as v1\n0002 teaches Catalog.pm to export both C attr name and SQL attr name, so we\ncan use \"sizeof\".\n0003 generates static inline functions that work the same as the current\nGETSTRUCT macro, i.e. just cast to the right pointer and return it.\n0004 generates a function for pg_cast that memcpys to a passed struct, for\ndemonstration.\n\nHere's the full deforming function generated for pg_cast. In English, the\ncurrent offset is the previous offset plus the previous type length, plus\nany alignment padding suitable for the current type (there is none here, so\nthe alignment aspect is not tested). I'm hoping something like this will be\nsufficient for what's in the current structs, but of course will need\nadditional work when expanding those to include pointers to varlen\nattributes. I've not yet inspected the emitted assembly language, but\nregression tests pass.\n\nstatic inline void\nDeform_pg_cast_tuple(Form_pg_cast pg_cast_struct, char * pg_cast_tuple)\n{\n#define Aoff_pg_cast_oid 0\nmemcpy(&pg_cast_struct->oid, pg_cast_tuple + Aoff_pg_cast_oid, sizeof(Oid));\n\n#define Aoff_pg_cast_castsource att_align_nominal(Aoff_pg_cast_oid +\nsizeof(Oid), 'i')\nmemcpy(&pg_cast_struct->castsource, pg_cast_tuple +\nAoff_pg_cast_castsource, sizeof(Oid));\n\n#define Aoff_pg_cast_casttarget att_align_nominal(Aoff_pg_cast_castsource +\nsizeof(Oid), 'i')\nmemcpy(&pg_cast_struct->casttarget, pg_cast_tuple +\nAoff_pg_cast_casttarget, sizeof(Oid));\n\n#define Aoff_pg_cast_castfunc att_align_nominal(Aoff_pg_cast_casttarget +\nsizeof(Oid), 'i')\nmemcpy(&pg_cast_struct->castfunc, pg_cast_tuple + Aoff_pg_cast_castfunc,\nsizeof(Oid));\n\n#define Aoff_pg_cast_castcontext att_align_nominal(Aoff_pg_cast_castfunc +\nsizeof(Oid), 'c')\nmemcpy(&pg_cast_struct->castcontext, pg_cast_tuple +\nAoff_pg_cast_castcontext, sizeof(char));\n\n#define Aoff_pg_cast_castmethod att_align_nominal(Aoff_pg_cast_castcontext\n+ sizeof(char), 'c')\nmemcpy(&pg_cast_struct->castmethod, pg_cast_tuple +\nAoff_pg_cast_castmethod, sizeof(char));\n}\n\nHere's an example of the changes done in the call sites. For the rest of\nthe catalogs, perhaps many of them can be done mechanically. I still\nanticipate a lot of manual work. Note that GETSTRUCT_MEMCPY is just\ntemporary scaffolding to distinguish from just returning a pointer, and is\nnot proposed for commit.\n\n- Form_pg_cast castForm = GETSTRUCT(pg_cast, tuple);\n+ FormData_pg_cast castForm;\n CoercionContext castcontext;\n\n+ GETSTRUCT_MEMCPY(pg_cast, &castForm, tuple);\n+\n /* convert char value for castcontext to CoercionContext\nenum */\n- switch (castForm->castcontext)\n+ switch (castForm.castcontext)\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com", "msg_date": "Mon, 18 Jul 2022 09:46:44 +0700", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Hi,\n\nOn 2022-07-18 09:46:44 +0700, John Naylor wrote:\n> I've made a small step in this direction.\n\nThanks for working on this!\n\n\n> 0001 is just boilerplate, same as v1\n\nIf we were to go for this, I wonder if we should backpatch the cast containing\nversion of GESTRUCT for less pain backpatching bugfixes. That'd likely require\nusing a different name for the cast containing one.\n\n\n> 0002 teaches Catalog.pm to export both C attr name and SQL attr name, so we\n> can use \"sizeof\".\n> 0003 generates static inline functions that work the same as the current\n> GETSTRUCT macro, i.e. just cast to the right pointer and return it.\n\nIt seems likely that inline functions are going to be too large for\nthis. There's a lot of GESTRUCTs in a lot of files, emitting a copy of the\nfunction every time doesn't seem great.\n\n\n> current offset is the previous offset plus the previous type length, plus\n> any alignment padding suitable for the current type (there is none here, so\n> the alignment aspect is not tested). I'm hoping something like this will be\n> sufficient for what's in the current structs, but of course will need\n> additional work when expanding those to include pointers to varlen\n> attributes. I've not yet inspected the emitted assembly language, but\n> regression tests pass.\n\nHm. Wouldn't it make sense to just use the normal tuple deforming routines and\nthen map the results to the structs?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sun, 17 Jul 2022 19:58:41 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Mon, Jul 18, 2022 at 9:58 AM Andres Freund <andres@anarazel.de> wrote:\n\n> > 0001 is just boilerplate, same as v1\n>\n> If we were to go for this, I wonder if we should backpatch the cast\ncontaining\n> version of GESTRUCT for less pain backpatching bugfixes. That'd likely\nrequire\n> using a different name for the cast containing one.\n\nThe new version in this series was meant to be temporary scaffolding, but\nin the back of my mind I wondered if we should go ahead and keep the simple\ncast for catalogs that have no varlenas or alignment issues. It sounds like\nyou'd be in favor of that.\n\n> > 0003 generates static inline functions that work the same as the current\n> > GETSTRUCT macro, i.e. just cast to the right pointer and return it.\n>\n> It seems likely that inline functions are going to be too large for\n> this. There's a lot of GESTRUCTs in a lot of files, emitting a copy of the\n> function every time doesn't seem great.\n\nOk.\n\n> > current offset is the previous offset plus the previous type length,\nplus\n> > any alignment padding suitable for the current type (there is none\nhere, so\n> > the alignment aspect is not tested). I'm hoping something like this\nwill be\n> > sufficient for what's in the current structs, but of course will need\n> > additional work when expanding those to include pointers to varlen\n> > attributes. I've not yet inspected the emitted assembly language, but\n> > regression tests pass.\n>\n> Hm. Wouldn't it make sense to just use the normal tuple deforming\nroutines and\n> then map the results to the structs?\n\nI wasn't sure if they'd be suitable for this, but if they are, that'd make\nthis easier and more maintainable. I'll look into it.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nOn Mon, Jul 18, 2022 at 9:58 AM Andres Freund <andres@anarazel.de> wrote:> > 0001 is just boilerplate, same as v1>> If we were to go for this, I wonder if we should backpatch the cast containing> version of GESTRUCT for less pain backpatching bugfixes. That'd likely require> using a different name for the cast containing one.The new version in this series was meant to be temporary scaffolding, but in the back of my mind I wondered if we should go ahead and keep the simple cast for catalogs that have no varlenas or alignment issues. It sounds like you'd be in favor of that. > > 0003 generates static inline functions that work the same as the current> > GETSTRUCT macro, i.e. just cast to the right pointer and return it.>> It seems likely that inline functions are going to be too large for> this. There's a lot of GESTRUCTs in a lot of files, emitting a copy of the> function every time doesn't seem great.Ok.> > current offset is the previous offset plus the previous type length, plus> > any alignment padding suitable for the current type (there is none here, so> > the alignment aspect is not tested). I'm hoping something like this will be> > sufficient for what's in the current structs, but of course will need> > additional work when expanding those to include pointers to varlen> > attributes. I've not yet inspected the emitted assembly language, but> > regression tests pass.>> Hm. Wouldn't it make sense to just use the normal tuple deforming routines and> then map the results to the structs?I wasn't sure if they'd be suitable for this, but if they are, that'd make this easier and more maintainable. I'll look into it.--John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Tue, 19 Jul 2022 08:30:48 +0700", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "I wrote:\n\n> On Mon, Jul 18, 2022 at 9:58 AM Andres Freund <andres@anarazel.de> wrote:\n> > Hm. Wouldn't it make sense to just use the normal tuple deforming\nroutines and\n> > then map the results to the structs?\n>\n> I wasn't sure if they'd be suitable for this, but if they are, that'd\nmake this easier and more maintainable. I'll look into it.\n\nThis would seem to have its own problems: heap_deform_tuple writes to\npassed arrays of datums and bools. The lower level parts like fetchatt and\nnocachegetattr return datums, so still need some generated boilerplate.\nSome of these also assume they can write cached offsets on a passed tuple\ndescriptor.\n\nI'm thinking where the first few attributes are fixed length, not null, and\n(because of AIX) not double-aligned, we can do a single memcpy on multiple\ncolumns at once. That will still be a common pattern after namedata is\nvarlen. Otherwise, use helper functions/macros similar to the above but\ninstead of passing a tuple descriptor, use info we have at compile time.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\nI wrote:> On Mon, Jul 18, 2022 at 9:58 AM Andres Freund <andres@anarazel.de> wrote:> > Hm. Wouldn't it make sense to just use the normal tuple deforming routines and> > then map the results to the structs?>> I wasn't sure if they'd be suitable for this, but if they are, that'd make this easier and more maintainable. I'll look into it.This would seem to have its own problems: heap_deform_tuple writes to passed arrays of datums and bools. The lower level parts like fetchatt and nocachegetattr return datums, so still need some generated boilerplate. Some of these also assume they can write cached offsets on a passed tuple descriptor.I'm thinking where the first few attributes are fixed length, not null, and (because of AIX) not double-aligned, we can do a single memcpy on multiple columns at once. That will still be a common pattern after namedata is varlen. Otherwise, use helper functions/macros similar to the above but instead of passing a tuple descriptor, use info we have at compile time. --John NaylorEDB: http://www.enterprisedb.com", "msg_date": "Tue, 19 Jul 2022 14:30:34 +0700", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Hi,\n\nOn 2022-07-19 14:30:34 +0700, John Naylor wrote:\n> I wrote:\n> \n> > On Mon, Jul 18, 2022 at 9:58 AM Andres Freund <andres@anarazel.de> wrote:\n> > > Hm. Wouldn't it make sense to just use the normal tuple deforming\n> routines and\n> > > then map the results to the structs?\n> >\n> > I wasn't sure if they'd be suitable for this, but if they are, that'd\n> make this easier and more maintainable. I'll look into it.\n> \n> This would seem to have its own problems: heap_deform_tuple writes to\n> passed arrays of datums and bools. The lower level parts like fetchatt and\n> nocachegetattr return datums, so still need some generated boilerplate.\n> Some of these also assume they can write cached offsets on a passed tuple\n> descriptor.\n\nSure. But that'll just be a form of conversion we do all over, rather than\nencoding low-level data layout details. Basically\nstruct->member1 = DatumGetInt32(values[0]);\nstruct->member2 = DatumGetChar(values[1]);\n\netc.\n\n\n> I'm thinking where the first few attributes are fixed length, not null, and\n> (because of AIX) not double-aligned, we can do a single memcpy on multiple\n> columns at once. That will still be a common pattern after namedata is\n> varlen. Otherwise, use helper functions/macros similar to the above but\n> instead of passing a tuple descriptor, use info we have at compile time.\n\nI think that might be over-optimizing things. I don't think we do these\nconversions at a rate that's high enough to warrant it - the common stuff\nshould be in relcache etc. It's possible that we might want to optimize the\ncatcache case specifically - but that'd be more optimizing memory usage than\n\"conversion\" imo.\n\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 19 Jul 2022 08:57:19 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "On Tue, Jul 19, 2022 at 10:57 PM Andres Freund <andres@anarazel.de> wrote:\n>\n> Hi,\n>\n> On 2022-07-19 14:30:34 +0700, John Naylor wrote:\n> > I'm thinking where the first few attributes are fixed length, not null,\nand\n> > (because of AIX) not double-aligned, we can do a single memcpy on\nmultiple\n> > columns at once. That will still be a common pattern after namedata is\n> > varlen. Otherwise, use helper functions/macros similar to the above but\n> > instead of passing a tuple descriptor, use info we have at compile time.\n>\n> I think that might be over-optimizing things. I don't think we do these\n> conversions at a rate that's high enough to warrant it - the common stuff\n> should be in relcache etc. It's possible that we might want to optimize\nthe\n> catcache case specifically - but that'd be more optimizing memory usage\nthan\n> \"conversion\" imo.\n\nOkay, here is a hackish experiment that applies on top of v2 but also\ninvalidates some of that earlier work. Since there is already a pg_cast.c,\nI demoed a new function there which looks like this:\n\nvoid\nDeform_pg_cast_tuple(Form_pg_cast pg_cast_struct, HeapTuple pg_cast_tuple,\nTupleDesc pg_cast_desc)\n{\n Datum values[Natts_pg_cast];\n bool isnull[Natts_pg_cast];\n\n heap_deform_tuple(pg_cast_tuple, pg_cast_desc, values, isnull);\n\n pg_cast_struct->oid = DatumGetObjectId(values[Anum_pg_cast_oid - 1]);\n pg_cast_struct->castsource =\nDatumGetObjectId(values[Anum_pg_cast_castsource - 1]);\n pg_cast_struct->casttarget =\nDatumGetObjectId(values[Anum_pg_cast_casttarget - 1]);\n pg_cast_struct->castfunc =\nDatumGetObjectId(values[Anum_pg_cast_castfunc - 1]);\n pg_cast_struct->castcontext =\nDatumGetChar(values[Anum_pg_cast_castcontext - 1]);\n pg_cast_struct->castmethod =\nDatumGetChar(values[Anum_pg_cast_castmethod - 1]);\n}\n\nFor the general case we can use pg_*_deform.c or something like that, with\nextern declarations in the main headers. To get this to work, I had to add\na couple pointless table open/close calls to get the tuple descriptor,\nsince currently the whole tuple is stored in the syscache, but that's not\ngood even as a temporary measure. Storing the full struct in the syscache\nis a good future step, as noted upthread, but to get there without a bunch\nmore churn, maybe the above function can copy the tuple descriptor into a\nlocal stack variable from an expanded version of schemapg.h. Once the\ndeformed structs are stored in caches, I imagine most of the times we want\nto deform are when we have the table open, and we can pass the descriptor\nas above without additional code.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com", "msg_date": "Fri, 22 Jul 2022 14:52:43 +0700", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "Attached is v3, which is mostly putting Andres's suggestion above (use\nheap_deform_tuple) into a code generation context. Everything interesting\nis in 0002, and again only touches pg_cast as an experiment. Some design\npoints which could be debatable:\n\n- I thought individual C files would be a pain for the build process, so I\njust dumped the new functions into a single file, with the extern\ndeclarations in the pg_*.h files.\n- I used `#include \"catalog/pg_cast.h\"` just for Form_pg_cast, but maybe a\nforward declaration would work.\n- To get the struct member assignments, I resorted to a Perl hash to map\nthe attribute types to the DatumGet* macros. That may not be great, but I\ndon't have a better idea at the moment.\n- I directly called this function for the table scan rather than hide it\nbehind a new variant of GETSTRUCT as I did before. That seems clearer to me\nabout the intent.\n\nThe syscache use of GETSTRUCT still uses a simple cast of the tuple (for\npg_cast those calls live in parse_coerce.c, which is unchanged from master\nin v3). Next step I think is to see about the syscache piece -- teaching a\nsyscache miss to deform the entire tuple into a struct and store it in the\nsyscache.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com", "msg_date": "Mon, 1 Aug 2022 19:38:05 +0700", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" }, { "msg_contents": "I wrote:\n\n> The syscache use of GETSTRUCT still uses a simple cast of the tuple (for pg_cast those calls live in parse_coerce.c, which is unchanged from master in v3). Next step I think is to see about the syscache piece -- teaching a syscache miss to deform the entire tuple into a struct and store it in the syscache.\n\nv4 is a hackish attempt at getting the syscache to deform the tuple\nand store the struct. Using only pg_cast again for ease, it seems to\nwork for that. It's now about as far as I can get without thinking\nabout byref types.\n\n0001 just adds copies of some syscache / catcache functions for\nprivate use by pg_cast, as scaffolding.\n0002 teaches the temporary CatalogCacheCreateEntry_STRUCT() to call\nheap_deform_tuple(). This then calls a for-now handwritten function\n(similar to the one generated in v3) which palloc's space for the\nstruct and copies the fields over. Only this function knows the\ncatalog struct type, so a future design could call the per-cache\nfunction via a pointer in the catcache control array. Since we already\nhave the isnull/values array, it's also trivial to copy the datums for\nthe cache keys. WIP: CatCTup->tuple is still declared a tuple, but the\nt_data contents are now bogus, so there is a temporary GETSTRUCT_NEW\nthat knows it's looking directly at the struct.\n\nGetting to varlen attributes: For one, I think it was mentioned above\nthat we will need a way to perform a deep copy of structs that contain\npointers to varlen fields. I imagine keeping track of the attributes\nlength will come up for some types and might be tricky. And before\nthat, the catalog machinery will need some preprocessor tricks to\ndeclare pointers in the structs.\n\n-- \nJohn Naylor\nEDB: http://www.enterprisedb.com", "msg_date": "Wed, 10 Aug 2022 17:57:46 +0700", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" } ]
[ { "msg_contents": "I don't very close with PG testing methodology, but I can pay for a server\n(virtual or dedicated, DO maybe) and give access to it, if anyone has time\nfor that.\n\nOr if someone describes to me steps and shows where to look - I can do it\nby myself.\n\nI don't very close with PG testing methodology, but I can pay for a server (virtual or dedicated, DO maybe) and give access to it, if anyone has time for that.Or if someone describes to me steps and shows where to look - I can do it by myself.", "msg_date": "Wed, 18 Aug 2021 18:43:18 +0700", "msg_from": "=?UTF-8?B?0JTQtdC90LjRgSDQoNC+0LzQsNC90LXQvdC60L4=?=\n <deromanenko@gmail.com>", "msg_from_op": true, "msg_subject": "Re: NAMEDATALEN increase because of non-latin languages" } ]
[ { "msg_contents": "When working on zedstore, the developers solved the lack of support\nfor passing column projection into the AM as explained in the\nzedstore/README [*]\n\n-----8<------8<------8<-------8<-------\nCurrent table am API requires enhancement here to pass down column\nprojection to AM. The patch showcases two different ways for the same.\n\n* For sequential scans added new beginscan_with_column_projection()\nAPI. Executor checks AM property and if it leverages column projection\nuses this new API else normal beginscan() API.\n\n* For index scans instead of modifying the begin scan API, added new\nAPI to specifically pass column projection list after calling begin\nscan to populate the scan descriptor but before fetching the tuples.\n-----8<------8<------8<-------8<-------\n\nWhich of course requires patching also the call sites in PostgreSQL\ncode itself to make use of these methods\n\nAs this was already almost a year ago, have there been any\ndevelopments in the core PostgreSQL code for supporting this ?\n\nOr is projection still supported only in FDWs ?\n\n----------\n[*] https://github.com/greenplum-db/postgres/blob/zedstore/src/backend/access/zedstore/README\n\n-----\nHannu Krosing\nGoogle Cloud - We have a long list of planned contributions and we are hiring.\nContact me if interested.\n\n\n", "msg_date": "Wed, 18 Aug 2021 13:55:48 +0200", "msg_from": "Hannu Krosing <hannuk@google.com>", "msg_from_op": true, "msg_subject": "Is there now an official way to pass column projection to heap AM" }, { "msg_contents": "> On 18 Aug 2021, at 13:55, Hannu Krosing <hannuk@google.com> wrote:\n\n> As this was already almost a year ago, have there been any\n> developments in the core PostgreSQL code for supporting this ?\n\nThis is the thread where that work was discussed:\n\nhttps://www.postgresql.org/message-id/flat/CAE-ML%2B9RmTNzKCNTZPQf8O3b-UjHWGFbSoXpQa3Wvuc8YBbEQw%40mail.gmail.com\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Wed, 18 Aug 2021 14:15:18 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Is there now an official way to pass column projection to heap AM" } ]
[ { "msg_contents": "Has anybody worked on making the pgbench internal functions available\nas extensions ?\n\nI mean the ones from \" Built-In Functions\" [*]\n\nSome of these are probably available in other extensions or even as\nbuiltins but having things like hash_fnv1a() or random_zipfian() which\nare guaranteed to have exact same behaviour as the ones in bundled\npgbench would enable more work to be pushed to database and generally\nresu;lt in better interoperability for tests.\n\n------\n[*] https://www.postgresql.org/docs/13/pgbench.html#PGBENCH-BUILTIN-FUNCTIONS\n\n-----\nHannu Krosing\nGoogle Cloud - We have a long list of planned contributions and we are hiring.\nContact me if interested.\n\n\n", "msg_date": "Wed, 18 Aug 2021 14:21:26 +0200", "msg_from": "Hannu Krosing <hannuk@google.com>", "msg_from_op": true, "msg_subject": "pgbench functions as extension" } ]
[ { "msg_contents": "Hi,\n\nI ran into some segfaults when using Postgres that was compiled with LLVM 7. According to the backtraces these crashes happened during the call to llvm_shutdown, during cleanup after another out of memory condition. It seems that calls to LLVMOrcDisposeInstance, can crash (at least on LLVM 7) when LLVM is left in bad state. I attached the relevant part of the stacktrace to this email.\n\nWith the attached patch these segfaults went away. The patch turns llvm_shutdown into a no-op whenever the backend is exiting with an error. Based on my understanding of the code this should be totally fine. No memory should be leaked, since all memory will be cleaned up anyway once the backend exits shortly after. The only reason this cleanup code even seems to exist at all is to get useful LLVM profiling data. To me it seems be acceptable if the profiling data is incorrect/missing when the backend exits with an error.\n\nJelte", "msg_date": "Wed, 18 Aug 2021 15:00:59 +0000", "msg_from": "Jelte Fennema <Jelte.Fennema@microsoft.com>", "msg_from_op": true, "msg_subject": "Don't clean up LLVM state when exiting in a bad way" }, { "msg_contents": "On Wed, Aug 18, 2021 at 8:01 AM Jelte Fennema <Jelte.Fennema@microsoft.com>\nwrote:\n\n> Hi,\n>\n> I ran into some segfaults when using Postgres that was compiled with LLVM\n> 7. According to the backtraces these crashes happened during the call to\n> llvm_shutdown, during cleanup after another out of memory condition. It\n> seems that calls to LLVMOrcDisposeInstance, can crash (at least on LLVM 7)\n> when LLVM is left in bad state. I attached the relevant part of the\n> stacktrace to this email.\n>\n> With the attached patch these segfaults went away. The patch turns\n> llvm_shutdown into a no-op whenever the backend is exiting with an error.\n> Based on my understanding of the code this should be totally fine. No\n> memory should be leaked, since all memory will be cleaned up anyway once\n> the backend exits shortly after. The only reason this cleanup code even\n> seems to exist at all is to get useful LLVM profiling data. To me it seems\n> be acceptable if the profiling data is incorrect/missing when the backend\n> exits with an error.\n>\n> Jelte\n>\nHi,\nMinor comment:\n\n+ * shut LLVM down, this can result into a segfault. So if this\nprocess\n\nresult into a segfault -> result in a segfault\n\nCheers\n\nOn Wed, Aug 18, 2021 at 8:01 AM Jelte Fennema <Jelte.Fennema@microsoft.com> wrote:\n\n\nHi,\n\n\n\n\nI ran into some segfaults when using Postgres that was compiled with LLVM 7. According to the backtraces these crashes happened during the call to llvm_shutdown, during cleanup after another out of memory condition. It seems that calls to LLVMOrcDisposeInstance,\n can crash (at least on LLVM 7) when LLVM is left in bad state. I attached the relevant part of the stacktrace to this email.\n\n\n\n\nWith the attached patch these segfaults went away. The patch turns llvm_shutdown into a no-op whenever the backend is exiting with an error. Based on my understanding of the code this should be totally fine. No memory should be leaked, since all memory will\n be cleaned up anyway once the backend exits shortly after. The only reason this cleanup code even seems to exist at all is to get useful LLVM profiling data. To me it seems be acceptable if the profiling data is incorrect/missing when the backend exits with\n an error.  \n\n\n\n\nJelteHi,Minor comment:+        * shut LLVM down, this can result into a segfault. So if this process result into a segfault -> result in a segfaultCheers", "msg_date": "Wed, 18 Aug 2021 08:17:54 -0700", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: Don't clean up LLVM state when exiting in a bad way" }, { "msg_contents": "On Wed, Aug 18, 2021 at 03:00:59PM +0000, Jelte Fennema wrote:\n> I ran into some segfaults when using Postgres that was compiled with LLVM 7. According to the backtraces these crashes happened during the call to llvm_shutdown, during cleanup after another out of memory condition. It seems that calls to LLVMOrcDisposeInstance, can crash (at least on LLVM 7) when LLVM is left in bad state. I attached the relevant part of the stacktrace to this email.\n> \n> With the attached patch these segfaults went away. The patch turns llvm_shutdown into a no-op whenever the backend is exiting with an error. Based on my understanding of the code this should be totally fine. No memory should be leaked, since all memory will be cleaned up anyway once the backend exits shortly after. The only reason this cleanup code even seems to exist at all is to get useful LLVM profiling data. To me it seems be acceptable if the profiling data is incorrect/missing when the backend exits with an error.\n\nAndres , could you comment on this ?\n\nThis seems to explain the crash I reported to you when testing your WIP patches\nfor the JIT memory leak. I realize now that the crash happens without your\npatches.\nhttps://www.postgresql.org/message-id/20210419164130.byegpfrw46mzagcu@alap3.anarazel.de\n\nI can reproduce the crash on master (not just v13, as I said before) compiled\non centos7, with:\nLLVM_CONFIG=/usr/lib64/llvm7.0/bin/llvm-config CLANG=/opt/rh/llvm-toolset-7.0/root/usr/bin/clang\n\nI cannot reproduce the crash after applying Jelte's patch.\n\nI couldn't crash on ubuntu either, so maybe they have a patch which fixes this,\nor maybe RH applied a patch which caused it...\n\npostgres=# CREATE TABLE t AS SELECT i FROM generate_series(1,999999)i; VACUUM ANALYZE t;\npostgres=# SET client_min_messages=debug; SET statement_timeout=333; SET jit_above_cost=0; SET jit_optimize_above_cost=-1; SET jit_inline_above_cost=-1; explain analyze SELECT sum(i) FROM t a NATURAL JOIN t b;\n2021-09-05 22:47:12.807 ADT client backend[7563] psql ERROR: canceling statement due to statement timeout\n2021-09-05 22:47:12.880 ADT postmaster[7272] LOG: background worker \"parallel worker\" (PID 8212) was terminated by signal 11: Segmentation fault\n\n-- \nJustin\n\n\n", "msg_date": "Sun, 5 Sep 2021 21:33:56 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Don't clean up LLVM state when exiting in a bad way" }, { "msg_contents": "Hi,\n\nOn 2021-08-18 15:00:59 +0000, Jelte Fennema wrote:\n> I ran into some segfaults when using Postgres that was compiled with LLVM\n> 7. According to the backtraces these crashes happened during the call to\n> llvm_shutdown, during cleanup after another out of memory condition. It\n> seems that calls to LLVMOrcDisposeInstance, can crash (at least on LLVM 7)\n> when LLVM is left in bad state. I attached the relevant part of the\n> stacktrace to this email.\n\n> With the attached patch these segfaults went away. The patch turns\n> llvm_shutdown into a no-op whenever the backend is exiting with an\n> error. Based on my understanding of the code this should be totally fine. No\n> memory should be leaked, since all memory will be cleaned up anyway once the\n> backend exits shortly after. The only reason this cleanup code even seems to\n> exist at all is to get useful LLVM profiling data. To me it seems be\n> acceptable if the profiling data is incorrect/missing when the backend exits\n> with an error.\n\nI think this is a tad too strong. We should continue to clean up on exit as\nlong as the error didn't happen while we're already inside llvm\ncode. Otherwise we loose some ability to find leaks. How about checking in the\nerror path whether fatal_new_handler_depth is > 0, and skipping cleanup in\nthat case? Because that's precisely when it should be unsafe to reenter LLVM.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 7 Sep 2021 12:27:27 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Don't clean up LLVM state when exiting in a bad way" }, { "msg_contents": "On Tue, Sep 07, 2021 at 12:27:27PM -0700, Andres Freund wrote:\n> Hi,\n> \n> On 2021-08-18 15:00:59 +0000, Jelte Fennema wrote:\n> > I ran into some segfaults when using Postgres that was compiled with LLVM\n> > 7. According to the backtraces these crashes happened during the call to\n> > llvm_shutdown, during cleanup after another out of memory condition. It\n> > seems that calls to LLVMOrcDisposeInstance, can crash (at least on LLVM 7)\n> > when LLVM is left in bad state. I attached the relevant part of the\n> > stacktrace to this email.\n> \n> > With the attached patch these segfaults went away. The patch turns\n> > llvm_shutdown into a no-op whenever the backend is exiting with an\n> > error. Based on my understanding of the code this should be totally fine. No\n> > memory should be leaked, since all memory will be cleaned up anyway once the\n> > backend exits shortly after. The only reason this cleanup code even seems to\n> > exist at all is to get useful LLVM profiling data. To me it seems be\n> > acceptable if the profiling data is incorrect/missing when the backend exits\n> > with an error.\n> \n> I think this is a tad too strong. We should continue to clean up on exit as\n> long as the error didn't happen while we're already inside llvm\n> code. Otherwise we loose some ability to find leaks. How about checking in the\n> error path whether fatal_new_handler_depth is > 0, and skipping cleanup in\n> that case? Because that's precisely when it should be unsafe to reenter LLVM.\n\nThis avoids a crash when compiled with llvm7+clang7 on RH7 on master:\n\npython3 -c \"import pg; db=pg.DB('dbname=postgres host=/tmp port=5678'); db.query('SET jit_above_cost=0; SET jit_inline_above_cost=-1; SET jit=on; SET client_min_messages=debug'); db.query('begin'); db.query_formatted('SELECT 1 FROM generate_series(1,99)a WHERE a=%s', [1], inline=False);\"\n\ndiff --git a/src/backend/jit/llvm/llvmjit.c b/src/backend/jit/llvm/llvmjit.c\nindex df691cbf1c..a3869ee700 100644\n--- a/src/backend/jit/llvm/llvmjit.c\n+++ b/src/backend/jit/llvm/llvmjit.c\n@@ -885,6 +885,12 @@ llvm_session_initialize(void)\n static void\n llvm_shutdown(int code, Datum arg)\n {\n+\textern int fatal_new_handler_depth;\n+\n+\t// if (code!=0)\n+\tif (fatal_new_handler_depth > 0)\n+\t\treturn;\n+\n #if LLVM_VERSION_MAJOR > 11\n \t{\n \t\tif (llvm_opt3_orc)\ndiff --git a/src/backend/jit/llvm/llvmjit_error.cpp b/src/backend/jit/llvm/llvmjit_error.cpp\nindex 26bc828875..802dc1b058 100644\n--- a/src/backend/jit/llvm/llvmjit_error.cpp\n+++ b/src/backend/jit/llvm/llvmjit_error.cpp\n@@ -24,7 +24,7 @@ extern \"C\"\n #include \"jit/llvmjit.h\"\n \n \n-static int fatal_new_handler_depth = 0;\n+int fatal_new_handler_depth = 0;\n static std::new_handler old_new_handler = NULL;\n \n static void fatal_system_new_handler(void);\n\n\n", "msg_date": "Tue, 7 Sep 2021 14:44:39 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Don't clean up LLVM state when exiting in a bad way" }, { "msg_contents": "Hi,\n\n\nOn 2021-09-07 14:44:39 -0500, Justin Pryzby wrote:\n> On Tue, Sep 07, 2021 at 12:27:27PM -0700, Andres Freund wrote:\n> > I think this is a tad too strong. We should continue to clean up on exit as\n> > long as the error didn't happen while we're already inside llvm\n> > code. Otherwise we loose some ability to find leaks. How about checking in the\n> > error path whether fatal_new_handler_depth is > 0, and skipping cleanup in\n> > that case? Because that's precisely when it should be unsafe to reenter\n> > LLVM.\n\nThe more important reason is actually profiling information that needs to be\nwritten out.\n\nI've now pushed a fix to all relevant branches. Thanks all!\n\nRegards,\n\nAndres\n\n\n\n", "msg_date": "Mon, 13 Sep 2021 18:32:55 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Don't clean up LLVM state when exiting in a bad way" }, { "msg_contents": "Hello hackers,\n14.09.2021 04:32, Andres Freund wrote:\n> On 2021-09-07 14:44:39 -0500, Justin Pryzby wrote:\n>> On Tue, Sep 07, 2021 at 12:27:27PM -0700, Andres Freund wrote:\n>>> I think this is a tad too strong. We should continue to clean up on exit as\n>>> long as the error didn't happen while we're already inside llvm\n>>> code. Otherwise we loose some ability to find leaks. How about checking in the\n>>> error path whether fatal_new_handler_depth is > 0, and skipping cleanup in\n>>> that case? Because that's precisely when it should be unsafe to reenter\n>>> LLVM.\n> The more important reason is actually profiling information that needs to be\n> written out.\n>\n> I've now pushed a fix to all relevant branches. Thanks all!\n>\nI've encountered similar issue last week, but found this discussion only\nafter the commit.\nI'm afraid that it's not completely gone yet. I've reproduced a similar\ncrash (on edb4d95d) with\necho \"statement_timeout = 50\njit_optimize_above_cost = 1\njit_inline_above_cost = 1\nparallel_setup_cost=0\nparallel_tuple_cost=0\n\" >/tmp/extra.config\nTEMP_CONFIG=/tmp/extra.config  make check\n\nparallel group (11 tests):  memoize explain hash_part partition_info\nreloptions tuplesort compression partition_aggregate indexing\npartition_prune partition_join\n     partition_join               ... FAILED (test process exited with\nexit code 2)     1815 ms\n     partition_prune              ... FAILED (test process exited with\nexit code 2)     1779 ms\n     reloptions                   ... ok          146 ms\n\nI've extracted the crash-causing fragment from the partition_prune test\nto reproduce the segfault reliably (see the patch attached).\nThe segfault stack is:\nCore was generated by `postgres: parallel worker for PID\n12029                                       '.\nProgram terminated with signal 11, Segmentation fault.\n#0  0x00007f045e0a88ca in notifyFreed (K=<optimized out>, Obj=...,\nthis=<optimized out>)\n    at\n/usr/src/debug/llvm-7.0.1.src/lib/ExecutionEngine/Orc/OrcCBindingsStack.h:485\n485           Listener->NotifyFreeingObject(Obj);\n(gdb) bt\n#0  0x00007f045e0a88ca in notifyFreed (K=<optimized out>, Obj=...,\nthis=<optimized out>)\n    at\n/usr/src/debug/llvm-7.0.1.src/lib/ExecutionEngine/Orc/OrcCBindingsStack.h:485\n#1  operator() (K=<optimized out>, Obj=..., __closure=<optimized out>)\n    at\n/usr/src/debug/llvm-7.0.1.src/lib/ExecutionEngine/Orc/OrcCBindingsStack.h:226\n#2  std::_Function_handler<void (unsigned long, llvm::object::ObjectFile\nconst&),\nllvm::OrcCBindingsStack::OrcCBindingsStack(llvm::TargetMachine&,\nstd::function<std::unique_ptr<llvm::orc::IndirectStubsManager,\nstd::default_delete<llvm::orc::IndirectStubsManager> >\n()>)::{lambda(unsigned long, llvm::object::ObjectFile\nconst&)#3}>::_M_invoke(std::_Any_data const&, unsigned long,\nllvm::object::ObjectFile const&) (__functor=..., __args#0=<optimized\nout>, __args#1=...)\n    at /usr/include/c++/4.8.2/functional:2071\n#3  0x00007f045e0aa578 in operator() (__args#1=..., __args#0=<optimized\nout>, this=<optimized out>)\n    at /usr/include/c++/4.8.2/functional:2471\n...\n\nThe corresponding code in OrcCBindingsStack.h is:\nvoid notifyFreed(orc::VModuleKey K, const object::ObjectFile &Obj) {\n    for (auto &Listener : EventListeners)\n     Listener->NotifyFreeingObject(Obj);\n}\nSo probably one of the EventListeners has become null. I see that\nwithout debugging and profiling enabled the only listener registration\nin the postgres code is LLVMOrcRegisterJITEventListener.\n\nWith LLVM 9 on the same Centos 7 I don't get such segfault. Also it\ndoesn't happen on different OSes with LLVM 7. I still have no\nexplanation for that, but maybe there is difference between LLVM\nconfigure options, e.g. like this:\nhttps://stackoverflow.com/questions/47712670/segmentation-fault-in-llvm-pass-when-using-registerstandardpasses\n\nBest regards,\nAlexander", "msg_date": "Tue, 14 Sep 2021 07:00:00 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Don't clean up LLVM state when exiting in a bad way" }, { "msg_contents": "Hi, \n\nOn September 13, 2021 9:00:00 PM PDT, Alexander Lakhin <exclusion@gmail.com> wrote:\n>Hello hackers,\n>14.09.2021 04:32, Andres Freund wrote:\n>> On 2021-09-07 14:44:39 -0500, Justin Pryzby wrote:\n>>> On Tue, Sep 07, 2021 at 12:27:27PM -0700, Andres Freund wrote:\n>>>> I think this is a tad too strong. We should continue to clean up on exit as\n>>>> long as the error didn't happen while we're already inside llvm\n>>>> code. Otherwise we loose some ability to find leaks. How about checking in the\n>>>> error path whether fatal_new_handler_depth is > 0, and skipping cleanup in\n>>>> that case? Because that's precisely when it should be unsafe to reenter\n>>>> LLVM.\n>> The more important reason is actually profiling information that needs to be\n>> written out.\n>>\n>> I've now pushed a fix to all relevant branches. Thanks all!\n>>\n>I've encountered similar issue last week, but found this discussion only\n>after the commit.\n>I'm afraid that it's not completely gone yet. I've reproduced a similar\n>crash (on edb4d95d) with\n>echo \"statement_timeout = 50\n>jit_optimize_above_cost = 1\n>jit_inline_above_cost = 1\n>parallel_setup_cost=0\n>parallel_tuple_cost=0\n>\" >/tmp/extra.config\n>TEMP_CONFIG=/tmp/extra.config  make check\n>\n>parallel group (11 tests):  memoize explain hash_part partition_info\n>reloptions tuplesort compression partition_aggregate indexing\n>partition_prune partition_join\n>     partition_join               ... FAILED (test process exited with\n>exit code 2)     1815 ms\n>     partition_prune              ... FAILED (test process exited with\n>exit code 2)     1779 ms\n>     reloptions                   ... ok          146 ms\n>\n>I've extracted the crash-causing fragment from the partition_prune test\n>to reproduce the segfault reliably (see the patch attached).\n>The segfault stack is:\n>Core was generated by `postgres: parallel worker for PID\n>12029                                       '.\n>Program terminated with signal 11, Segmentation fault.\n>#0  0x00007f045e0a88ca in notifyFreed (K=<optimized out>, Obj=...,\n>this=<optimized out>)\n>    at\n>/usr/src/debug/llvm-7.0.1.src/lib/ExecutionEngine/Orc/OrcCBindingsStack.h:485\n>485           Listener->NotifyFreeingObject(Obj);\n>(gdb) bt\n>#0  0x00007f045e0a88ca in notifyFreed (K=<optimized out>, Obj=...,\n>this=<optimized out>)\n>    at\n>/usr/src/debug/llvm-7.0.1.src/lib/ExecutionEngine/Orc/OrcCBindingsStack.h:485\n>#1  operator() (K=<optimized out>, Obj=..., __closure=<optimized out>)\n>    at\n>/usr/src/debug/llvm-7.0.1.src/lib/ExecutionEngine/Orc/OrcCBindingsStack.h:226\n>#2  std::_Function_handler<void (unsigned long, llvm::object::ObjectFile\n>const&),\n>llvm::OrcCBindingsStack::OrcCBindingsStack(llvm::TargetMachine&,\n>std::function<std::unique_ptr<llvm::orc::IndirectStubsManager,\n>std::default_delete<llvm::orc::IndirectStubsManager> >\n>()>)::{lambda(unsigned long, llvm::object::ObjectFile\n>const&)#3}>::_M_invoke(std::_Any_data const&, unsigned long,\n>llvm::object::ObjectFile const&) (__functor=..., __args#0=<optimized\n>out>, __args#1=...)\n>    at /usr/include/c++/4.8.2/functional:2071\n>#3  0x00007f045e0aa578 in operator() (__args#1=..., __args#0=<optimized\n>out>, this=<optimized out>)\n>    at /usr/include/c++/4.8.2/functional:2471\n>...\n>\n>The corresponding code in OrcCBindingsStack.h is:\n>void notifyFreed(orc::VModuleKey K, const object::ObjectFile &Obj) {\n>    for (auto &Listener : EventListeners)\n>     Listener->NotifyFreeingObject(Obj);\n>}\n>So probably one of the EventListeners has become null. I see that\n>without debugging and profiling enabled the only listener registration\n>in the postgres code is LLVMOrcRegisterJITEventListener.\n>\n>With LLVM 9 on the same Centos 7 I don't get such segfault. Also it\n>doesn't happen on different OSes with LLVM 7.\n\nThat just like an llvm bug to me. Rather than the usage issue addressed in this thread.\n\n\n I still have no\n>explanation for that, but maybe there is difference between LLVM\n>configure options, e.g. like this:\n>https://stackoverflow.com/questions/47712670/segmentation-fault-in-llvm-pass-when-using-registerstandardpasses\n\nWhy is it not much more likely that bugs were fixed?\n\n\nAndres\n-- \nSent from my Android device with K-9 Mail. Please excuse my brevity.\n\n\n", "msg_date": "Mon, 13 Sep 2021 22:05:23 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Don't clean up LLVM state when exiting in a bad way" }, { "msg_contents": "Hello Andres,\n14.09.2021 08:05, Andres Freund wrote:\n>\n>> With LLVM 9 on the same Centos 7 I don't get such segfault. Also it\n>> doesn't happen on different OSes with LLVM 7.\n> That just like an llvm bug to me. Rather than the usage issue addressed in this thread.\nBut Justin seen this strangeness too:\n>\n> I couldn't crash on ubuntu either, so maybe they have a patch which\n> fixes this,\n> or maybe RH applied a patch which caused it...\n>\nThe script that Justin presented:\n> postgres=# CREATE TABLE t AS SELECT i FROM generate_series(1,999999)i;\n> VACUUM ANALYZE t;\n> postgres=# SET client_min_messages=debug; SET statement_timeout=333;\n> SET jit_above_cost=0; SET jit_optimize_above_cost=-1; SET\n> jit_inline_above_cost=-1; explain analyze SELECT sum(i) FROM t a\n> NATURAL JOIN t b;\ncauses the server crash on Centos 7 with LLVM 7 (even with the fix\napplied) and doesn't crash with LLVM 9 (I used llvm-toolset-9* and\ndevtoolset-9* packages from\nhttps://buildlogs.centos.org/c7-llvm-toolset-9.0.x86_64/ and\nhttps://buildlogs.centos.org/c7-devtoolset-9.x86_64/ repositories).\n\nThe another script:\n>\n> python3 -c \"import pg; db=pg.DB('dbname=postgres host=/tmp\n> port=5678'); db.query('SET jit_above_cost=0; SET\n> jit_inline_above_cost=-1; SET jit=on; SET client_min_messages=debug');\n> db.query('begin'); db.query_formatted('SELECT 1 FROM\n> generate_series(1,99)a WHERE a=%s', [1], inline=False);\"\n>\nalso causes the server crash with LLVM 7, and doesn't crash with LLVM 9.\n\nSo I wonder, isn't the fixed usage issue specific to LLVM 7, which is\nnot going to be supported as having some bugs?\n\nBest regards,\nAlexander\n\n\n", "msg_date": "Tue, 14 Sep 2021 23:00:00 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Don't clean up LLVM state when exiting in a bad way" }, { "msg_contents": "> So I wonder, isn't the fixed usage issue specific to LLVM 7\n\nThat's definitely possible. I was unable to reproduce the issue I shared in my original email when postgres was compiled with LLVM 10. \n\nThat's also why I sent an email to the pgsql-pkg-yum mailing list about options to use a newer version of LLVM on CentOS 7: https://www.postgresql.org/message-id/flat/AM5PR83MB0178475D87EFA290A4D0793DF7FF9%40AM5PR83MB0178.EURPRD83.prod.outlook.com (no response so far though)\n\n", "msg_date": "Tue, 14 Sep 2021 20:36:44 +0000", "msg_from": "Jelte Fennema <Jelte.Fennema@microsoft.com>", "msg_from_op": true, "msg_subject": "Re: [EXTERNAL] Re: Don't clean up LLVM state when exiting in a bad\n way" } ]
[ { "msg_contents": "Hi hackers,\r\n\r\nI received a report of missing privileges after an upgrade, and I\r\nbelieve I've traced it back to pg_dump's handling of ALTER DEFAULT\r\nPRIVILEGES IN SCHEMA. I did find a recent report [0] that looks\r\nrelated, but I didn't see any follow-ups on that thread. It looks\r\nlike the issue dates back to the introduction of pg_init_privs in v9.6\r\n[1] [2].\r\n\r\nA simple reproduction of the issue is to run pg_dump after the\r\nfollowing command is run:\r\n\r\n ALTER DEFAULT PRIVILEGES FOR ROLE nathan IN SCHEMA test GRANT EXECUTE ON FUNCTIONS TO PUBLIC;\r\n\r\npg_dump will emit this command for this ACL:\r\n\r\n ALTER DEFAULT PRIVILEGES FOR ROLE nathan IN SCHEMA test REVOKE ALL ON FUNCTIONS FROM nathan;\r\n\r\nThe problem appears to be that pg_dump is comparing the entries in\r\npg_default_acl to the default ACL (i.e., acldefault()). This is fine\r\nfor \"global\" entries (i.e., entries with no schema specified), but it\r\ndoesn't work for \"non-global\" entries (i.e., entries with a schema\r\nspecified). This is because the default for a non-global entry is\r\nactually an empty ACL. aclchk.c has the following comment:\r\n\r\n /*\r\n * The default for a global entry is the hard-wired default ACL for the\r\n * particular object type. The default for non-global entries is an empty\r\n * ACL. This must be so because global entries replace the hard-wired\r\n * defaults, while others are added on.\r\n */\r\n\r\nI've attached a quick hack that seems to fix this by adjusting the\r\npg_dump query to use NULL instead of acldefault() for non-global\r\nentries. I'm posting this early in order to gather thoughts on the\r\napproach and to make sure I'm not missing something obvious.\r\n\r\nNathan\r\n\r\n[0] https://postgr.es/m/111621616618184%40mail.yandex.ru\r\n[1] https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=23f34fa\r\n[2] https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=e2090d9", "msg_date": "Wed, 18 Aug 2021 17:09:44 +0000", "msg_from": "\"Bossart, Nathan\" <bossartn@amazon.com>", "msg_from_op": true, "msg_subject": "pg_dump handling of ALTER DEFAULT PRIVILEGES IN SCHEMA" }, { "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\nThe patch looks fine and successfully fixes the issue of missing privileges issue.\n\nThe new status of this patch is: Ready for Committer\n", "msg_date": "Mon, 23 Aug 2021 08:44:48 +0000", "msg_from": "Muhammad Usama <m.usama@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg_dump handling of ALTER DEFAULT PRIVILEGES IN SCHEMA" }, { "msg_contents": "\"Bossart, Nathan\" <bossartn@amazon.com> writes:\n> The problem appears to be that pg_dump is comparing the entries in\n> pg_default_acl to the default ACL (i.e., acldefault()). This is fine\n> for \"global\" entries (i.e., entries with no schema specified), but it\n> doesn't work for \"non-global\" entries (i.e., entries with a schema\n> specified). This is because the default for a non-global entry is\n> actually an empty ACL.\n\nGood point.\n\n> I've attached a quick hack that seems to fix this by adjusting the\n> pg_dump query to use NULL instead of acldefault() for non-global\n> entries. I'm posting this early in order to gather thoughts on the\n> approach and to make sure I'm not missing something obvious.\n\nI find this impossible to comment on as to correctness, because the patch\nis nigh unreadable. \"case_stmt\" is a pretty darn opaque variable name,\nand the lack of comments doesn't help, and I don't really think that you\nchose good semantics for it anyway. Probably it would be better for the\nnew argument to be along the lines of \"bool is_default_acl\", and allow\nbuildACLQueries to know what it should put in when that's true.\n\nI'm kind of allergic to this SQL coding style, too. It expects the\nbackend to expend many thousands of cycles parsing and then optimizing\naway a useless CASE, to save a couple of lines of code and a few cycles\non the client side. Nor is doing the query this way even particularly\nreadable on the client side.\n\nLastly, there probably should be a test case or two.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 05 Sep 2021 13:07:26 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_dump handling of ALTER DEFAULT PRIVILEGES IN SCHEMA" }, { "msg_contents": "On 9/5/21, 10:08 AM, \"Tom Lane\" <tgl@sss.pgh.pa.us> wrote:\r\n> \"Bossart, Nathan\" <bossartn@amazon.com> writes:\r\n>> I've attached a quick hack that seems to fix this by adjusting the\r\n>> pg_dump query to use NULL instead of acldefault() for non-global\r\n>> entries. I'm posting this early in order to gather thoughts on the\r\n>> approach and to make sure I'm not missing something obvious.\r\n>\r\n> I find this impossible to comment on as to correctness, because the patch\r\n> is nigh unreadable. \"case_stmt\" is a pretty darn opaque variable name,\r\n> and the lack of comments doesn't help, and I don't really think that you\r\n> chose good semantics for it anyway. Probably it would be better for the\r\n> new argument to be along the lines of \"bool is_default_acl\", and allow\r\n> buildACLQueries to know what it should put in when that's true.\r\n\r\nMy apologies. This definitely shouldn't have been marked as ready-\r\nfor-committer. FWIW this is exactly the sort of feedback I was hoping\r\nto get before I expended more effort on this patch.\r\n\r\n> I'm kind of allergic to this SQL coding style, too. It expects the\r\n> backend to expend many thousands of cycles parsing and then optimizing\r\n> away a useless CASE, to save a couple of lines of code and a few cycles\r\n> on the client side. Nor is doing the query this way even particularly\r\n> readable on the client side.\r\n\r\nIs there a specific style you have in mind for this change, or is your\r\npoint that the CASE statement should only be reserved for when\r\nis_default_acl is true?\r\n\r\n> Lastly, there probably should be a test case or two.\r\n\r\nOf course. That will be in the next revision.\r\n\r\nNathan\r\n\r\n", "msg_date": "Sun, 5 Sep 2021 17:57:11 +0000", "msg_from": "\"Bossart, Nathan\" <bossartn@amazon.com>", "msg_from_op": true, "msg_subject": "Re: pg_dump handling of ALTER DEFAULT PRIVILEGES IN SCHEMA" }, { "msg_contents": "\"Bossart, Nathan\" <bossartn@amazon.com> writes:\n> On 9/5/21, 10:08 AM, \"Tom Lane\" <tgl@sss.pgh.pa.us> wrote:\n>> I'm kind of allergic to this SQL coding style, too. It expects the\n>> backend to expend many thousands of cycles parsing and then optimizing\n>> away a useless CASE, to save a couple of lines of code and a few cycles\n>> on the client side. Nor is doing the query this way even particularly\n>> readable on the client side.\n\n> Is there a specific style you have in mind for this change, or is your\n> point that the CASE statement should only be reserved for when\n> is_default_acl is true?\n\nI'd be inclined to split this logic out into a separate if-statement,\nalong the lines of\n\n\t... build some of the query ...\n\n\tif (is_default_acl)\n\t{\n\t /* The reference ACL is empty for schema-local default ACLs */\n\t appendPQExpBuffer(..., \"CASE WHEN ... THEN pg_catalog.acldefault(%s,%s) ELSE NULL END\", ...);\n\t}\n\telse\n\t{\n\t /* For other cases, the reference is always acldefault() */\n\t appendPQExpBuffer(..., \"pg_catalog.acldefault(%s,%s)\", ...);\n\t}\n\n\t... build rest of the query ...\n\nI think this is more readable than one giant printf, and not incidentally\nit allows room for some helpful comments.\n\n(I kind of wonder if we shouldn't try to refactor buildACLQueries to\nreduce code duplication and add comments while we're at it. The existing\ncode seems pretty awful from a readability standpoint already. I don't\nhave any clear idea about what to do instead, though.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 05 Sep 2021 15:14:16 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_dump handling of ALTER DEFAULT PRIVILEGES IN SCHEMA" }, { "msg_contents": "On 9/5/21, 12:14 PM, \"Tom Lane\" <tgl@sss.pgh.pa.us> wrote:\r\n> \"Bossart, Nathan\" <bossartn@amazon.com> writes:\r\n>> Is there a specific style you have in mind for this change, or is your\r\n>> point that the CASE statement should only be reserved for when\r\n>> is_default_acl is true?\r\n>\r\n> I'd be inclined to split this logic out into a separate if-statement,\r\n> along the lines of\r\n\r\nGot it, thanks.\r\n\r\nNathan\r\n\r\n", "msg_date": "Sun, 5 Sep 2021 19:53:21 +0000", "msg_from": "\"Bossart, Nathan\" <bossartn@amazon.com>", "msg_from_op": true, "msg_subject": "Re: pg_dump handling of ALTER DEFAULT PRIVILEGES IN SCHEMA" }, { "msg_contents": "On 9/5/21, 12:58 PM, \"Bossart, Nathan\" <bossartn@amazon.com> wrote:\r\n> On 9/5/21, 12:14 PM, \"Tom Lane\" <tgl@sss.pgh.pa.us> wrote:\r\n>> I'd be inclined to split this logic out into a separate if-statement,\r\n>> along the lines of\r\n>\r\n> Got it, thanks.\r\n\r\nAttached is an attempt at cleaning the patch up and adding an\r\ninformative comment and a test case.\r\n\r\nNathan", "msg_date": "Mon, 6 Sep 2021 06:31:10 +0000", "msg_from": "\"Bossart, Nathan\" <bossartn@amazon.com>", "msg_from_op": true, "msg_subject": "Re: pg_dump handling of ALTER DEFAULT PRIVILEGES IN SCHEMA" }, { "msg_contents": "On 9/5/21, 11:33 PM, \"Bossart, Nathan\" <bossartn@amazon.com> wrote:\r\n> Attached is an attempt at cleaning the patch up and adding an\r\n> informative comment and a test case.\r\n\r\nFor future reference, there was another thread for this bug [0], and a\r\nfix was committed [1].\r\n\r\nNathan\r\n\r\n[0] https://postgr.es/m/CAA3qoJnr2%2B1dVJObNtfec%3DqW4Z0nz%3DA9%2Br5bZKoTSy5RDjskMw%40mail.gmail.com\r\n[1] https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=2acc84c\r\n\r\n", "msg_date": "Fri, 22 Oct 2021 20:14:33 +0000", "msg_from": "\"Bossart, Nathan\" <bossartn@amazon.com>", "msg_from_op": true, "msg_subject": "Re: pg_dump handling of ALTER DEFAULT PRIVILEGES IN SCHEMA" } ]
[ { "msg_contents": "Quite a few years ago Microsoft recognized that with windows copy and\nxcopy commands had some serious inadequacies. They therefore created\nrobocopy <https://ss64.com/nt/robocopy.html> as a replacement, and it\nhas shipped in all modern versions of Windows. At any rate it's\nsomething I think we should support. Unfortunately it has a couple of\nwrinkles. First, it actually returns non-zero in most success\nconditions. See <https://ss64.com/nt/robocopy-exit.html> That can be\nhandled by calling it via a script. But the other thing is that the\ncalling syntax is different. It's \"robocopy sourcedir destdir filename\"\nIt doesn't allow for files to be renamed, but luckily we don't normally\nneed it to. However, what we do need is the ability to get the directory\nname from the %p parameter for archive_command and restore_command,\nstripped of the actual file name. I therefore suggest in both cases we\nimplement a %P escape to allow for it. Should be a pretty tiny patch.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Wed, 18 Aug 2021 17:01:40 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": true, "msg_subject": "support for windows robocopy in archive_command and restore_command" }, { "msg_contents": "On Thu, Aug 19, 2021 at 5:01 AM Andrew Dunstan <andrew@dunslane.net> wrote:\n>\n> It doesn't allow for files to be renamed, but luckily we don't normally\n> need it to.\n\nDoesn't the recovery ask to recover the WAL files in\npg_wal/RECOVERYXLOG and the history files in pg_wal/RECOVERYHISTORY\nrather than the original names?\n\n\n", "msg_date": "Thu, 19 Aug 2021 10:32:15 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: support for windows robocopy in archive_command and\n restore_command" }, { "msg_contents": "\nOn 8/18/21 10:32 PM, Julien Rouhaud wrote:\n> On Thu, Aug 19, 2021 at 5:01 AM Andrew Dunstan <andrew@dunslane.net> wrote:\n>> It doesn't allow for files to be renamed, but luckily we don't normally\n>> need it to.\n> Doesn't the recovery ask to recover the WAL files in\n> pg_wal/RECOVERYXLOG and the history files in pg_wal/RECOVERYHISTORY\n> rather than the original names?\n\n\nOh, darn. I was looking at what pg_rewind does; it uses the same name.\n\n\nWell, maybe we need to scrub that idea -(\n\n\ncheers\n\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Wed, 18 Aug 2021 23:25:50 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": true, "msg_subject": "Re: support for windows robocopy in archive_command and\n restore_command" } ]
[ { "msg_contents": "Hello.\n\nWhile I was examining message translation for PG14, I found some\nmessages that would need to be fixed.\n\n0001 is a fix for perhaps-leftovers of the recent message cleanups\nrelated to \"positive integer\"(fd90f6ba7a).\n\n0002 is a fix for a maybe-mistake in message convention of a recent\nfix in ECPG of linked-connection (about trailing period and\nlower-cased commad names)\n\n0003 is a fix for remaining \"positive\" use, which are in doubt in\nworthiness to fix..\n\nPlease find the attached.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Thu, 19 Aug 2021 17:03:15 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": true, "msg_subject": "Some leftovers of recent message cleanup?" }, { "msg_contents": "\n\nOn 2021/08/19 17:03, Kyotaro Horiguchi wrote:\n> Hello.\n> \n> While I was examining message translation for PG14, I found some\n> messages that would need to be fixed.\n> \n> 0001 is a fix for perhaps-leftovers of the recent message cleanups\n> related to \"positive integer\"(fd90f6ba7a).\n\nThere are still other many messages using \"positive\" and \"negative\" keywords.\nWe should also fix them at all?\n\nBTW, we discussed this before at [1] and concluded that at first\nwe should focus on the fix of the ambiguous \"non-negative\" and\nlet \"positive\" and \"negative\" keywords as they are.\n\n[1]\nhttps://www.postgresql.org/message-id/CALj2ACV7KDM8R=SrDbxvxT5yMDi+BMWVVV_UwmmHiii1pumr8Q@mail.gmail.com\n\n> 0002 is a fix for a maybe-mistake in message convention of a recent\n> fix in ECPG of linked-connection (about trailing period and\n> lower-cased commad names)\n\nLGTM.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Thu, 19 Aug 2021 20:29:42 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Some leftovers of recent message cleanup?" }, { "msg_contents": "At Thu, 19 Aug 2021 20:29:42 +0900, Fujii Masao <masao.fujii@oss.nttdata.com> wrote in \n> On 2021/08/19 17:03, Kyotaro Horiguchi wrote:\n> > Hello.\n> > While I was examining message translation for PG14, I found some\n> > messages that would need to be fixed.\n> > 0001 is a fix for perhaps-leftovers of the recent message cleanups\n> > related to \"positive integer\"(fd90f6ba7a).\n> \n> There are still other many messages using \"positive\" and \"negative\"\n> keywords.\n> We should also fix them at all?\n\nI'm not sure, or no if anything. My main point here is not to avoid\nuse of such kind of words, but reducing variations of the effectively\nthe same message from the view of translator burden. The two messages\nin 0001 are in that category. I noticed those messages accidentally. I\ndon't think they are the only instance of such divergence, but I'm not\ngoing to do a comprehensive examination of such divergences.. (Or do I\nneed to check that more comprehensively?)\n\n> BTW, we discussed this before at [1] and concluded that at first\n> we should focus on the fix of the ambiguous \"non-negative\" and\n> let \"positive\" and \"negative\" keywords as they are.\n> \n> [1]\n> https://www.postgresql.org/message-id/CALj2ACV7KDM8R=SrDbxvxT5yMDi+BMWVVV_UwmmHiii1pumr8Q@mail.gmail.com\n\nUnderstood. I agree that point and 0003 is worthless as I anticipated.\nI misunderstood that \"positive\" were included in the do-not-use list.\n\n> > 0002 is a fix for a maybe-mistake in message convention of a recent\n> > fix in ECPG of linked-connection (about trailing period and\n> > lower-cased commad names)\n> \n> LGTM.\n\nThanks. So I excluded 0003 and added a fix for regression tests\naffected by 0001. (I'm a bit surprised that 0002 doesn't break\nregression tests.)\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Fri, 20 Aug 2021 11:53:08 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Some leftovers of recent message cleanup?" }, { "msg_contents": "\n\nOn 2021/08/20 11:53, Kyotaro Horiguchi wrote:\n> At Thu, 19 Aug 2021 20:29:42 +0900, Fujii Masao <masao.fujii@oss.nttdata.com> wrote in\n>> On 2021/08/19 17:03, Kyotaro Horiguchi wrote:\n>>> Hello.\n>>> While I was examining message translation for PG14, I found some\n>>> messages that would need to be fixed.\n>>> 0001 is a fix for perhaps-leftovers of the recent message cleanups\n>>> related to \"positive integer\"(fd90f6ba7a).\n>>\n>> There are still other many messages using \"positive\" and \"negative\"\n>> keywords.\n>> We should also fix them at all?\n> \n> I'm not sure, or no if anything. My main point here is not to avoid\n> use of such kind of words, but reducing variations of the effectively\n> the same message from the view of translator burden. The two messages\n> in 0001 are in that category. I noticed those messages accidentally. I\n> don't think they are the only instance of such divergence, but I'm not\n> going to do a comprehensive examination of such divergences.. (Or do I\n> need to check that more comprehensively?)\n\n\nUnderstood.\n\n-\t\t\t\t\t errmsg(\"modulus for hash partition must be a positive integer\")));\n+\t\t\t\t\t errmsg(\"modulus for hash partition must be an integer greater than zero\")));\n\n\"an integer greater\" should be \"an integer value greater\" because\nwe use that words in other similar log messages like \"modulus for\nhash partition must be an integer value greater than zero\"\nin src/backend/partitioning/partbounds.c?\n\nI'm thinking to back-patch this to v11 where hash partitioning\nwas supported. On the other hand, the following change should\nbe back-patched to all supported versions.\n\n-\t\t\t\t\t\t\t errmsg(\"distance in phrase operator should not be greater than %d\",\n+\t\t\t\t\t\t\t errmsg(\"distance in phrase operator must be an integer value between zero and %d inclusive\",\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Fri, 20 Aug 2021 19:36:02 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Some leftovers of recent message cleanup?" }, { "msg_contents": "At Fri, 20 Aug 2021 19:36:02 +0900, Fujii Masao <masao.fujii@oss.nttdata.com> wrote in \n> \n> \n> On 2021/08/20 11:53, Kyotaro Horiguchi wrote:\n> > At Thu, 19 Aug 2021 20:29:42 +0900, Fujii Masao\n> > <masao.fujii@oss.nttdata.com> wrote in\n> >> On 2021/08/19 17:03, Kyotaro Horiguchi wrote:\n> >>> Hello.\n> >>> While I was examining message translation for PG14, I found some\n> >>> messages that would need to be fixed.\n> >>> 0001 is a fix for perhaps-leftovers of the recent message cleanups\n> >>> related to \"positive integer\"(fd90f6ba7a).\n> >>\n> >> There are still other many messages using \"positive\" and \"negative\"\n> >> keywords.\n> >> We should also fix them at all?\n> > I'm not sure, or no if anything. My main point here is not to avoid\n> > use of such kind of words, but reducing variations of the effectively\n> > the same message from the view of translator burden. The two messages\n> > in 0001 are in that category. I noticed those messages accidentally. I\n> > don't think they are the only instance of such divergence, but I'm not\n> > going to do a comprehensive examination of such divergences.. (Or do I\n> > need to check that more comprehensively?)\n> \n> \n> Understood.\n> \n> -\t\t\t\t\t errmsg(\"modulus for hash partition must be a positive\n> -\t\t\t\t\t integer\")));\n> + errmsg(\"modulus for hash partition must be an integer greater than\n> zero\")));\n> \n> \"an integer greater\" should be \"an integer value greater\" because\n> we use that words in other similar log messages like \"modulus for\n> hash partition must be an integer value greater than zero\"\n> in src/backend/partitioning/partbounds.c?\n\nUgh... Of course. I thought I did that way but the actual file is\nincorrect... Fixed that in the attached.\n\n> I'm thinking to back-patch this to v11 where hash partitioning\n> was supported. On the other hand, the following change should\n\nIf I'm not missing something, back to 13, where the \"word change\" took\nplace? For 11 and 12, we need to change the *both* messages.\n\n\nv11, 12\n./src/backend/parser/parse_utilcmd.c\u00003744:\t\t\t\t\t errmsg(\"modulus for hash partition must be a positive integer\")));\nBinary file ./src/backend/parser/gram.o matches\n./src/backend/partitioning/partbounds.c\u00002086:\t\t\t\t errmsg(\"modulus for hash partition must be a positive integer\")));\n\nv13, 14\n./src/backend/parser/parse_utilcmd.c\u00003942:\t\t\t\t\t errmsg(\"modulus for hash partition must be a positive integer\")));\n./src/backend/partitioning/partbounds.c\u00004640:\t\t\t\t errmsg(\"modulus for hash partition must be an integer value greater than zero\")));\n\n\n> be back-patched to all supported versions.\n> \n> -\t\t\t\t\t\t\t errmsg(\"distance in phrase operator should not be\n> -\t\t\t\t\t\t\t greater than %d\",\n> + errmsg(\"distance in phrase operator must be an integer value between\n> zero and %d inclusive\",\n\nThe message is inconsistent since before the \"postive\" patch^^;\n\nv10, 11, 12\n./src/backend/utils/adt/tsquery.c\u0000200:\t\t\t\t\t\t\t errmsg(\"distance in phrase operator should not be greater than %d\",\n./src/backend/utils/adt/tsquery_op.c\u0000123:\t\t\t\t errmsg(\"distance in phrase operator should be non-negative and less than %d\",\n\nv13,14\n./src/backend/utils/adt/tsquery.c\u0000200:\t\t\t\t\t\t\t errmsg(\"distance in phrase operator should not be greater than %d\",\n./src/backend/utils/adt/tsquery_op.c\u0000124:\t\t\t\t errmsg(\"distance in phrase operator must be an integer value between zero and %d inclusive\",\n\nSo this patch is meaningful only for v13 and later, too. Not sure what\nto do for v12 and earlier but doesn't seem to be in much necessity.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Mon, 23 Aug 2021 15:27:25 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Some leftovers of recent message cleanup?" }, { "msg_contents": "On 2021/08/23 15:27, Kyotaro Horiguchi wrote:\n> So this patch is meaningful only for v13 and later, too. Not sure what\n> to do for v12 and earlier but doesn't seem to be in much necessity.\n\nProbably I failed to get your point... I was thinking that\nyour 0001 patch can be back-patched to v11. And also\nthe attached patch can be applied to v10 and v9.6. If we do this,\nthe log messages can be consistent between versions.\nBut you think that we should not change the log messages\nin v12 or before, for some reasons?\n\nI pushed your 0002 patch. Thanks!\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION", "msg_date": "Wed, 25 Aug 2021 10:05:25 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Some leftovers of recent message cleanup?" }, { "msg_contents": "At Wed, 25 Aug 2021 10:05:25 +0900, Fujii Masao <masao.fujii@oss.nttdata.com> wrote in \n> \n> \n> On 2021/08/23 15:27, Kyotaro Horiguchi wrote:\n> > So this patch is meaningful only for v13 and later, too. Not sure what\n> > to do for v12 and earlier but doesn't seem to be in much necessity.\n> \n> Probably I failed to get your point... I was thinking that\n> your 0001 patch can be back-patched to v11. And also\n> the attached patch can be applied to v10 and v9.6. If we do this,\n> the log messages can be consistent between versions.\n> But you think that we should not change the log messages\n> in v12 or before, for some reasons?\n\nSigh. The message of partbounds.c of v11,12 cited there was just\nwrong. So, you're right that it is simply applicable to v11 and\nlater. Sorry for the confusion.\n\n> I pushed your 0002 patch. Thanks!\n\nThanks for committing!\n\nregares.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Wed, 25 Aug 2021 10:50:19 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Some leftovers of recent message cleanup?" }, { "msg_contents": "\n\nOn 2021/08/25 10:50, Kyotaro Horiguchi wrote:\n> Sigh. The message of partbounds.c of v11,12 cited there was just\n> wrong. So, you're right that it is simply applicable to v11 and\n> later. Sorry for the confusion.\n\nI separated the patch into two, to make the commit message of each change clear.\nAnd I pushed them. Thanks!\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n", "msg_date": "Wed, 25 Aug 2021 11:54:31 +0900", "msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>", "msg_from_op": false, "msg_subject": "Re: Some leftovers of recent message cleanup?" } ]
[ { "msg_contents": "The current FE/BE protocol assumes that the client is talking to the\nserver directly. If middleware wants to do something like load\nbalancing, the only current option is to inspect the incoming commands\nand take action from that. That approach performs poorly and has\nproven difficult to maintain, limiting the functionality in Postgres\necosystem middleware.\n\nIt would be useful to have a way to speak to middleware within a\nsession or prior to each command. There are ways to frig this and\nobviously it can always be done out-of-core, but there is a clear\nrequirement for various client tools to agree a standard way for them\nto send messages to middleware rather than the database server. If we\nget PostgreSQL Project approval for this, then authors of client and\nmiddleware tools will know how to interoperate and can begin adding\nfeatures to take advantage of this, allowing the Postgres ecosystem to\nimprove and extend its middleware.\n\nByte1('M')\nIdentifies the message as a middleware message. (Or perhaps use 'U'\nfor User Message?).\n\nInt32\nLength of message contents in bytes, including self.\n\nInt64\nRouting/class identifier, allowing middleware to quickly ignore whole\nclasses of message if not appropriate. We would run some kind of\nallocation scheme to ensure unique meaning, probably via the Postgres\nWiki. The first 2 billion values would be reserved for allocation by\nthe PostgreSQL Project itself, values beyond that open for external\nallocation.\n\nByten\nThe message itself, where n is the remaining bytes in the message.\n\nThe message is intended for middleware only. The server always ignores\nthese messages, with an optional debug facility that can be enabled to\nallow printing NOTICEs to allow testing.\n\nI will supply a patch to any agreed message format, together with a\nnew libpq call to utilise this.\n\nIn summary: the patch is easy, the point is we need agreement to allow\nand encourage interoperation between clients and middleware.\n\nThoughts?\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/\n\n\n", "msg_date": "Thu, 19 Aug 2021 09:33:05 +0100", "msg_from": "Simon Riggs <simon.riggs@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Middleware Messages for FE/BE" }, { "msg_contents": "Need for this does come up quite often so I very much support this.\n\nIn addition to keeping a registry there likely need to be some other\n\"generally agreed\" rules as well, like\n* it being safe to ignore any and all of the middleware messages (at\nleast with no degradation from the state of not having them)\n* and maybe even a standard way to turn them on and off.\n\n On/Off switch could be of course done using flags for each\nindividual use case, but it would be good to agree conventions.\n\nAnother thing to agree would be a set of standard messages, like \"I am\noverloaded, consider moving some load away\" or \"Planning to switch\nover to replica x.x.x.x, please follow\"\n\n-----\nHannu Krosing\nGoogle Cloud - We have a long list of planned contributions and we are hiring.\nContact me if interested.\n\n\nOn Thu, Aug 19, 2021 at 10:33 AM Simon Riggs\n<simon.riggs@enterprisedb.com> wrote:\n>\n> The current FE/BE protocol assumes that the client is talking to the\n> server directly. If middleware wants to do something like load\n> balancing, the only current option is to inspect the incoming commands\n> and take action from that. That approach performs poorly and has\n> proven difficult to maintain, limiting the functionality in Postgres\n> ecosystem middleware.\n>\n> It would be useful to have a way to speak to middleware within a\n> session or prior to each command. There are ways to frig this and\n> obviously it can always be done out-of-core, but there is a clear\n> requirement for various client tools to agree a standard way for them\n> to send messages to middleware rather than the database server. If we\n> get PostgreSQL Project approval for this, then authors of client and\n> middleware tools will know how to interoperate and can begin adding\n> features to take advantage of this, allowing the Postgres ecosystem to\n> improve and extend its middleware.\n>\n> Byte1('M')\n> Identifies the message as a middleware message. (Or perhaps use 'U'\n> for User Message?).\n>\n> Int32\n> Length of message contents in bytes, including self.\n>\n> Int64\n> Routing/class identifier, allowing middleware to quickly ignore whole\n> classes of message if not appropriate. We would run some kind of\n> allocation scheme to ensure unique meaning, probably via the Postgres\n> Wiki. The first 2 billion values would be reserved for allocation by\n> the PostgreSQL Project itself, values beyond that open for external\n> allocation.\n>\n> Byten\n> The message itself, where n is the remaining bytes in the message.\n>\n> The message is intended for middleware only. The server always ignores\n> these messages, with an optional debug facility that can be enabled to\n> allow printing NOTICEs to allow testing.\n>\n> I will supply a patch to any agreed message format, together with a\n> new libpq call to utilise this.\n>\n> In summary: the patch is easy, the point is we need agreement to allow\n> and encourage interoperation between clients and middleware.\n>\n> Thoughts?\n>\n> --\n> Simon Riggs http://www.EnterpriseDB.com/\n>\n>\n\n\n", "msg_date": "Thu, 19 Aug 2021 11:33:22 +0200", "msg_from": "Hannu Krosing <hannuk@google.com>", "msg_from_op": false, "msg_subject": "Re: Middleware Messages for FE/BE" }, { "msg_contents": "One more set of \"standard middleware messages\" clients/middleware\ncould turn on could be reporting LSNs\n * various local LSNs for progress of WAL persisting\n * reporting replication state of some or all replicas\n\n-----\nHannu Krosing\nGoogle Cloud - We have a long list of planned contributions and we are hiring.\nContact me if interested.\n\nOn Thu, Aug 19, 2021 at 11:33 AM Hannu Krosing <hannuk@google.com> wrote:\n>\n> Need for this does come up quite often so I very much support this.\n>\n> In addition to keeping a registry there likely need to be some other\n> \"generally agreed\" rules as well, like\n> * it being safe to ignore any and all of the middleware messages (at\n> least with no degradation from the state of not having them)\n> * and maybe even a standard way to turn them on and off.\n>\n> On/Off switch could be of course done using flags for each\n> individual use case, but it would be good to agree conventions.\n>\n> Another thing to agree would be a set of standard messages, like \"I am\n> overloaded, consider moving some load away\" or \"Planning to switch\n> over to replica x.x.x.x, please follow\"\n>\n> -----\n> Hannu Krosing\n> Google Cloud - We have a long list of planned contributions and we are hiring.\n> Contact me if interested.\n>\n>\n> On Thu, Aug 19, 2021 at 10:33 AM Simon Riggs\n> <simon.riggs@enterprisedb.com> wrote:\n> >\n> > The current FE/BE protocol assumes that the client is talking to the\n> > server directly. If middleware wants to do something like load\n> > balancing, the only current option is to inspect the incoming commands\n> > and take action from that. That approach performs poorly and has\n> > proven difficult to maintain, limiting the functionality in Postgres\n> > ecosystem middleware.\n> >\n> > It would be useful to have a way to speak to middleware within a\n> > session or prior to each command. There are ways to frig this and\n> > obviously it can always be done out-of-core, but there is a clear\n> > requirement for various client tools to agree a standard way for them\n> > to send messages to middleware rather than the database server. If we\n> > get PostgreSQL Project approval for this, then authors of client and\n> > middleware tools will know how to interoperate and can begin adding\n> > features to take advantage of this, allowing the Postgres ecosystem to\n> > improve and extend its middleware.\n> >\n> > Byte1('M')\n> > Identifies the message as a middleware message. (Or perhaps use 'U'\n> > for User Message?).\n> >\n> > Int32\n> > Length of message contents in bytes, including self.\n> >\n> > Int64\n> > Routing/class identifier, allowing middleware to quickly ignore whole\n> > classes of message if not appropriate. We would run some kind of\n> > allocation scheme to ensure unique meaning, probably via the Postgres\n> > Wiki. The first 2 billion values would be reserved for allocation by\n> > the PostgreSQL Project itself, values beyond that open for external\n> > allocation.\n> >\n> > Byten\n> > The message itself, where n is the remaining bytes in the message.\n> >\n> > The message is intended for middleware only. The server always ignores\n> > these messages, with an optional debug facility that can be enabled to\n> > allow printing NOTICEs to allow testing.\n> >\n> > I will supply a patch to any agreed message format, together with a\n> > new libpq call to utilise this.\n> >\n> > In summary: the patch is easy, the point is we need agreement to allow\n> > and encourage interoperation between clients and middleware.\n> >\n> > Thoughts?\n> >\n> > --\n> > Simon Riggs http://www.EnterpriseDB.com/\n> >\n> >\n\n\n", "msg_date": "Thu, 19 Aug 2021 11:36:47 +0200", "msg_from": "Hannu Krosing <hannuk@google.com>", "msg_from_op": false, "msg_subject": "Re: Middleware Messages for FE/BE" }, { "msg_contents": "Actually the way I have been thinking about this would be a message\n\n \"Hey replica x.x.x.x, please take over the write head role\"\n\nWhich would\n\n1. cause the replica x.x.x.x to self-promote at this point-in-WAL\n1A - optionally the old write head becomes a replica (it should\nmention it in message if it plans to stay around as a replica)\n2. tells other replicas to switch over and start replicating from it\n3. tells all connected clients to switch, if they need read-write access.\n\nThis could be even done without timeline switch, as it should\nguarantee that there is no split brain writing\nOf course there are (and should be) ways to still use the WALs\nnormally for cases where replica x.x.x.x does not exists, like PITR\n\nAnd making this play nicely with Logical Decoding is another can of\nworms needing to be solved, but it is a start to becoming \"Cloud\nNative\" :)\n\n-----\nHannu Krosing\nGoogle Cloud - We have a long list of planned contributions and we are hiring.\nContact me if interested.\n\n\nOn Thu, Aug 19, 2021 at 11:36 AM Hannu Krosing <hannuk@google.com> wrote:\n>\n> One more set of \"standard middleware messages\" clients/middleware\n> could turn on could be reporting LSNs\n> * various local LSNs for progress of WAL persisting\n> * reporting replication state of some or all replicas\n>\n> -----\n> Hannu Krosing\n> Google Cloud - We have a long list of planned contributions and we are hiring.\n> Contact me if interested.\n>\n> On Thu, Aug 19, 2021 at 11:33 AM Hannu Krosing <hannuk@google.com> wrote:\n> >\n> > Need for this does come up quite often so I very much support this.\n> >\n> > In addition to keeping a registry there likely need to be some other\n> > \"generally agreed\" rules as well, like\n> > * it being safe to ignore any and all of the middleware messages (at\n> > least with no degradation from the state of not having them)\n> > * and maybe even a standard way to turn them on and off.\n> >\n> > On/Off switch could be of course done using flags for each\n> > individual use case, but it would be good to agree conventions.\n> >\n> > Another thing to agree would be a set of standard messages, like \"I am\n> > overloaded, consider moving some load away\" or \"Planning to switch\n> > over to replica x.x.x.x, please follow\"\n> >\n> > -----\n> > Hannu Krosing\n> > Google Cloud - We have a long list of planned contributions and we are hiring.\n> > Contact me if interested.\n> >\n> >\n> > On Thu, Aug 19, 2021 at 10:33 AM Simon Riggs\n> > <simon.riggs@enterprisedb.com> wrote:\n> > >\n> > > The current FE/BE protocol assumes that the client is talking to the\n> > > server directly. If middleware wants to do something like load\n> > > balancing, the only current option is to inspect the incoming commands\n> > > and take action from that. That approach performs poorly and has\n> > > proven difficult to maintain, limiting the functionality in Postgres\n> > > ecosystem middleware.\n> > >\n> > > It would be useful to have a way to speak to middleware within a\n> > > session or prior to each command. There are ways to frig this and\n> > > obviously it can always be done out-of-core, but there is a clear\n> > > requirement for various client tools to agree a standard way for them\n> > > to send messages to middleware rather than the database server. If we\n> > > get PostgreSQL Project approval for this, then authors of client and\n> > > middleware tools will know how to interoperate and can begin adding\n> > > features to take advantage of this, allowing the Postgres ecosystem to\n> > > improve and extend its middleware.\n> > >\n> > > Byte1('M')\n> > > Identifies the message as a middleware message. (Or perhaps use 'U'\n> > > for User Message?).\n> > >\n> > > Int32\n> > > Length of message contents in bytes, including self.\n> > >\n> > > Int64\n> > > Routing/class identifier, allowing middleware to quickly ignore whole\n> > > classes of message if not appropriate. We would run some kind of\n> > > allocation scheme to ensure unique meaning, probably via the Postgres\n> > > Wiki. The first 2 billion values would be reserved for allocation by\n> > > the PostgreSQL Project itself, values beyond that open for external\n> > > allocation.\n> > >\n> > > Byten\n> > > The message itself, where n is the remaining bytes in the message.\n> > >\n> > > The message is intended for middleware only. The server always ignores\n> > > these messages, with an optional debug facility that can be enabled to\n> > > allow printing NOTICEs to allow testing.\n> > >\n> > > I will supply a patch to any agreed message format, together with a\n> > > new libpq call to utilise this.\n> > >\n> > > In summary: the patch is easy, the point is we need agreement to allow\n> > > and encourage interoperation between clients and middleware.\n> > >\n> > > Thoughts?\n> > >\n> > > --\n> > > Simon Riggs http://www.EnterpriseDB.com/\n> > >\n> > >\n\n\n", "msg_date": "Thu, 19 Aug 2021 11:57:58 +0200", "msg_from": "Hannu Krosing <hannuk@google.com>", "msg_from_op": false, "msg_subject": "Re: Middleware Messages for FE/BE" }, { "msg_contents": "On Thu, 19 Aug 2021 at 10:33, Hannu Krosing <hannuk@google.com> wrote:\n>\n> Need for this does come up quite often so I very much support this.\n>\n> In addition to keeping a registry there likely need to be some other\n> \"generally agreed\" rules as well, like\n> * it being safe to ignore any and all of the middleware messages (at\n> least with no degradation from the state of not having them)\n> * and maybe even a standard way to turn them on and off.\n>\n> On/Off switch could be of course done using flags for each\n> individual use case, but it would be good to agree conventions.\n\nGood feedback and thoughts, thanks.\n\nBased on your interest, I will begin to code, but won't be ready for Sept CF.\n\n> Another thing to agree would be a set of standard messages, like \"I am\n> overloaded, consider moving some load away\" or \"Planning to switch\n> over to replica x.x.x.x, please follow\"\n\nThat sounds like a server->middleware message and existing mechanisms\nmight work for that already.\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/\n\n\n", "msg_date": "Thu, 19 Aug 2021 17:07:25 +0100", "msg_from": "Simon Riggs <simon.riggs@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Middleware Messages for FE/BE" }, { "msg_contents": "On Thu, 19 Aug 2021 at 10:58, Hannu Krosing <hannuk@google.com> wrote:\n>\n> Actually the way I have been thinking about this would be a message\n>\n> \"Hey replica x.x.x.x, please take over the write head role\"\n>\n> Which would\n>\n> 1. cause the replica x.x.x.x to self-promote at this point-in-WAL\n> 1A - optionally the old write head becomes a replica (it should\n> mention it in message if it plans to stay around as a replica)\n> 2. tells other replicas to switch over and start replicating from it\n> 3. tells all connected clients to switch, if they need read-write access.\n>\n> This could be even done without timeline switch, as it should\n> guarantee that there is no split brain writing\n> Of course there are (and should be) ways to still use the WALs\n> normally for cases where replica x.x.x.x does not exists, like PITR\n>\n> And making this play nicely with Logical Decoding is another can of\n> worms needing to be solved, but it is a start to becoming \"Cloud\n> Native\" :)\n\nGood ideas!\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/\n\n\n", "msg_date": "Thu, 19 Aug 2021 17:08:06 +0100", "msg_from": "Simon Riggs <simon.riggs@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Middleware Messages for FE/BE" }, { "msg_contents": "Hi Simon,\n\nOn 8/19/21 4:33 AM, Simon Riggs wrote:\n> The current FE/BE protocol assumes that the client is talking to the\n> server directly. If middleware wants to do something like load\n> balancing, the only current option is to inspect the incoming commands\n> and take action from that. That approach performs poorly and has\n> proven difficult to maintain, limiting the functionality in Postgres\n> ecosystem middleware.\n>\n> It would be useful to have a way to speak to middleware within a\n> session or prior to each command. There are ways to frig this and\n> obviously it can always be done out-of-core, but there is a clear\n> requirement for various client tools to agree a standard way for them\n> to send messages to middleware rather than the database server. If we\n> get PostgreSQL Project approval for this, then authors of client and\n> middleware tools will know how to interoperate and can begin adding\n> features to take advantage of this, allowing the Postgres ecosystem to\n> improve and extend its middleware.\n>\n> Byte1('M')\n> Identifies the message as a middleware message. (Or perhaps use 'U'\n> for User Message?).\n>\n> Int32\n> Length of message contents in bytes, including self.\n>\n> Int64\n> Routing/class identifier, allowing middleware to quickly ignore whole\n> classes of message if not appropriate. We would run some kind of\n> allocation scheme to ensure unique meaning, probably via the Postgres\n> Wiki. The first 2 billion values would be reserved for allocation by\n> the PostgreSQL Project itself, values beyond that open for external\n> allocation.\n>\n> Byten\n> The message itself, where n is the remaining bytes in the message.\n>\n> The message is intended for middleware only. The server always ignores\n> these messages, with an optional debug facility that can be enabled to\n> allow printing NOTICEs to allow testing.\n>\n> I will supply a patch to any agreed message format, together with a\n> new libpq call to utilise this.\n>\n> In summary: the patch is easy, the point is we need agreement to allow\n> and encourage interoperation between clients and middleware.\n>\n> Thoughts?\n>\n\nI would say that this is a PostgreSQL protocol v4 thing, as there is a \nbit more to it.\n\n\nThere is a need to trigger middleware functionality, but you need to \nquery the middleware stack first on what it supports - failover, load \nbalancing, ... And, what type of language is that ? SQL query ? Not all \nmiddleware support general SQL queries.\n\n\nOnce you have established what is supported and what isn't you need the \nclient driver (libpq is the very easy part) - so lets include Java, C#, \nRust, golang, ... - to understand their environment to trigger the \ncorrect message in the configured scenario. F.ex. how is multiple \napplication clusters connecting to the same middleware instance \n(connection pool) going to coordinate their 'M' message ?\n\n\nIf you are looking to configure the middleware instance then we can just \nuse the existing protocol with FE/Q; that said pgagroal has its own \nbinary protocol for admin payload.\n\n\nCould you expand on typical scenarios that you want to see implemented ?\n\n\nBest regards,\n\n  Jesper\n\n\n\n\n", "msg_date": "Thu, 19 Aug 2021 12:42:14 -0400", "msg_from": "Jesper Pedersen <jesper.pedersen@redhat.com>", "msg_from_op": false, "msg_subject": "Re: Middleware Messages for FE/BE" }, { "msg_contents": "On Thu, 19 Aug 2021 at 17:42, Jesper Pedersen\n<jesper.pedersen@redhat.com> wrote:\n\n> I would say that this is a PostgreSQL protocol v4 thing, as there is a\n> bit more to it.\n>\n>\n> There is a need to trigger middleware functionality, but you need to\n> query the middleware stack first on what it supports - failover, load\n> balancing, ... And, what type of language is that ? SQL query ? Not all\n> middleware support general SQL queries.\n\nAgreed. No part of my proposal mentioned SQL queries.\n\nWe need to be able to send the middleware a message. Replies can be\nsent as NoticeResponse, if needed, which already exists.\n\nIf you want to invent a new grammar for your middleware, cool, I'm not\nstopping you.\n\n> Once you have established what is supported and what isn't you need the\n> client driver (libpq is the very easy part) - so lets include Java, C#,\n> Rust, golang, ... - to understand their environment to trigger the\n> correct message in the configured scenario. F.ex. how is multiple\n> application clusters connecting to the same middleware instance\n> (connection pool) going to coordinate their 'M' message ?\n\nEach component can speak to the middleware to discover that, if it\nwishes. The middleware can coordinate.\n\n> If you are looking to configure the middleware instance then we can just\n> use the existing protocol with FE/Q;\n\nWhich is exactly the thing we already have and the very thing I said I\nwas trying to avoid.\n\n> that said pgagroal has its own binary protocol for admin payload.\n\nI want to empower all future middleware, not just support one. Perhaps\nwe can take code or ideas from pgagroal and put it in core? Please\nexplain the binary protocol some more.\n\n> Could you expand on typical scenarios that you want to see implemented ?\n\nI see this as a generalized interface that can be used for a great many things.\n* Failover managers\n* Load Balancers\n* Routing agents\n* Things I haven't thought of yet, but others may have\netc..\n\nWe are currently limited by the messages we can send efficiently.\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/\n\n\n", "msg_date": "Thu, 19 Aug 2021 18:13:20 +0100", "msg_from": "Simon Riggs <simon.riggs@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Middleware Messages for FE/BE" }, { "msg_contents": "Hi,\n\nOn 8/19/21 1:13 PM, Simon Riggs wrote:\n> We need to be able to send the middleware a message. Replies can be\n> sent as NoticeResponse, if needed, which already exists.\n> \n\nYeah, but you need the client driver - of all languages - to understand \nthat notice. And, if different middleware uses different codes then the \nproblem is just pushed to the client;\n\nJava: M|12|0 (Do you support failover ?) MW1: N|6|-|0 (meaning: yes)\nRust: M|12|0 (Do you support load balancing ?) MW2: N|6|-|0 (meaning: no)\n\nShould the middleware guess the client driver based on the startup \nmessage ? Or are you thinking about having a class identifier group for \neach client driver and then a massive \"switch/case\" inside each middleware ?\n\n>> Once you have established what is supported and what isn't you need the\n>> client driver (libpq is the very easy part) - so lets include Java, C#,\n>> Rust, golang, ... - to understand their environment to trigger the\n>> correct message in the configured scenario. F.ex. how is multiple\n>> application clusters connecting to the same middleware instance\n>> (connection pool) going to coordinate their 'M' message ?\n> \n> Each component can speak to the middleware to discover that, if it\n> wishes. The middleware can coordinate.\n> \n\nSo, application cluster 1 (written in Java) detects that a failover is \nneeded, and application cluster 2..N (written in Rust, C# and golang) \nshould detect that mid-transaction - or rollback and send their 'M' for \nthe same thing ?\n\n> I want to empower all future middleware, not just support one. Perhaps\n> we can take code or ideas from pgagroal and put it in core? Please\n> explain the binary protocol some more.\n> \n\nThere is nothing fancy there (see management.c) - so the official \nprotocol should be the focus.\n\n>> Could you expand on typical scenarios that you want to see implemented ?\n> \n> I see this as a generalized interface that can be used for a great many things.\n> * Failover managers\n> * Load Balancers\n> * Routing agents\n> * Things I haven't thought of yet, but others may have\n> etc..\n>\n\nMoving control to the client will make some of this harder. Maybe \nPeterE, Andrey and Tatsuo-san have additional feedback based on their \nexperience.\n\n> We are currently limited by the messages we can send efficiently.\n> \n\nThere are a lot of good ideas for the PostgreSQL protocol v4 already.\n\nBest regards,\n Jesper\n\n\n\n", "msg_date": "Thu, 19 Aug 2021 14:04:20 -0400", "msg_from": "Jesper Pedersen <jesper.pedersen@redhat.com>", "msg_from_op": false, "msg_subject": "Re: Middleware Messages for FE/BE" }, { "msg_contents": "On Thu, 19 Aug 2021 at 19:04, Jesper Pedersen\n<jesper.pedersen@redhat.com> wrote:\n\n> Should the middleware guess the client driver based on the startup\n> message ? Or are you thinking about having a class identifier group for\n> each client driver and then a massive \"switch/case\" inside each middleware ?\n\nThe question is how does a client communicate with middleware?\n\nThe message that would be sent would relate to the features of the\nmiddleware, while being agnostic as to the client driver.\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/\n\n\n", "msg_date": "Thu, 19 Aug 2021 19:29:31 +0100", "msg_from": "Simon Riggs <simon.riggs@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Middleware Messages for FE/BE" }, { "msg_contents": "Jesper, please don't confuse my ramblings with Simon's initial proposal.\n\nAs I understand, the original proposal was just about adding a new\nwire protocol message type, which then could be used for emitting\ncustom messages by middleware support extension - likely loaded as a\npreloaded shared library - and consumed by some middleware, which\ncould either be some proxy or connection pooler or something compiled\nas part of the libpq, JDBC or other client driver. So it was just\nabout providing extensibility to the protocol (the same way almost\neverything else in PostgreSQL is extensible).\n\nBut at least initially each middleware would process only it's own\nclass, so a single if() and not a big switch/case :)\n\nThe things I talked about were some forward-looking proposals on how\nto use this capability and that some of the messages may at some point\nbecome used / usable by more than a single middleware component at\nwhich point they should be standardised .\n\n-----\nHannu Krosing\nGoogle Cloud - We have a long list of planned contributions and we are hiring.\nContact me if interested.\n\nOn Thu, Aug 19, 2021 at 8:29 PM Simon Riggs\n<simon.riggs@enterprisedb.com> wrote:\n>\n> On Thu, 19 Aug 2021 at 19:04, Jesper Pedersen\n> <jesper.pedersen@redhat.com> wrote:\n>\n> > Should the middleware guess the client driver based on the startup\n> > message ? Or are you thinking about having a class identifier group for\n> > each client driver and then a massive \"switch/case\" inside each middleware ?\n>\n> The question is how does a client communicate with middleware?\n>\n> The message that would be sent would relate to the features of the\n> middleware, while being agnostic as to the client driver.\n>\n> --\n> Simon Riggs http://www.EnterpriseDB.com/\n>\n>\n\n\n", "msg_date": "Thu, 19 Aug 2021 21:52:38 +0200", "msg_from": "Hannu Krosing <hannuk@google.com>", "msg_from_op": false, "msg_subject": "Re: Middleware Messages for FE/BE" }, { "msg_contents": "Hi Hannu,\n\nOn 8/19/21 3:52 PM, Hannu Krosing wrote:\n> Jesper, please don't confuse my ramblings with Simon's initial proposal.\n> \n> As I understand, the original proposal was just about adding a new\n> wire protocol message type, which then could be used for emitting\n> custom messages by middleware support extension - likely loaded as a\n> preloaded shared library - and consumed by some middleware, which\n> could either be some proxy or connection pooler or something compiled\n> as part of the libpq, JDBC or other client driver. So it was just\n> about providing extensibility to the protocol (the same way almost\n> everything else in PostgreSQL is extensible).\n> \n\nYeah, but it is a change to the protocol which means that the client \ndrivers and middleware ecosystem needs to be updated to support that \nmessage.\n\nSo, if the message was added to the protocol we could add another \nmessage with the response to the request and make the protocol stricter, say\n\nFE/M\nInt32 - Length\nInt16 - Request type (0 == Query capability, 1 == Execute capability)\nInt32 - Capability type (0 == Failover, 1 == ..., ...)\n\nBE/?\nInt32 - Length\nInt32 - Capability type\nByte - Support (0 == No, 1 == Yes)\nByten - Additional information\n\nNone of the client driver interfaces (specification API, like JDBC) has \nfunctionality for this currently, so the client would need to type cast \nthe interface in all cases in order to get access to the trigger method, say\n\n org.postgresql.jdbc.PgConnection.failover()\n\nThere could be custom capability type codes that targets specific \nmiddleware like Simon suggested.\n\n> But at least initially each middleware would process only it's own\n> class, so a single if() and not a big switch/case :)\n>\n\nWith a defined baseline of capabilities the client drivers and \nmiddleware wouldn't have to invent their own codes.\n\n> The things I talked about were some forward-looking proposals on how\n> to use this capability and that some of the messages may at some point\n> become used / usable by more than a single middleware component at\n> which point they should be standardised .\n> \n\nIt would be good to see a PoC of one capability implemented from the \nclient to the middleware that deals with coordination at the client level.\n\nBest regards,\n Jesper\n\n\n\n", "msg_date": "Fri, 20 Aug 2021 08:58:59 -0400", "msg_from": "Jesper Pedersen <jesper.pedersen@redhat.com>", "msg_from_op": false, "msg_subject": "Re: Middleware Messages for FE/BE" }, { "msg_contents": "On Fri, 20 Aug 2021 at 13:59, Jesper Pedersen\n<jesper.pedersen@redhat.com> wrote:\n>\n> On 8/19/21 3:52 PM, Hannu Krosing wrote:\n> > Jesper, please don't confuse my ramblings with Simon's initial proposal.\n> >\n> > As I understand, the original proposal was just about adding a new\n> > wire protocol message type, which then could be used for emitting\n> > custom messages by middleware support extension - likely loaded as a\n> > preloaded shared library - and consumed by some middleware, which\n> > could either be some proxy or connection pooler or something compiled\n> > as part of the libpq, JDBC or other client driver. So it was just\n> > about providing extensibility to the protocol (the same way almost\n> > everything else in PostgreSQL is extensible).\n> >\n>\n> Yeah, but it is a change to the protocol which means that the client\n> drivers and middleware ecosystem needs to be updated to support that\n> message.\n\nNo, because FE messages don't need to be handled by the client, they\njust send them. It is the server that needs to be updated to\nunderstand that these messages might be received and to ignore them,\nwhich is simple enough.\n\nIf a client doesn't know about a message it COULD send, but doesn't,\nthen there is no update required.\n\n> So, if the message was added to the protocol we could add another\n> message with the response to the request and make the protocol stricter, say\n>\n> FE/M\n> Int32 - Length\n> Int16 - Request type (0 == Query capability, 1 == Execute capability)\n> Int32 - Capability type (0 == Failover, 1 == ..., ...)\n\nThis much detail is optional. It is up to the middleware to define if\nit supports capability requests, or how it handles requests that it\ncannot satisfy.\n\nI'm trying to come up with something generic that people can use for\ndecades to come, not restrict their choices to a very small subset\nbased upon our current vision.\n\n> BE/?\n> Int32 - Length\n> Int32 - Capability type\n> Byte - Support (0 == No, 1 == Yes)\n> Byten - Additional information\n\nIf we add a new message from BE, then yes, we need to modify all\ndrivers, which would be an immediate fail for this proposal.\n\nThe message replies you foresee are optional; they are not required by\nall middleware.\n\nI've already suggested you use NoticeResponse, which is already\ndefined to ignore unknown field types, so is suitable and extensible.\nWe could add a new field type of 'm' to represent a message sent from\nmiddleware to the client.\n\n-- \nSimon Riggs http://www.EnterpriseDB.com/\n\n\n", "msg_date": "Fri, 20 Aug 2021 15:39:23 +0100", "msg_from": "Simon Riggs <simon.riggs@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Middleware Messages for FE/BE" }, { "msg_contents": "Hi Simon,\n\nOn 8/20/21 10:39 AM, Simon Riggs wrote:\n>> Yeah, but it is a change to the protocol which means that the client\n>> drivers and middleware ecosystem needs to be updated to support that\n>> message.\n> \n> No, because FE messages don't need to be handled by the client, they\n> just send them.\n\nYes, but the middleware need to parse them in order to send a response.\n\n> It is the server that needs to be updated to\n> understand that these messages might be received and to ignore them,\n> which is simple enough.\n> \n> If a client doesn't know about a message it COULD send, but doesn't,\n> then there is no update required.\n> \n\nAgreed.\n\n>> So, if the message was added to the protocol we could add another\n>> message with the response to the request and make the protocol stricter, say\n>>\n>> FE/M\n>> Int32 - Length\n>> Int16 - Request type (0 == Query capability, 1 == Execute capability)\n>> Int32 - Capability type (0 == Failover, 1 == ..., ...)\n> \n> This much detail is optional. It is up to the middleware to define if\n> it supports capability requests, or how it handles requests that it\n> cannot satisfy.\n> \n> I'm trying to come up with something generic that people can use for\n> decades to come, not restrict their choices to a very small subset\n> based upon our current vision.\n> \n>> BE/?\n>> Int32 - Length\n>> Int32 - Capability type\n>> Byte - Support (0 == No, 1 == Yes)\n>> Byten - Additional information\n> \n> If we add a new message from BE, then yes, we need to modify all\n> drivers, which would be an immediate fail for this proposal.\n> \n> The message replies you foresee are optional; they are not required by\n> all middleware.\n> \n> I've already suggested you use NoticeResponse, which is already\n> defined to ignore unknown field types, so is suitable and extensible.\n> We could add a new field type of 'm' to represent a message sent from\n> middleware to the client.\n> \n\nWhen doing the PoC just keep in mind that middleware acting on a 'M' \nmessage on a user authenticated connection could lead to a DoS attack.\n\nBest regards,\n Jesper\n\n\n\n", "msg_date": "Fri, 20 Aug 2021 12:13:16 -0400", "msg_from": "Jesper Pedersen <jesper.pedersen@redhat.com>", "msg_from_op": false, "msg_subject": "Re: Middleware Messages for FE/BE" } ]
[ { "msg_contents": "Hi.\n\nThe attached patches allow pushing down \ncurrent_timestamp/localtimestamp/current_time/localtime and now() to \nremote PostgreSQL server as locally computed parameters.\nThe idea is based on oracle_fdw behavior.\n\nExamples.\n\n\\d test\n Foreign table \"public.test\"\n Column | Type | Collation | Nullable | Default | \nFDW options\n--------+--------------------------+-----------+----------+---------+-------------------\n i | integer | | | | \n(column_name 'i')\n t | timestamp with time zone | | | | \n(column_name 't')\nServer: loopback\nFDW options: (schema_name 'data', table_name 'test')\n\nPrior the patch:\n\nexplain verbose select * from test where t=current_timestamp;\n QUERY PLAN\n---------------------------------------------------------------------\n Foreign Scan on public.test (cost=100.00..188.12 rows=11 width=12)\n Output: i, t\n Filter: (test.t = CURRENT_TIMESTAMP)\n Remote SQL: SELECT i, t FROM data.test\n\nexplain verbose update test set t=current_timestamp where t<now();\n QUERY PLAN\n----------------------------------------------------------------------------\n Update on public.test (cost=100.00..154.47 rows=0 width=0)\n Remote SQL: UPDATE data.test SET t = $2 WHERE ctid = $1\n -> Foreign Scan on public.test (cost=100.00..154.47 rows=414 \nwidth=50)\n Output: CURRENT_TIMESTAMP, ctid, test.*\n Filter: (test.t < now())\n Remote SQL: SELECT i, t, ctid FROM data.test FOR UPDATE\n\n\nAfter patch:\nexplain verbose select * from test where t=current_timestamp;\n QUERY PLAN\n-------------------------------------------------------------------------------------\n Foreign Scan on public.test (cost=100.00..144.35 rows=11 width=12)\n Output: i, t\n Remote SQL: SELECT i, t FROM data.test WHERE ((t = $1::timestamp with \ntime zone))\n\nexplain verbose update test set t=current_timestamp where t<now();\n QUERY PLAN\n----------------------------------------------------------------------------------------------------------------------\n Update on public.test (cost=100.00..137.93 rows=0 width=0)\n -> Foreign Update on public.test (cost=100.00..137.93 rows=414 \nwidth=50)\n Remote SQL: UPDATE data.test SET t = $1::timestamp with time \nzone WHERE ((t < $1::timestamp with time zone))\n\n-- \nBest regards,\nAlexander Pyhalov,\nPostgres Professional", "msg_date": "Thu, 19 Aug 2021 12:51:55 +0300", "msg_from": "Alexander Pyhalov <a.pyhalov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "On Thu, Aug 19, 2021 at 2:52 AM Alexander Pyhalov <a.pyhalov@postgrespro.ru>\nwrote:\n\n> Hi.\n>\n> The attached patches allow pushing down\n> current_timestamp/localtimestamp/current_time/localtime and now() to\n> remote PostgreSQL server as locally computed parameters.\n> The idea is based on oracle_fdw behavior.\n>\n> Examples.\n>\n> \\d test\n> Foreign table \"public.test\"\n> Column | Type | Collation | Nullable | Default |\n> FDW options\n>\n> --------+--------------------------+-----------+----------+---------+-------------------\n> i | integer | | | |\n> (column_name 'i')\n> t | timestamp with time zone | | | |\n> (column_name 't')\n> Server: loopback\n> FDW options: (schema_name 'data', table_name 'test')\n>\n> Prior the patch:\n>\n> explain verbose select * from test where t=current_timestamp;\n> QUERY PLAN\n> ---------------------------------------------------------------------\n> Foreign Scan on public.test (cost=100.00..188.12 rows=11 width=12)\n> Output: i, t\n> Filter: (test.t = CURRENT_TIMESTAMP)\n> Remote SQL: SELECT i, t FROM data.test\n>\n> explain verbose update test set t=current_timestamp where t<now();\n> QUERY PLAN\n>\n> ----------------------------------------------------------------------------\n> Update on public.test (cost=100.00..154.47 rows=0 width=0)\n> Remote SQL: UPDATE data.test SET t = $2 WHERE ctid = $1\n> -> Foreign Scan on public.test (cost=100.00..154.47 rows=414\n> width=50)\n> Output: CURRENT_TIMESTAMP, ctid, test.*\n> Filter: (test.t < now())\n> Remote SQL: SELECT i, t, ctid FROM data.test FOR UPDATE\n>\n>\n> After patch:\n> explain verbose select * from test where t=current_timestamp;\n> QUERY PLAN\n>\n> -------------------------------------------------------------------------------------\n> Foreign Scan on public.test (cost=100.00..144.35 rows=11 width=12)\n> Output: i, t\n> Remote SQL: SELECT i, t FROM data.test WHERE ((t = $1::timestamp with\n> time zone))\n>\n> explain verbose update test set t=current_timestamp where t<now();\n> QUERY PLAN\n>\n> ----------------------------------------------------------------------------------------------------------------------\n> Update on public.test (cost=100.00..137.93 rows=0 width=0)\n> -> Foreign Update on public.test (cost=100.00..137.93 rows=414\n> width=50)\n> Remote SQL: UPDATE data.test SET t = $1::timestamp with time\n> zone WHERE ((t < $1::timestamp with time zone))\n>\n> --\n> Best regards,\n> Alexander Pyhalov,\n> Postgres Professional\n\nHi,\nFor 0002 patch:\n\n+ /* now() is stable, but we can ship it as it's replaced by parameter */\n+ return !(func_volatile(func_id) == PROVOLATILE_IMMUTABLE || func_id ==\nF_NOW);\n\nDid you mean to say 'now() is unstable' ?\n\nOn Thu, Aug 19, 2021 at 2:52 AM Alexander Pyhalov <a.pyhalov@postgrespro.ru> wrote:Hi.\n\nThe attached patches allow pushing down \ncurrent_timestamp/localtimestamp/current_time/localtime and now() to \nremote PostgreSQL server as locally computed parameters.\nThe idea is based on oracle_fdw behavior.\n\nExamples.\n\n\\d test\n                               Foreign table \"public.test\"\n  Column |           Type           | Collation | Nullable | Default |    \nFDW options\n--------+--------------------------+-----------+----------+---------+-------------------\n  i      | integer                  |           |          |         | \n(column_name 'i')\n  t      | timestamp with time zone |           |          |         | \n(column_name 't')\nServer: loopback\nFDW options: (schema_name 'data', table_name 'test')\n\nPrior the patch:\n\nexplain verbose select * from test where t=current_timestamp;\n                              QUERY PLAN\n---------------------------------------------------------------------\n  Foreign Scan on public.test  (cost=100.00..188.12 rows=11 width=12)\n    Output: i, t\n    Filter: (test.t = CURRENT_TIMESTAMP)\n    Remote SQL: SELECT i, t FROM data.test\n\nexplain verbose update test set t=current_timestamp where t<now();\n                                  QUERY PLAN\n----------------------------------------------------------------------------\n  Update on public.test  (cost=100.00..154.47 rows=0 width=0)\n    Remote SQL: UPDATE data.test SET t = $2 WHERE ctid = $1\n    ->  Foreign Scan on public.test  (cost=100.00..154.47 rows=414 \nwidth=50)\n          Output: CURRENT_TIMESTAMP, ctid, test.*\n          Filter: (test.t < now())\n          Remote SQL: SELECT i, t, ctid FROM data.test FOR UPDATE\n\n\nAfter patch:\nexplain verbose select * from test where t=current_timestamp;\n                                      QUERY PLAN\n-------------------------------------------------------------------------------------\n  Foreign Scan on public.test  (cost=100.00..144.35 rows=11 width=12)\n    Output: i, t\n    Remote SQL: SELECT i, t FROM data.test WHERE ((t = $1::timestamp with \ntime zone))\n\nexplain verbose update test set t=current_timestamp where t<now();\n                                                       QUERY PLAN\n----------------------------------------------------------------------------------------------------------------------\n  Update on public.test  (cost=100.00..137.93 rows=0 width=0)\n    ->  Foreign Update on public.test  (cost=100.00..137.93 rows=414 \nwidth=50)\n          Remote SQL: UPDATE data.test SET t = $1::timestamp with time \nzone WHERE ((t < $1::timestamp with time zone))\n\n-- \nBest regards,\nAlexander Pyhalov,\nPostgres ProfessionalHi,For 0002 patch:+   /* now() is stable, but we can ship it as it's replaced by parameter */+   return !(func_volatile(func_id) == PROVOLATILE_IMMUTABLE || func_id == F_NOW);Did you mean to say 'now() is unstable' ?", "msg_date": "Thu, 19 Aug 2021 03:22:39 -0700", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "Zhihong Yu писал 2021-08-19 13:22:\n\n> Hi,\n> For 0002 patch:\n> \n> + /* now() is stable, but we can ship it as it's replaced by\n> parameter */\n> + return !(func_volatile(func_id) == PROVOLATILE_IMMUTABLE ||\n> func_id == F_NOW);\n> \n> Did you mean to say 'now() is unstable' ?\n\nNo, it's stable, not immutable, so we need additional check.\n-- \nBest regards,\nAlexander Pyhalov,\nPostgres Professional\n\n\n", "msg_date": "Thu, 19 Aug 2021 13:24:13 +0300", "msg_from": "Alexander Pyhalov <a.pyhalov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "On Thu, Aug 19, 2021 at 2:52 AM Alexander Pyhalov <a.pyhalov@postgrespro.ru>\nwrote:\n\n> Hi.\n>\n> The attached patches allow pushing down\n> current_timestamp/localtimestamp/current_time/localtime and now() to\n> remote PostgreSQL server as locally computed parameters.\n> The idea is based on oracle_fdw behavior.\n>\n> Examples.\n>\n> \\d test\n> Foreign table \"public.test\"\n> Column | Type | Collation | Nullable | Default |\n> FDW options\n>\n> --------+--------------------------+-----------+----------+---------+-------------------\n> i | integer | | | |\n> (column_name 'i')\n> t | timestamp with time zone | | | |\n> (column_name 't')\n> Server: loopback\n> FDW options: (schema_name 'data', table_name 'test')\n>\n> Prior the patch:\n>\n> explain verbose select * from test where t=current_timestamp;\n> QUERY PLAN\n> ---------------------------------------------------------------------\n> Foreign Scan on public.test (cost=100.00..188.12 rows=11 width=12)\n> Output: i, t\n> Filter: (test.t = CURRENT_TIMESTAMP)\n> Remote SQL: SELECT i, t FROM data.test\n>\n> explain verbose update test set t=current_timestamp where t<now();\n> QUERY PLAN\n>\n> ----------------------------------------------------------------------------\n> Update on public.test (cost=100.00..154.47 rows=0 width=0)\n> Remote SQL: UPDATE data.test SET t = $2 WHERE ctid = $1\n> -> Foreign Scan on public.test (cost=100.00..154.47 rows=414\n> width=50)\n> Output: CURRENT_TIMESTAMP, ctid, test.*\n> Filter: (test.t < now())\n> Remote SQL: SELECT i, t, ctid FROM data.test FOR UPDATE\n>\n>\n> After patch:\n> explain verbose select * from test where t=current_timestamp;\n> QUERY PLAN\n>\n> -------------------------------------------------------------------------------------\n> Foreign Scan on public.test (cost=100.00..144.35 rows=11 width=12)\n> Output: i, t\n> Remote SQL: SELECT i, t FROM data.test WHERE ((t = $1::timestamp with\n> time zone))\n>\n> explain verbose update test set t=current_timestamp where t<now();\n> QUERY PLAN\n>\n> ----------------------------------------------------------------------------------------------------------------------\n> Update on public.test (cost=100.00..137.93 rows=0 width=0)\n> -> Foreign Update on public.test (cost=100.00..137.93 rows=414\n> width=50)\n> Remote SQL: UPDATE data.test SET t = $1::timestamp with time\n> zone WHERE ((t < $1::timestamp with time zone))\n>\n> --\n> Best regards,\n> Alexander Pyhalov,\n> Postgres Professional\n\nHi,\nFor 0001 patch:\n\n+ if ((s->op != SVFOP_CURRENT_TIMESTAMP) &&\n+ (s->op != SVFOP_CURRENT_TIMESTAMP_N) &&\n+ (s->op != SVFOP_CURRENT_TIME) &&\n...\n\nThe above check appears more than once. If extracted into a helper method,\nit would help reduce duplicate and make the code more readable.\n\nCheers\n\nOn Thu, Aug 19, 2021 at 2:52 AM Alexander Pyhalov <a.pyhalov@postgrespro.ru> wrote:Hi.\n\nThe attached patches allow pushing down \ncurrent_timestamp/localtimestamp/current_time/localtime and now() to \nremote PostgreSQL server as locally computed parameters.\nThe idea is based on oracle_fdw behavior.\n\nExamples.\n\n\\d test\n                               Foreign table \"public.test\"\n  Column |           Type           | Collation | Nullable | Default |    \nFDW options\n--------+--------------------------+-----------+----------+---------+-------------------\n  i      | integer                  |           |          |         | \n(column_name 'i')\n  t      | timestamp with time zone |           |          |         | \n(column_name 't')\nServer: loopback\nFDW options: (schema_name 'data', table_name 'test')\n\nPrior the patch:\n\nexplain verbose select * from test where t=current_timestamp;\n                              QUERY PLAN\n---------------------------------------------------------------------\n  Foreign Scan on public.test  (cost=100.00..188.12 rows=11 width=12)\n    Output: i, t\n    Filter: (test.t = CURRENT_TIMESTAMP)\n    Remote SQL: SELECT i, t FROM data.test\n\nexplain verbose update test set t=current_timestamp where t<now();\n                                  QUERY PLAN\n----------------------------------------------------------------------------\n  Update on public.test  (cost=100.00..154.47 rows=0 width=0)\n    Remote SQL: UPDATE data.test SET t = $2 WHERE ctid = $1\n    ->  Foreign Scan on public.test  (cost=100.00..154.47 rows=414 \nwidth=50)\n          Output: CURRENT_TIMESTAMP, ctid, test.*\n          Filter: (test.t < now())\n          Remote SQL: SELECT i, t, ctid FROM data.test FOR UPDATE\n\n\nAfter patch:\nexplain verbose select * from test where t=current_timestamp;\n                                      QUERY PLAN\n-------------------------------------------------------------------------------------\n  Foreign Scan on public.test  (cost=100.00..144.35 rows=11 width=12)\n    Output: i, t\n    Remote SQL: SELECT i, t FROM data.test WHERE ((t = $1::timestamp with \ntime zone))\n\nexplain verbose update test set t=current_timestamp where t<now();\n                                                       QUERY PLAN\n----------------------------------------------------------------------------------------------------------------------\n  Update on public.test  (cost=100.00..137.93 rows=0 width=0)\n    ->  Foreign Update on public.test  (cost=100.00..137.93 rows=414 \nwidth=50)\n          Remote SQL: UPDATE data.test SET t = $1::timestamp with time \nzone WHERE ((t < $1::timestamp with time zone))\n\n-- \nBest regards,\nAlexander Pyhalov,\nPostgres ProfessionalHi,For 0001 patch:+               if ((s->op != SVFOP_CURRENT_TIMESTAMP) &&+                   (s->op != SVFOP_CURRENT_TIMESTAMP_N) &&+                   (s->op != SVFOP_CURRENT_TIME) &&...The above check appears more than once. If extracted into a helper method, it would help reduce duplicate and make the code more readable.Cheers", "msg_date": "Thu, 19 Aug 2021 03:55:46 -0700", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "Em qui., 19 de ago. de 2021 às 07:50, Zhihong Yu <zyu@yugabyte.com>\nescreveu:\n\n>\n>\n> On Thu, Aug 19, 2021 at 2:52 AM Alexander Pyhalov <\n> a.pyhalov@postgrespro.ru> wrote:\n>\n>> Hi.\n>>\n>> The attached patches allow pushing down\n>> current_timestamp/localtimestamp/current_time/localtime and now() to\n>> remote PostgreSQL server as locally computed parameters.\n>> The idea is based on oracle_fdw behavior.\n>>\n>> Examples.\n>>\n>> \\d test\n>> Foreign table \"public.test\"\n>> Column | Type | Collation | Nullable | Default |\n>> FDW options\n>>\n>> --------+--------------------------+-----------+----------+---------+-------------------\n>> i | integer | | | |\n>> (column_name 'i')\n>> t | timestamp with time zone | | | |\n>> (column_name 't')\n>> Server: loopback\n>> FDW options: (schema_name 'data', table_name 'test')\n>>\n>> Prior the patch:\n>>\n>> explain verbose select * from test where t=current_timestamp;\n>> QUERY PLAN\n>> ---------------------------------------------------------------------\n>> Foreign Scan on public.test (cost=100.00..188.12 rows=11 width=12)\n>> Output: i, t\n>> Filter: (test.t = CURRENT_TIMESTAMP)\n>> Remote SQL: SELECT i, t FROM data.test\n>>\n>> explain verbose update test set t=current_timestamp where t<now();\n>> QUERY PLAN\n>>\n>> ----------------------------------------------------------------------------\n>> Update on public.test (cost=100.00..154.47 rows=0 width=0)\n>> Remote SQL: UPDATE data.test SET t = $2 WHERE ctid = $1\n>> -> Foreign Scan on public.test (cost=100.00..154.47 rows=414\n>> width=50)\n>> Output: CURRENT_TIMESTAMP, ctid, test.*\n>> Filter: (test.t < now())\n>> Remote SQL: SELECT i, t, ctid FROM data.test FOR UPDATE\n>>\n>>\n>> After patch:\n>> explain verbose select * from test where t=current_timestamp;\n>> QUERY PLAN\n>>\n>> -------------------------------------------------------------------------------------\n>> Foreign Scan on public.test (cost=100.00..144.35 rows=11 width=12)\n>> Output: i, t\n>> Remote SQL: SELECT i, t FROM data.test WHERE ((t = $1::timestamp with\n>> time zone))\n>>\n>> explain verbose update test set t=current_timestamp where t<now();\n>> QUERY PLAN\n>>\n>> ----------------------------------------------------------------------------------------------------------------------\n>> Update on public.test (cost=100.00..137.93 rows=0 width=0)\n>> -> Foreign Update on public.test (cost=100.00..137.93 rows=414\n>> width=50)\n>> Remote SQL: UPDATE data.test SET t = $1::timestamp with time\n>> zone WHERE ((t < $1::timestamp with time zone))\n>>\n>> --\n>> Best regards,\n>> Alexander Pyhalov,\n>> Postgres Professional\n>\n> Hi,\n> For 0001 patch:\n>\n> + if ((s->op != SVFOP_CURRENT_TIMESTAMP) &&\n> + (s->op != SVFOP_CURRENT_TIMESTAMP_N) &&\n> + (s->op != SVFOP_CURRENT_TIME) &&\n> ...\n>\n> The above check appears more than once. If extracted into a helper method,\n> it would help reduce duplicate and make the code more readable.\n>\nPerhaps in a MACRO?\n\nregards,\nRanier Vilela\n\nEm qui., 19 de ago. de 2021 às 07:50, Zhihong Yu <zyu@yugabyte.com> escreveu:On Thu, Aug 19, 2021 at 2:52 AM Alexander Pyhalov <a.pyhalov@postgrespro.ru> wrote:Hi.\n\nThe attached patches allow pushing down \ncurrent_timestamp/localtimestamp/current_time/localtime and now() to \nremote PostgreSQL server as locally computed parameters.\nThe idea is based on oracle_fdw behavior.\n\nExamples.\n\n\\d test\n                               Foreign table \"public.test\"\n  Column |           Type           | Collation | Nullable | Default |    \nFDW options\n--------+--------------------------+-----------+----------+---------+-------------------\n  i      | integer                  |           |          |         | \n(column_name 'i')\n  t      | timestamp with time zone |           |          |         | \n(column_name 't')\nServer: loopback\nFDW options: (schema_name 'data', table_name 'test')\n\nPrior the patch:\n\nexplain verbose select * from test where t=current_timestamp;\n                              QUERY PLAN\n---------------------------------------------------------------------\n  Foreign Scan on public.test  (cost=100.00..188.12 rows=11 width=12)\n    Output: i, t\n    Filter: (test.t = CURRENT_TIMESTAMP)\n    Remote SQL: SELECT i, t FROM data.test\n\nexplain verbose update test set t=current_timestamp where t<now();\n                                  QUERY PLAN\n----------------------------------------------------------------------------\n  Update on public.test  (cost=100.00..154.47 rows=0 width=0)\n    Remote SQL: UPDATE data.test SET t = $2 WHERE ctid = $1\n    ->  Foreign Scan on public.test  (cost=100.00..154.47 rows=414 \nwidth=50)\n          Output: CURRENT_TIMESTAMP, ctid, test.*\n          Filter: (test.t < now())\n          Remote SQL: SELECT i, t, ctid FROM data.test FOR UPDATE\n\n\nAfter patch:\nexplain verbose select * from test where t=current_timestamp;\n                                      QUERY PLAN\n-------------------------------------------------------------------------------------\n  Foreign Scan on public.test  (cost=100.00..144.35 rows=11 width=12)\n    Output: i, t\n    Remote SQL: SELECT i, t FROM data.test WHERE ((t = $1::timestamp with \ntime zone))\n\nexplain verbose update test set t=current_timestamp where t<now();\n                                                       QUERY PLAN\n----------------------------------------------------------------------------------------------------------------------\n  Update on public.test  (cost=100.00..137.93 rows=0 width=0)\n    ->  Foreign Update on public.test  (cost=100.00..137.93 rows=414 \nwidth=50)\n          Remote SQL: UPDATE data.test SET t = $1::timestamp with time \nzone WHERE ((t < $1::timestamp with time zone))\n\n-- \nBest regards,\nAlexander Pyhalov,\nPostgres ProfessionalHi,For 0001 patch:+               if ((s->op != SVFOP_CURRENT_TIMESTAMP) &&+                   (s->op != SVFOP_CURRENT_TIMESTAMP_N) &&+                   (s->op != SVFOP_CURRENT_TIME) &&...The above check appears more than once. If extracted into a helper method, it would help reduce duplicate and make the code more readable.Perhaps in a MACRO?regards,Ranier Vilela", "msg_date": "Thu, 19 Aug 2021 08:01:49 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "I spent some time looking at this patch.\n\nGenerally it looks like a good idea. These stable functions will be\nevaluated at the execution time and replaced with constants. I am not\nsure whether the nodes saved in the param_list may not get the same\ntreatment. Have you verified that?\n\nAlso the new node types being added to the param list is something\nother than Param. So it conflicts with the comment below in\nprepare_query_params()?\n /*\n * Prepare remote-parameter expressions for evaluation. (Note: in\n * practice, we expect that all these expressions will be just Params, so\n * we could possibly do something more efficient than using the full\n * expression-eval machinery for this. But probably there would be little\n * benefit, and it'd require postgres_fdw to know more than is desirable\n * about Param evaluation.)\n */\nIf we are already adding non-params to this list, then the comment is outdated?\n\nOn Thu, Aug 19, 2021 at 3:22 PM Alexander Pyhalov\n<a.pyhalov@postgrespro.ru> wrote:\n>\n> Hi.\n>\n> The attached patches allow pushing down\n> current_timestamp/localtimestamp/current_time/localtime and now() to\n> remote PostgreSQL server as locally computed parameters.\n> The idea is based on oracle_fdw behavior.\n>\n> Examples.\n>\n> \\d test\n> Foreign table \"public.test\"\n> Column | Type | Collation | Nullable | Default |\n> FDW options\n> --------+--------------------------+-----------+----------+---------+-------------------\n> i | integer | | | |\n> (column_name 'i')\n> t | timestamp with time zone | | | |\n> (column_name 't')\n> Server: loopback\n> FDW options: (schema_name 'data', table_name 'test')\n>\n> Prior the patch:\n>\n> explain verbose select * from test where t=current_timestamp;\n> QUERY PLAN\n> ---------------------------------------------------------------------\n> Foreign Scan on public.test (cost=100.00..188.12 rows=11 width=12)\n> Output: i, t\n> Filter: (test.t = CURRENT_TIMESTAMP)\n> Remote SQL: SELECT i, t FROM data.test\n>\n> explain verbose update test set t=current_timestamp where t<now();\n> QUERY PLAN\n> ----------------------------------------------------------------------------\n> Update on public.test (cost=100.00..154.47 rows=0 width=0)\n> Remote SQL: UPDATE data.test SET t = $2 WHERE ctid = $1\n> -> Foreign Scan on public.test (cost=100.00..154.47 rows=414\n> width=50)\n> Output: CURRENT_TIMESTAMP, ctid, test.*\n> Filter: (test.t < now())\n> Remote SQL: SELECT i, t, ctid FROM data.test FOR UPDATE\n>\n>\n> After patch:\n> explain verbose select * from test where t=current_timestamp;\n> QUERY PLAN\n> -------------------------------------------------------------------------------------\n> Foreign Scan on public.test (cost=100.00..144.35 rows=11 width=12)\n> Output: i, t\n> Remote SQL: SELECT i, t FROM data.test WHERE ((t = $1::timestamp with\n> time zone))\n>\n> explain verbose update test set t=current_timestamp where t<now();\n> QUERY PLAN\n> ----------------------------------------------------------------------------------------------------------------------\n> Update on public.test (cost=100.00..137.93 rows=0 width=0)\n> -> Foreign Update on public.test (cost=100.00..137.93 rows=414\n> width=50)\n> Remote SQL: UPDATE data.test SET t = $1::timestamp with time\n> zone WHERE ((t < $1::timestamp with time zone))\n>\n> --\n> Best regards,\n> Alexander Pyhalov,\n> Postgres Professional\n\n\n\n-- \nBest Wishes,\nAshutosh Bapat\n\n\n", "msg_date": "Thu, 19 Aug 2021 19:31:09 +0530", "msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "Hi.\n\nRanier Vilela писал 2021-08-19 14:01:\n> Em qui., 19 de ago. de 2021 às 07:50, Zhihong Yu <zyu@yugabyte.com>\n>> Hi,\n>> For 0001 patch:\n>> \n>> + if ((s->op != SVFOP_CURRENT_TIMESTAMP) &&\n>> + (s->op != SVFOP_CURRENT_TIMESTAMP_N) &&\n>> + (s->op != SVFOP_CURRENT_TIME) &&\n>> ...\n>> \n>> The above check appears more than once. If extracted into a helper\n>> method, it would help reduce duplicate and make the code more\n>> readable.\n> \n> Perhaps in a MACRO?\n\nChanged this check to a macro, also fixed condition in \nis_foreign_param() and added test for it.\nAlso fixed comment in prepare_query_params().\n\n\n-- \nBest regards,\nAlexander Pyhalov,\nPostgres Professional", "msg_date": "Fri, 20 Aug 2021 10:13:30 +0300", "msg_from": "Alexander Pyhalov <a.pyhalov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "Hi.\n\nAshutosh Bapat писал 2021-08-19 17:01:\n> I spent some time looking at this patch.\n> \n> Generally it looks like a good idea. These stable functions will be\n> evaluated at the execution time and replaced with constants. I am not\n> sure whether the nodes saved in the param_list may not get the same\n> treatment. Have you verified that?\n\nI'm not sure I understand you. All parameters are treated in the same \nway.\nThey are evaluated in process_query_params(), real params and \nparameters, corresponding to our SQLValue functions.\nIf we look at execution of something like\n\n explain verbose select * from test1 t1 where i in (select i from test1 \nt2 where t2.t< now() and t1.i=t2.i) ;\n QUERY PLAN\n-------------------------------------------------------------------------------------------------------------------\n Foreign Scan on public.test1 t1 (cost=100.00..243310.11 rows=930 \nwidth=20)\n Output: t1.i, t1.t, t1.l\n Filter: (SubPlan 1)\n Remote SQL: SELECT i, t, l FROM data.test1\n SubPlan 1\n -> Foreign Scan on public.test1 t2 (cost=100.00..161.29 rows=5 \nwidth=4)\n Output: t2.i\n Remote SQL: SELECT i FROM data.test1 WHERE (($1::integer = \ni)) AND ((t < $2::timestamp with time zone)\n\nwe can see two parameters evaluated in process_query_params(), one - of \nT_Param type (with value of current t1.i) and one of T_SQLValueFunction \ntype (with value of current_timestamp).\n\n> \n> Also the new node types being added to the param list is something\n> other than Param. So it conflicts with the comment below in\n> prepare_query_params()?\n> /*\n> * Prepare remote-parameter expressions for evaluation. (Note: in\n> * practice, we expect that all these expressions will be just \n> Params, so\n> * we could possibly do something more efficient than using the \n> full\n> * expression-eval machinery for this. But probably there would be \n> little\n> * benefit, and it'd require postgres_fdw to know more than is \n> desirable\n> * about Param evaluation.)\n> */\n> If we are already adding non-params to this list, then the comment is \n> outdated?\n\nFixed comment in the new version of the patches.\n\n-- \nBest regards,\nAlexander Pyhalov,\nPostgres Professional\n\n\n", "msg_date": "Fri, 20 Aug 2021 10:36:08 +0300", "msg_from": "Alexander Pyhalov <a.pyhalov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "Em sex., 20 de ago. de 2021 às 04:13, Alexander Pyhalov <\na.pyhalov@postgrespro.ru> escreveu:\n\n> Hi.\n>\n> Ranier Vilela писал 2021-08-19 14:01:\n> > Em qui., 19 de ago. de 2021 às 07:50, Zhihong Yu <zyu@yugabyte.com>\n> >> Hi,\n> >> For 0001 patch:\n> >>\n> >> + if ((s->op != SVFOP_CURRENT_TIMESTAMP) &&\n> >> + (s->op != SVFOP_CURRENT_TIMESTAMP_N) &&\n> >> + (s->op != SVFOP_CURRENT_TIME) &&\n> >> ...\n> >>\n> >> The above check appears more than once. If extracted into a helper\n> >> method, it would help reduce duplicate and make the code more\n> >> readable.\n> >\n> > Perhaps in a MACRO?\n>\n> Changed this check to a macro, also fixed condition in\n> is_foreign_param() and added test for it.\n> Also fixed comment in prepare_query_params().\n>\nThanks.\n\nAnother question:\nFor 0002 patch:\n\n+ if (node->funcid == F_NOW)\n+ {\n+ SQLValueFunction *svf = makeNode(SQLValueFunction);\n+\n+ svf->op = SVFOP_CURRENT_TIMESTAMP;\n+ svf->type = TIMESTAMPTZOID;\n+ svf->typmod = -1;\n+ svf->location = -1;\n+\n+ deparseSQLValueFunction(svf, context);\n+\n+ return;\n+ }\nIt seems to me that the svf->xpr field ( SQLValueFunction *svf ) is not\ninitialized somewhere even by deparseSQLValueFunction.\nIf it's not really used, it should be initialized to NULL, ok?\n\nregards,\nRanier Vilela\n\nEm sex., 20 de ago. de 2021 às 04:13, Alexander Pyhalov <a.pyhalov@postgrespro.ru> escreveu:Hi.\n\nRanier Vilela писал 2021-08-19 14:01:\n> Em qui., 19 de ago. de 2021 às 07:50, Zhihong Yu <zyu@yugabyte.com>\n>> Hi,\n>> For 0001 patch:\n>> \n>> +               if ((s->op != SVFOP_CURRENT_TIMESTAMP) &&\n>> +                   (s->op != SVFOP_CURRENT_TIMESTAMP_N) &&\n>> +                   (s->op != SVFOP_CURRENT_TIME) &&\n>> ...\n>> \n>> The above check appears more than once. If extracted into a helper\n>> method, it would help reduce duplicate and make the code more\n>> readable.\n> \n> Perhaps in a MACRO?\n\nChanged this check to a macro, also fixed condition in \nis_foreign_param() and added test for it.\nAlso fixed comment in prepare_query_params().Thanks.Another question:For 0002 patch:+\tif (node->funcid == F_NOW)+\t{+\t\tSQLValueFunction *svf = makeNode(SQLValueFunction);++\t\tsvf->op = SVFOP_CURRENT_TIMESTAMP;+\t\tsvf->type = TIMESTAMPTZOID;+\t\tsvf->typmod = -1;+\t\tsvf->location = -1;++\t\tdeparseSQLValueFunction(svf, context);++\t\treturn;+\t}It seems to me that the svf->xpr field (\nSQLValueFunction *svf\n\n) is not initialized somewhere even by deparseSQLValueFunction.If it's not really used, it should be initialized to NULL, ok?regards,Ranier Vilela", "msg_date": "Fri, 20 Aug 2021 08:19:37 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "Ranier Vilela писал 2021-08-20 14:19:\n\n> Another question:\n> For 0002 patch:\n> \n> + if (node->funcid == F_NOW)\n> + {\n> + SQLValueFunction *svf = makeNode(SQLValueFunction);\n> +\n> + svf->op = SVFOP_CURRENT_TIMESTAMP;\n> + svf->type = TIMESTAMPTZOID;\n> + svf->typmod = -1;\n> + svf->location = -1;\n> +\n> + deparseSQLValueFunction(svf, context);\n> +\n> + return;\n> + }\n> It seems to me that the svf->xpr field ( SQLValueFunction *svf ) is\n> not initialized somewhere even by deparseSQLValueFunction.\n> If it's not really used, it should be initialized to NULL, ok?\n> \n\nxpr field just carries node type, which will be initialized by \nmakeNode().\n\n-- \nBest regards,\nAlexander Pyhalov,\nPostgres Professional\n\n\n", "msg_date": "Fri, 20 Aug 2021 15:18:09 +0300", "msg_from": "Alexander Pyhalov <a.pyhalov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "On Fri, Aug 20, 2021 at 12:13 AM Alexander Pyhalov <a.pyhalov@postgrespro.ru>\nwrote:\n\n> Hi.\n>\n> Ranier Vilela писал 2021-08-19 14:01:\n> > Em qui., 19 de ago. de 2021 às 07:50, Zhihong Yu <zyu@yugabyte.com>\n> >> Hi,\n> >> For 0001 patch:\n> >>\n> >> + if ((s->op != SVFOP_CURRENT_TIMESTAMP) &&\n> >> + (s->op != SVFOP_CURRENT_TIMESTAMP_N) &&\n> >> + (s->op != SVFOP_CURRENT_TIME) &&\n> >> ...\n> >>\n> >> The above check appears more than once. If extracted into a helper\n> >> method, it would help reduce duplicate and make the code more\n> >> readable.\n> >\n> > Perhaps in a MACRO?\n>\n> Changed this check to a macro, also fixed condition in\n> is_foreign_param() and added test for it.\n> Also fixed comment in prepare_query_params().\n>\n>\n> --\n> Best regards,\n> Alexander Pyhalov,\n> Postgres Professional\n\nHi,\nThe patches are good by me.\n\nThanks\n\nOn Fri, Aug 20, 2021 at 12:13 AM Alexander Pyhalov <a.pyhalov@postgrespro.ru> wrote:Hi.\n\nRanier Vilela писал 2021-08-19 14:01:\n> Em qui., 19 de ago. de 2021 às 07:50, Zhihong Yu <zyu@yugabyte.com>\n>> Hi,\n>> For 0001 patch:\n>> \n>> +               if ((s->op != SVFOP_CURRENT_TIMESTAMP) &&\n>> +                   (s->op != SVFOP_CURRENT_TIMESTAMP_N) &&\n>> +                   (s->op != SVFOP_CURRENT_TIME) &&\n>> ...\n>> \n>> The above check appears more than once. If extracted into a helper\n>> method, it would help reduce duplicate and make the code more\n>> readable.\n> \n> Perhaps in a MACRO?\n\nChanged this check to a macro, also fixed condition in \nis_foreign_param() and added test for it.\nAlso fixed comment in prepare_query_params().\n\n\n-- \nBest regards,\nAlexander Pyhalov,\nPostgres ProfessionalHi,The patches are good by me.Thanks", "msg_date": "Fri, 20 Aug 2021 06:28:40 -0700", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "Em sex., 20 de ago. de 2021 às 09:18, Alexander Pyhalov <\na.pyhalov@postgrespro.ru> escreveu:\n\n> Ranier Vilela писал 2021-08-20 14:19:\n>\n> > Another question:\n> > For 0002 patch:\n> >\n> > + if (node->funcid == F_NOW)\n> > + {\n> > + SQLValueFunction *svf = makeNode(SQLValueFunction);\n> > +\n> > + svf->op = SVFOP_CURRENT_TIMESTAMP;\n> > + svf->type = TIMESTAMPTZOID;\n> > + svf->typmod = -1;\n> > + svf->location = -1;\n> > +\n> > + deparseSQLValueFunction(svf, context);\n> > +\n> > + return;\n> > + }\n> > It seems to me that the svf->xpr field ( SQLValueFunction *svf ) is\n> > not initialized somewhere even by deparseSQLValueFunction.\n> > If it's not really used, it should be initialized to NULL, ok?\n> >\n>\n> xpr field just carries node type, which will be initialized by\n> makeNode().\n>\nGreat, I missed it.\n\nregards,\nRanier Vilela\n\nEm sex., 20 de ago. de 2021 às 09:18, Alexander Pyhalov <a.pyhalov@postgrespro.ru> escreveu:Ranier Vilela писал 2021-08-20 14:19:\n\n> Another question:\n> For 0002 patch:\n> \n> + if (node->funcid == F_NOW)\n> + {\n> + SQLValueFunction *svf = makeNode(SQLValueFunction);\n> +\n> + svf->op = SVFOP_CURRENT_TIMESTAMP;\n> + svf->type = TIMESTAMPTZOID;\n> + svf->typmod = -1;\n> + svf->location = -1;\n> +\n> + deparseSQLValueFunction(svf, context);\n> +\n> + return;\n> + }\n> It seems to me that the svf->xpr field ( SQLValueFunction *svf ) is\n> not initialized somewhere even by deparseSQLValueFunction.\n> If it's not really used, it should be initialized to NULL, ok?\n> \n\nxpr field just carries node type, which will be initialized by \nmakeNode().Great, I missed it.regards,Ranier Vilela", "msg_date": "Fri, 20 Aug 2021 10:59:29 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "Alexander Pyhalov <a.pyhalov@postgrespro.ru> writes:\n>> Perhaps in a MACRO?\n\n> Changed this check to a macro, also fixed condition in \n> is_foreign_param() and added test for it.\n> Also fixed comment in prepare_query_params().\n\nI took a quick look at this. I'm unconvinced that you need the\nTIME_RELATED_SQLVALUE_FUNCTION macro, mainly because I think testing\nthat in is_foreign_param() is pointless. The only way we'll be seeing\na SQLValueFunction in is_foreign_param() is if we decided it was\nshippable, so you really don't need two duplicate tests.\n\n(In the same vein, I would not bother with including a switch in\ndeparseSQLValueFunction that knows about these opcodes explicitly.\nJust use the typmod field; exprTypmod() does.)\n\nI also find it pretty bizarre that contain_unsafe_functions\nisn't placed beside its one caller. Maybe that indicates that\nis_foreign_expr is mis-located and should be in shippable.c.\n\nMore generally, it's annoying that you had to copy-and-paste\nall of contain_mutable_functions to make this. That creates\na rather nasty maintenance hazard for future hackers, who will\nneed to keep these widely-separated functions in sync. Not\nsure what to do about that though. Do we want to extend\ncontain_mutable_functions itself to cover this use-case?\n\nThe test cases seem a bit overkill --- what is the point of the\ntwo nigh-identical PREPARE tests, or the GROUP BY test? If\nanything is broken about GROUP BY, surely it's not specific\nto this patch.\n\nI'm not really convinced by the premise of 0002, particularly\nthis bit:\n\n static bool\n-contain_mutable_functions_checker(Oid func_id, void *context)\n+contain_unsafe_functions_checker(Oid func_id, void *context)\n {\n-\treturn (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);\n+\t/* now() is stable, but we can ship it as it's replaced by parameter */\n+\treturn !(func_volatile(func_id) == PROVOLATILE_IMMUTABLE || func_id == F_NOW);\n }\n \nThe point of the check_functions_in_node callback API is to verify\nthe mutability of functions that are embedded in various sorts of\nexpression nodes ... but they might not be in a plain FuncExpr node,\nwhich is the only case you'll deparse correctly. It might be that\nnow() cannot legally appear in any of the other node types that\ncheck_functions_in_node knows about, but I'm not quite convinced\nof that, and even less convinced that that'll stay true as we add\nmore expression node types. Also, if we commit this, for sure\nsome poor soul will try to expand the logic to some other stable\nfunction that *can* appear in those contexts, and that'll be broken.\n\nThe implementation of converting now() to CURRENT_TIMESTAMP\nseems like an underdocumented kluge, too.\n\nOn the whole I'm a bit inclined to drop 0002; I'm not sure it's\nworth the trouble.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 17 Jan 2022 18:08:02 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "> The implementation of converting now() to CURRENT_TIMESTAMP\n> seems like an underdocumented kluge, too.\n>\n\nI'm very late to the party, but it seems to me that this effort is\ndescribing a small subset of what \"routine mapping\" seems to be for:\ndefining function calls that can be pushed down to the foreign server, and\nthe analogous function on the foreign side. We may want to consider\nimplementing just enough of CREATE ROUTINE MAPPING and DROP ROUTINE MAPPING\nto support these specific fixed functions.\n\nThe implementation of converting now() to CURRENT_TIMESTAMP\nseems like an underdocumented kluge, too. I'm very late to the party, but it seems to me that this effort is describing a small subset of what \"routine mapping\" seems to be for: defining function calls that can be pushed down to the foreign server, and the analogous function on the foreign side. We may want to consider implementing just enough of CREATE ROUTINE MAPPING and DROP ROUTINE MAPPING to support these specific fixed functions.", "msg_date": "Tue, 18 Jan 2022 00:08:53 -0500", "msg_from": "Corey Huinker <corey.huinker@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "Corey Huinker <corey.huinker@gmail.com> writes:\n> I'm very late to the party, but it seems to me that this effort is\n> describing a small subset of what \"routine mapping\" seems to be for:\n> defining function calls that can be pushed down to the foreign server, and\n> the analogous function on the foreign side. We may want to consider\n> implementing just enough of CREATE ROUTINE MAPPING and DROP ROUTINE MAPPING\n> to support these specific fixed functions.\n\nHmm ... not really, because for these particular functions, the\npoint is exactly that we *don't* translate them to some function\ncall on the remote end. We evaluate them locally and push the\nresulting constant to the far side, thus avoiding issues like\nclock skew.\n\nHaving said that: why couldn't that implementation sketch be used\nfor ANY stable subexpression? What's special about the datetime\nSQLValueFunctions?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 18 Jan 2022 00:43:58 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": ">\n> Hmm ... not really, because for these particular functions, the\n> point is exactly that we *don't* translate them to some function\n> call on the remote end. We evaluate them locally and push the\n> resulting constant to the far side, thus avoiding issues like\n> clock skew.\n>\n\nAh, my pattern matching brain was so excited to see a use for routine\nmapping that I didn't notice that important detail.\n\nHmm ... not really, because for these particular functions, the\npoint is exactly that we *don't* translate them to some function\ncall on the remote end.  We evaluate them locally and push the\nresulting constant to the far side, thus avoiding issues like\nclock skew.Ah, my pattern matching brain was so excited to see a use for routine mapping that I didn't notice that important detail.", "msg_date": "Tue, 18 Jan 2022 01:02:17 -0500", "msg_from": "Corey Huinker <corey.huinker@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "Hi.\n\nTom Lane писал 2022-01-18 02:08:\n> Alexander Pyhalov <a.pyhalov@postgrespro.ru> writes:\n>>> Perhaps in a MACRO?\n> \n>> Changed this check to a macro, also fixed condition in\n>> is_foreign_param() and added test for it.\n>> Also fixed comment in prepare_query_params().\n> \n> I took a quick look at this. I'm unconvinced that you need the\n> TIME_RELATED_SQLVALUE_FUNCTION macro, mainly because I think testing\n> that in is_foreign_param() is pointless. The only way we'll be seeing\n> a SQLValueFunction in is_foreign_param() is if we decided it was\n> shippable, so you really don't need two duplicate tests.\n> (In the same vein, I would not bother with including a switch in\n> deparseSQLValueFunction that knows about these opcodes explicitly.\n> Just use the typmod field; exprTypmod() does.)\n\nYes, sure, is_foreign_param() is called only when is_foreign_expr() is \ntrue.\nSimplified this part.\n\n> \n> I also find it pretty bizarre that contain_unsafe_functions\n> isn't placed beside its one caller. Maybe that indicates that\n> is_foreign_expr is mis-located and should be in shippable.c.\n> \n> More generally, it's annoying that you had to copy-and-paste\n> all of contain_mutable_functions to make this. That creates\n> a rather nasty maintenance hazard for future hackers, who will\n> need to keep these widely-separated functions in sync. Not\n> sure what to do about that though. Do we want to extend\n> contain_mutable_functions itself to cover this use-case?\n\nI've moved logic to contain_mutable_functions_skip_sqlvalues(), it\nuses the same subroutines as contain_mutable_functions().\nShould we instead just add one more parameter to \ncontain_mutable_functions()?\nI'm not sure that it's a good idea given that \ncontain_mutable_functions() seems to be an\nexternal interface.\n\n> \n> The test cases seem a bit overkill --- what is the point of the\n> two nigh-identical PREPARE tests, or the GROUP BY test? If\n> anything is broken about GROUP BY, surely it's not specific\n> to this patch.\n\nI've removed PREPARE tests, but GROUP BY test checks \nforeign_grouping_ok()/is_foreign_param() path,\nso I think it's useful.\n\n> \n> I'm not really convinced by the premise of 0002, particularly\n> this bit:\n> \n> static bool\n> -contain_mutable_functions_checker(Oid func_id, void *context)\n> +contain_unsafe_functions_checker(Oid func_id, void *context)\n> {\n> -\treturn (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);\n> +\t/* now() is stable, but we can ship it as it's replaced by parameter \n> */\n> +\treturn !(func_volatile(func_id) == PROVOLATILE_IMMUTABLE || func_id \n> == F_NOW);\n> }\n> \n> The point of the check_functions_in_node callback API is to verify\n> the mutability of functions that are embedded in various sorts of\n> expression nodes ... but they might not be in a plain FuncExpr node,\n> which is the only case you'll deparse correctly. It might be that\n> now() cannot legally appear in any of the other node types that\n> check_functions_in_node knows about, but I'm not quite convinced\n> of that, and even less convinced that that'll stay true as we add\n> more expression node types. Also, if we commit this, for sure\n> some poor soul will try to expand the logic to some other stable\n> function that *can* appear in those contexts, and that'll be broken.\n> \n> The implementation of converting now() to CURRENT_TIMESTAMP\n> seems like an underdocumented kluge, too.\n> \n> On the whole I'm a bit inclined to drop 0002; I'm not sure it's\n> worth the trouble.\n> \n\nOK. Let's drop it for now.\n\n-- \nBest regards,\nAlexander Pyhalov,\nPostgres Professional", "msg_date": "Tue, 18 Jan 2022 11:52:25 +0300", "msg_from": "Alexander Pyhalov <a.pyhalov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "Alexander Pyhalov <a.pyhalov@postgrespro.ru> writes:\n> [ updated patch ]\n\nThanks for updating the patch. (BTW, please attach version numbers\nto new patch versions, to avoid confusion.)\n\nHowever, before we proceed any further with this patch, I think we\nreally ought to stop and think about the question I raised last\nnight: why are we building a one-off feature for SQLValueFunction?\nWouldn't the same parameter-substitution mechanism work for *any*\nstable expression that doesn't contain remote Vars? That would\nsubsume the now() case as well as plenty of others.\n\nSo far the only counterexample I've been able to come up with is\nthat shipping values of reg* types might not be too safe, because\nthe remote side might not have the same objects. For example\nconsider these two potential quals:\n\tWHERE remote_oid_column = CURRENT_ROLE::regrole\n\tWHERE remote_text_column = CURRENT_ROLE::text\nSay we're running as user 'joe' and that role doesn't exist on the\nremote server. Then executing the first WHERE locally is fine, but\nshipping it to the remote would cause a failure because the remote's\nregrolein() will fail to convert the parameter value. But the second\ncase is quite non-problematic, because what will be sent over is just\nsome uninterpreted text.\n\nIn point of fact, this hazard doesn't have anything to do with stable\nor not-stable subexpressions --- for example,\n\tWHERE remote_oid_column = 'joe'::regrole\nis just as unsafe, even though the value under consideration is a\n*constant*. Maybe there is something in postgres_fdw that would stop\nit from shipping this qual, but I don't recall seeing it, so I wonder\nif there's a pre-existing bug here.\n\nSo it seems like we need a check to prevent generating remote Params\nthat are of \"unsafe\" types, but this is a type issue not an expression\nissue --- as long as an expression is stable and does not yield an\nunsafe-to-ship data type, why can't we treat it as a Param?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 18 Jan 2022 11:53:00 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "Tom Lane писал 2022-01-18 19:53:\n> Alexander Pyhalov <a.pyhalov@postgrespro.ru> writes:\n>> [ updated patch ]\n> \n> Thanks for updating the patch. (BTW, please attach version numbers\n> to new patch versions, to avoid confusion.)\n> \n> However, before we proceed any further with this patch, I think we\n> really ought to stop and think about the question I raised last\n> night: why are we building a one-off feature for SQLValueFunction?\n> Wouldn't the same parameter-substitution mechanism work for *any*\n> stable expression that doesn't contain remote Vars? That would\n> subsume the now() case as well as plenty of others.\n> \n\nHi.\n\nI think, I can extend it to allow any stable function (not just \nimmutable/sqlvalues) in is_foreign_expr(), but not so sure about \n\"expression\".\n\nPerhaps, at top of deparseExpr() we can check that expression doesn't \ncontain vars, params, but contains stable function, and deparse it as \nparam.\nThis means we'll translate something like\n\nexplain select * from t where d > now() - '1 day'::interval;\n\nto\n\nselect * from t where d > $1;\n\nThe question is how will we reliably determine its typmod (given that I \nread in exprTypmod() comment\n\"returns the type-specific modifier of the expression's result type, if \nit can be determined. In many cases, it can't\".\n\nWhat do we save if we don't ship whole expression as param, but only \nstable functions? Allowing them seems to be more straightforward.\n-- \nBest regards,\nAlexander Pyhalov,\nPostgres Professional\n\n\n", "msg_date": "Tue, 18 Jan 2022 22:02:14 +0300", "msg_from": "Alexander Pyhalov <a.pyhalov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "Alexander Pyhalov <a.pyhalov@postgrespro.ru> writes:\n> Tom Lane писал 2022-01-18 19:53:\n>> However, before we proceed any further with this patch, I think we\n>> really ought to stop and think about the question I raised last\n>> night: why are we building a one-off feature for SQLValueFunction?\n>> Wouldn't the same parameter-substitution mechanism work for *any*\n>> stable expression that doesn't contain remote Vars? That would\n>> subsume the now() case as well as plenty of others.\n\n> This means we'll translate something like\n> explain select * from t where d > now() - '1 day'::interval;\n> to\n> select * from t where d > $1;\n\nRight.\n\n> The question is how will we reliably determine its typmod (given that I \n> read in exprTypmod() comment\n> \"returns the type-specific modifier of the expression's result type, if \n> it can be determined. In many cases, it can't\".\n\nI don't think we need to. If exprTypmod() says the typmod is -1,\nthen that's what it is.\n\n> What do we save if we don't ship whole expression as param, but only \n> stable functions? Allowing them seems to be more straightforward.\n\nHow so? Right off the bat, you get rid of the need for your own\nversion of contain_mutable_function. ISTM this approach can probably\nbe implemented in a patch that's noticeably smaller than what you\nhave now. It'll likely be touching entirely different places in\npostgres_fdw, of course.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 18 Jan 2022 14:11:30 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "I wrote:\n> Alexander Pyhalov <a.pyhalov@postgrespro.ru> writes:\n>> This means we'll translate something like\n>> explain select * from t where d > now() - '1 day'::interval;\n>> to\n>> select * from t where d > $1;\n\n> Right.\n\nAfter thinking about that a bit more, I see that this will result\nin a major redefinition of what is \"shippable\". Right now, we do not\nconsider the above WHERE clause to be shippable, not only because of\nnow() but because the timestamptz-minus-interval operator is dependent\non the timezone setting, which might be different at the remote.\nBut if we evaluate that operator locally and send its result as a\nparameter, the objection vanishes. In fact, I don't think we even\nneed to require the subexpression to contain only built-in functions.\nIts result still has to be of a built-in type, but that's a much\nweaker restriction.\n\nSo this is going to require significant restructuring of both\nis_foreign_expr and deparse.c, which I realize may be more than\nyou bargained for. But if you want to tackle it, I think what\nwe want to do is divide potentially-shippable expressions into\nthree sorts of components:\n\n1. Remote Vars, which obviously ship as-is.\n\n2. Locally-evaluatable subexpressions, which must contain no\nremote Vars, must be stable or immutable, and must have a result\ntype that we consider safe to ship. If such a subexpression\nis just a Const, we ship it as a constant, otherwise we evaluate\nthe value at runtime and ship a parameter.\n\n3. Superstructure, which consists of all expression nodes having\nat least one remote Var below them. These nodes have to be\nshippable according to the existing definition, so that we know\nthat the remote server will evaluate them just as we would.\n\nIf we keep the existing division of labor between is_foreign_expr\nand deparse.c, I fear that there's going to be a lot of duplicated\ncode as well as duplicative planning effort. I wonder if it'd be\nwise to combine those operations into a single expression-scanning\nprocess that determines whether an expression is safe to ship and\nproduces the translated string immediately if it is.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 18 Jan 2022 15:01:05 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "Tom Lane писал 2022-01-18 23:01:\n> I wrote:\n>> Alexander Pyhalov <a.pyhalov@postgrespro.ru> writes:\n>>> This means we'll translate something like\n>>> explain select * from t where d > now() - '1 day'::interval;\n>>> to\n>>> select * from t where d > $1;\n> \n>> Right.\n> \n> After thinking about that a bit more, I see that this will result\n> in a major redefinition of what is \"shippable\". Right now, we do not\n> consider the above WHERE clause to be shippable, not only because of\n> now() but because the timestamptz-minus-interval operator is dependent\n> on the timezone setting, which might be different at the remote.\n> But if we evaluate that operator locally and send its result as a\n> parameter, the objection vanishes. In fact, I don't think we even\n> need to require the subexpression to contain only built-in functions.\n> Its result still has to be of a built-in type, but that's a much\n> weaker restriction.\n> \n\nHi.\nSo far I have the following prototype. It seems to be working, but I \nthink it can be enhanced.\nAt least, some sort of caching seems to be necessary for \nis_stable_expr().\n\n1) Now expression can be either 'stable shippable' or 'shippable \naccording to old rules'. We check if it's 'stable shippable' in \nforeign_expr_walker(),\nis_foreign_param() and deparseExpr(). All such exprs are replaced by \nparams while deparsing.\n2) contain_mutable_functions() now is calculated only for current node, \nif node is not considered 'stable shippable'.\n\nIs it step in the right direction or do I miss something?\n-- \nBest regards,\nAlexander Pyhalov,\nPostgres Professional", "msg_date": "Thu, 20 Jan 2022 16:42:18 +0300", "msg_from": "Alexander Pyhalov <a.pyhalov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "Alexander Pyhalov <a.pyhalov@postgrespro.ru> writes:\n> So far I have the following prototype. It seems to be working, but I \n> think it can be enhanced.\n> At least, some sort of caching seems to be necessary for \n> is_stable_expr().\n\nYeah, from a performance standpoint this seems pretty horrid ---\nit's probably exponential in the size of the expressions considered\nbecause of the repeated recursions.\n\nThe approach I had in mind was to extend the responsibility of\nforeign_expr_walker to make it deduce the classification of\nan expression in a bottom-up fashion. Also, as I noted before,\nwe don't want to re-deduce that in a later deparse pass, so\nmaybe we should just go ahead and deparse during foreign_expr_walker.\nNot sure about that part. It sounds expensive; but recording the\nclassification results in a way we could re-use later doesn't seem\ntoo cheap either.\n\nBTW, the patch is just about unreadable as-is. It would have been\nbetter to not have re-indented the bulk of foreign_expr_walker,\nleaving that for some later pgindent pass. But that may be moot,\nbecause I don't think we can tolerate the double-recursion approach\nyou took here.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 21 Jan 2022 14:57:12 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" }, { "msg_contents": "This entry has been waiting on author input for a while (our current\nthreshold is roughly two weeks), so I've marked it Returned with\nFeedback.\n\nOnce you think the patchset is ready for review again, you (or any\ninterested party) can resurrect the patch entry by visiting\n\n https://commitfest.postgresql.org/38/3289/\n\nand changing the status to \"Needs Review\", and then changing the\nstatus again to \"Move to next CF\". (Don't forget the second step;\nhopefully we will have streamlined this in the near future!)\n\nThanks,\n--Jacob\n\n\n", "msg_date": "Tue, 2 Aug 2022 13:59:45 -0700", "msg_from": "Jacob Champion <jchampion@timescale.com>", "msg_from_op": false, "msg_subject": "Re: Push down time-related SQLValue functions to foreign server" } ]
[ { "msg_contents": "## What is this?\n\nIt's a draft patch that replaces code like this:\n```c\npg_file_unlink(PG_FUNCTION_ARGS)\n{\nchar *filename;\nrequireSuperuser();\nfilename = convert_and_check_filename(PG_GETARG_TEXT_PP(0));\n```\n\nWith this shorter version:\n```c\npg_file_unlink(PG_FUNCTION_ARGS)\n{\nrequireSuperuser();\nchar *filename = convert_and_check_filename(PG_GETARG_TEXT_PP(0));\n```\n\n## Why would we want this?\n1. It removes 23328 lines of code that don't have any impact on how the code behaves [1]. This is roughly 2.7% of all the lines of code in the codebase.\n2. Declarations are closer to the actual usage. This is advised by the \"Code Complete\" book [2] and has the following advantages:\n a. This limits variable scope to what is necessary. Which in turn makes the mental model you have to keep of a function when reading the code simpler.\n b. In most cases it allows you to see the the type of a variable without needing to go to the top of the function.\n3. You can do input checking and assertions at the top of the function, instead of having to put declarations in front of it. This makes it clear which invariants hold for the function. (as seen in the example above and the changes for pg_file_rename[3])\n4. Declaring variables after statements is allowed in C99. Postgres already requires C99, so it might as well use this feature too.\n\n## How was this changeset created?\n\nI created a script that modifies all C files in the following way:\n\n1. Find a non `static` declaration.\n2. If it has an initializer and it is not a single variable/constant, don't consider replacing it. (reason: a function call initializer might have sideffects).\n3. Otherwise (it's a simple initializer or it has no initializer at all), take the type and variable from that declaration.\n4. Find the next use of the variable.\n5. If the next use is not an assignment, don't do anything (the value of the original initialization is used).\n6. If the next use is an assignment:\n 1. Remove the old declaration\n 2. Prefix the found assignment with the type\n 3. Unless the variable is also used in the same line of the new initialization, e.g:\n ```c\n int a = 1;\n a = a + a;\n ```\n\n## How does this script work?\n\nIt uses a Perl regex to search and replace! (obligatory jokes at the bottom of the email) This regex is based on the ones used in this PR to citus[4] and the similar PR to pg_auto_failover[5]. The script is in the 3rd commit of this patchset.\n\nTo visualize the regex in the script in a reasonable way, copy paste the search part of it:\n```\n\\n\\t(?!(return|static)\\b)(?P<type>(\\w+[\\t ])+[\\t *]*)(?>(?P<variable>\\w+)( = [\\w>\\s\\n-]*?)?;\\n(?P<code_between>(?>(?P<comment_or_string_or_not_preprocessor>\\/\\*.*?\\*\\/|\"(?>\\\\\"|.)*?\"|(?!goto)[^#]))*?)(\\t)?(?=\\b(?P=variable)\\b))(?<=\\n\\t)(?<!:\\n\\t)(?P=variable) =(?![^;]*?[^>_]\\b(?P=variable)\\b[^_])\n```\n\nAnd paste that into https://www.debuggex.com/, then select PCRE from the dropdown. (Sharing seems to be down at this point, so this is the only way to do it at the moment) Try it out! The regex is not as crazy as it looks.\n\nThere's two important assumptions this regex makes:\n1. Code is indented using tabs, and the intent level determines the scope. (this is true, because of `pgindent`)\n2. Declared variables are actually used. (this is true, because we would get compiler warnings otherwise)\n\nThere's two cases where this regex has some special behaviour:\n1. Stop searching for the first usage of a variable when either a `goto` or a preprocessor command is found (outside a string or comment). These things affect the control flow in a way that the regex does not understand. (any `#` character is assumed to be a preprocessor commands).\n2. Don't replace if the assignment is right after a `label:`, by checking if there was a `:` as the last character on the previous line. This works around errors like this:\n```\nhashovfl.c:865:3: error: a label can only be part of a statement and a declaration is not a statement\n OffsetNumber maxroffnum = PageGetMaxOffsetNumber(rpage);\n ^~~~~~~~~~~~\n```\nDetecting this case in this way is not perfect, because sometimes there is an extra newline or a comment between the label and the assignment. This is not easily detectable by the regex, because lookbehinds cannot have a variable length in Perl (or most regex engines for that matter). For these few cases (5 in the entire codebase) a manual change was done either before or after the automatic replacement to fix them so the code compiles again. (2nd and 5th commits of this patchset)\n\nAfter all these changes `make -s world` doesn't show any warnings or errors and `make check-world` succeeds. I configured compilation like this:\n```\n./configure --enable-cassert --enable-depend --enable-debug --with-openssl --with-libxml --with-libxslt --with-uuid=e2fs --with-icu\n```\n\n## What I want to achieve with this email\n\n1. For people to look at a small sample of the changes made by this script. I will try to send patches with the actual changes made to the code as attachments in a followup email. However, I don't know if that will succeed since the patch files are very big and it might run into some mailserver limits. So in case that doesn't work, the full changeset is available on Github[6]. This make viewing this enormous diff quite a bit easier IMHO anyaway. If you see something weird that is not covered in the \"Known issues\" section below, please share it. That way it can be discussed and/or fixed.\n2. A discussion on if this type of code change would be a net positive for Postgres codebase. Please explain clearly why or why not.\n3. Some links to resources on what's necessary to get a big refactoring patch like this merged.\n\n## What I don't want to achieve with this email\n\n1. For someone to go over all the changes right now. There's likely to be changes to the script or something else. Doing a full review of the changes would be better saved for later during a final review.\n\n## Known issues with the currently generated code\n\nThere's a few issues with the final generated code that I've already spotted. These should all be relatively easy to fix in an automated way. However, I think doing so is probably better done by `pgindent` or some other auto formatting tool, instead of with the regex. Note that I did run `pgindent`, it just didn't address these things:\n\n1. Whitespace between type and variable is kept the same as it was before moving the declaration. If the original declaration had whitespace added in such a way that all variable names of declarations aligned, then this whitespace is preserved. This looks weird in various cases. See [3] for an example.\n2. `pgindent` adds a newline after each block of declarations, even if they are not at the start of function. If this is desired is debatable, but to me it seems like it adds excessive newlines. See [7] for an example.\n3. If all declarations are moved away from the top of the function, then an empty newline is kept at the top of the function. This seems like an unnecessary newline to me. See [3] for an example.\n\nSources:\n1. `tokei`[8] results of lines of code:\nBefore:\n```\n$ tokei --type C\n===============================================================================\n Language Files Lines Code Comments Blanks\n===============================================================================\n C 1389 1361309 866514 330933 163862\n===============================================================================\n Total 1389 1361309 866514 330933 163862\n===============================================================================\n```\nAfter:\n```\n$ tokei --type C\n===============================================================================\n Language Files Lines Code Comments Blanks\n===============================================================================\n C 1389 1347515 843186 330952 173377\n===============================================================================\n Total 1389 1347515 843186 330952 173377\n===============================================================================\n```\n2. https://github.com/mgp/book-notes/blob/master/code-complete.markdown#103-guidelines-for-initializing-variables\n3.\n```patch\n@@ -401,11 +389,10 @@ pg_file_rename_internal(text *file1, text *file2, text *file3)\n Datum\n pg_file_unlink(PG_FUNCTION_ARGS)\n {\n- char *filename;\n\n requireSuperuser();\n\n- filename = convert_and_check_filename(PG_GETARG_TEXT_PP(0));\n+ char *filename = convert_and_check_filename(PG_GETARG_TEXT_PP(0));\n\n if (access(filename, W_OK) < 0)\n```\n4. https://github.com/citusdata/citus/pull/3181\n5. https://github.com/citusdata/pg_auto_failover/pull/266\n6. https://github.com/JelteF/postgres/pull/2\n7.\n```patch\n@@ -2863,7 +2886,8 @@ palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum)\n * longer than we must.\n */\n Buffer buffer = ReadBufferExtended(state->rel, MAIN_FORKNUM, blocknum, RBM_NORMAL,\n- state->checkstrategy);\n+ state->checkstrategy);\n+\n LockBuffer(buffer, BT_READ);\n\n /*\n```\n8. https://github.com/XAMPPRocky/tokei\n\n\nObligatory jokes:\n1. https://xkcd.com/1171/\n2. https://xkcd.com/208/\n3. https://stackoverflow.com/a/1732454/2570866 (and serious response to it https://neilmadden.blog/2019/02/24/why-you-really-can-parse-html-and-anything-else-with-regular-expressions/)", "msg_date": "Thu, 19 Aug 2021 11:50:09 +0000", "msg_from": "Jelte Fennema <Jelte.Fennema@microsoft.com>", "msg_from_op": true, "msg_subject": "Allow declaration after statement and reformat code to use it" }, { "msg_contents": "Em qui., 19 de ago. de 2021 às 08:50, Jelte Fennema <\nJelte.Fennema@microsoft.com> escreveu:\n\n> ## What is this?\n>\n> It's a draft patch that replaces code like this:\n> ```c\n> pg_file_unlink(PG_FUNCTION_ARGS)\n> {\n> char *filename;\n> requireSuperuser();\n> filename = convert_and_check_filename(PG_GETARG_TEXT_PP(0));\n> ```\n>\n> With this shorter version:\n> ```c\n> pg_file_unlink(PG_FUNCTION_ARGS)\n> {\n> requireSuperuser();\n> char *filename = convert_and_check_filename(PG_GETARG_TEXT_PP(0));\n> ```\n>\n> ## Why would we want this?\n> 1. It removes 23328 lines of code that don't have any impact on how the\n> code behaves [1]. This is roughly 2.7% of all the lines of code in the\n> codebase.\n> 2. Declarations are closer to the actual usage. This is advised by the\n> \"Code Complete\" book [2] and has the following advantages:\n> a. This limits variable scope to what is necessary. Which in turn makes\n> the mental model you have to keep of a function when reading the code\n> simpler.\n> b. In most cases it allows you to see the the type of a variable\n> without needing to go to the top of the function.\n> 3. You can do input checking and assertions at the top of the function,\n> instead of having to put declarations in front of it. This makes it clear\n> which invariants hold for the function. (as seen in the example above and\n> the changes for pg_file_rename[3])\n> 4. Declaring variables after statements is allowed in C99. Postgres\n> already requires C99, so it might as well use this feature too.\n>\n> ## How was this changeset created?\n>\n> I created a script that modifies all C files in the following way:\n>\n> 1. Find a non `static` declaration.\n> 2. If it has an initializer and it is not a single variable/constant,\n> don't consider replacing it. (reason: a function call initializer might\n> have sideffects).\n> 3. Otherwise (it's a simple initializer or it has no initializer at all),\n> take the type and variable from that declaration.\n> 4. Find the next use of the variable.\n> 5. If the next use is not an assignment, don't do anything (the value of\n> the original initialization is used).\n> 6. If the next use is an assignment:\n> 1. Remove the old declaration\n> 2. Prefix the found assignment with the type\n> 3. Unless the variable is also used in the same line of the new\n> initialization, e.g:\n> ```c\n> int a = 1;\n> a = a + a;\n> ```\n>\n> ## How does this script work?\n>\n> It uses a Perl regex to search and replace! (obligatory jokes at the\n> bottom of the email) This regex is based on the ones used in this PR to\n> citus[4] and the similar PR to pg_auto_failover[5]. The script is in the\n> 3rd commit of this patchset.\n>\n> To visualize the regex in the script in a reasonable way, copy paste the\n> search part of it:\n> ```\n> \\n\\t(?!(return|static)\\b)(?P<type>(\\w+[\\t ])+[\\t *]*)(?>(?P<variable>\\w+)(\n> =\n> [\\w>\\s\\n-]*?)?;\\n(?P<code_between>(?>(?P<comment_or_string_or_not_preprocessor>\\/\\*.*?\\*\\/|\"(?>\\\\\"|.)*?\"|(?!goto)[^#]))*?)(\\t)?(?=\\b(?P=variable)\\b))(?<=\\n\\t)(?<!:\\n\\t)(?P=variable)\n> =(?![^;]*?[^>_]\\b(?P=variable)\\b[^_])\n> ```\n>\n> And paste that into https://www.debuggex.com/, then select PCRE from the\n> dropdown. (Sharing seems to be down at this point, so this is the only way\n> to do it at the moment) Try it out! The regex is not as crazy as it looks.\n>\n> There's two important assumptions this regex makes:\n> 1. Code is indented using tabs, and the intent level determines the scope.\n> (this is true, because of `pgindent`)\n> 2. Declared variables are actually used. (this is true, because we would\n> get compiler warnings otherwise)\n>\n> There's two cases where this regex has some special behaviour:\n> 1. Stop searching for the first usage of a variable when either a `goto`\n> or a preprocessor command is found (outside a string or comment). These\n> things affect the control flow in a way that the regex does not understand.\n> (any `#` character is assumed to be a preprocessor commands).\n> 2. Don't replace if the assignment is right after a `label:`, by checking\n> if there was a `:` as the last character on the previous line. This works\n> around errors like this:\n> ```\n> hashovfl.c:865:3: error: a label can only be part of a statement and a\n> declaration is not a statement\n> OffsetNumber maxroffnum = PageGetMaxOffsetNumber(rpage);\n> ^~~~~~~~~~~~\n> ```\n> Detecting this case in this way is not perfect, because sometimes there is\n> an extra newline or a comment between the label and the assignment. This is\n> not easily detectable by the regex, because lookbehinds cannot have a\n> variable length in Perl (or most regex engines for that matter). For these\n> few cases (5 in the entire codebase) a manual change was done either before\n> or after the automatic replacement to fix them so the code compiles again.\n> (2nd and 5th commits of this patchset)\n>\n> After all these changes `make -s world` doesn't show any warnings or\n> errors and `make check-world` succeeds. I configured compilation like this:\n> ```\n> ./configure --enable-cassert --enable-depend --enable-debug --with-openssl\n> --with-libxml --with-libxslt --with-uuid=e2fs --with-icu\n> ```\n>\n> ## What I want to achieve with this email\n>\n> 1. For people to look at a small sample of the changes made by this\n> script. I will try to send patches with the actual changes made to the code\n> as attachments in a followup email. However, I don't know if that will\n> succeed since the patch files are very big and it might run into some\n> mailserver limits. So in case that doesn't work, the full changeset is\n> available on Github[6]. This make viewing this enormous diff quite a bit\n> easier IMHO anyaway. If you see something weird that is not covered in the\n> \"Known issues\" section below, please share it. That way it can be discussed\n> and/or fixed.\n> 2. A discussion on if this type of code change would be a net positive for\n> Postgres codebase. Please explain clearly why or why not.\n> 3. Some links to resources on what's necessary to get a big refactoring\n> patch like this merged.\n>\n> ## What I don't want to achieve with this email\n>\n> 1. For someone to go over all the changes right now. There's likely to be\n> changes to the script or something else. Doing a full review of the changes\n> would be better saved for later during a final review.\n>\n> ## Known issues with the currently generated code\n>\n> There's a few issues with the final generated code that I've already\n> spotted. These should all be relatively easy to fix in an automated way.\n> However, I think doing so is probably better done by `pgindent` or some\n> other auto formatting tool, instead of with the regex. Note that I did run\n> `pgindent`, it just didn't address these things:\n>\n> 1. Whitespace between type and variable is kept the same as it was before\n> moving the declaration. If the original declaration had whitespace added in\n> such a way that all variable names of declarations aligned, then this\n> whitespace is preserved. This looks weird in various cases. See [3] for an\n> example.\n> 2. `pgindent` adds a newline after each block of declarations, even if\n> they are not at the start of function. If this is desired is debatable, but\n> to me it seems like it adds excessive newlines. See [7] for an example.\n> 3. If all declarations are moved away from the top of the function, then\n> an empty newline is kept at the top of the function. This seems like an\n> unnecessary newline to me. See [3] for an example.\n>\n> Sources:\n> 1. `tokei`[8] results of lines of code:\n> Before:\n> ```\n> $ tokei --type C\n>\n> ===============================================================================\n> Language Files Lines Code Comments\n> Blanks\n>\n> ===============================================================================\n> C 1389 1361309 866514 330933\n> 163862\n>\n> ===============================================================================\n> Total 1389 1361309 866514 330933\n> 163862\n>\n> ===============================================================================\n> ```\n> After:\n> ```\n> $ tokei --type C\n>\n> ===============================================================================\n> Language Files Lines Code Comments\n> Blanks\n>\n> ===============================================================================\n> C 1389 1347515 843186 330952\n> 173377\n>\n> ===============================================================================\n> Total 1389 1347515 843186 330952\n> 173377\n>\n> ===============================================================================\n> ```\n> 2.\n> https://github.com/mgp/book-notes/blob/master/code-complete.markdown#103-guidelines-for-initializing-variables\n> 3.\n> ```patch\n> @@ -401,11 +389,10 @@ pg_file_rename_internal(text *file1, text *file2,\n> text *file3)\n> Datum\n> pg_file_unlink(PG_FUNCTION_ARGS)\n> {\n> - char *filename;\n>\n> requireSuperuser();\n>\n> - filename = convert_and_check_filename(PG_GETARG_TEXT_PP(0));\n> + char *filename = convert_and_check_filename(PG_GETARG_TEXT_PP(0));\n>\n> if (access(filename, W_OK) < 0)\n> ```\n> 4. https://github.com/citusdata/citus/pull/3181\n> 5. https://github.com/citusdata/pg_auto_failover/pull/266\n> 6. https://github.com/JelteF/postgres/pull/2\n> 7.\n> ```patch\n> @@ -2863,7 +2886,8 @@ palloc_btree_page(BtreeCheckState *state,\n> BlockNumber blocknum)\n> * longer than we must.\n> */\n> Buffer buffer = ReadBufferExtended(state->rel, MAIN_FORKNUM, blocknum,\n> RBM_NORMAL,\n> - state->checkstrategy);\n> + state->checkstrategy);\n> +\n> LockBuffer(buffer, BT_READ);\n>\n> /*\n> ```\n> 8. https://github.com/XAMPPRocky/tokei\n>\n>\n> Obligatory jokes:\n> 1. https://xkcd.com/1171/\n> 2. https://xkcd.com/208/\n> 3. https://stackoverflow.com/a/1732454/2570866 (and serious response to\n> it\n> https://neilmadden.blog/2019/02/24/why-you-really-can-parse-html-and-anything-else-with-regular-expressions/\n> )\n>\n-1 in short.\n\nC needs readability, not fewer lines.\nAside from horrible code, it doesn't improve 0.1% on anything.\n\nI think it's a bad idea and I'm strongly against it.\n\nregards,\nRanier Vilela\n\nEm qui., 19 de ago. de 2021 às 08:50, Jelte Fennema <Jelte.Fennema@microsoft.com> escreveu:\n\n\n## What is this?\n\n\n\nIt's a draft patch that replaces code like this:\n```c\npg_file_unlink(PG_FUNCTION_ARGS)\n{\nchar   *filename;\nrequireSuperuser();\nfilename = convert_and_check_filename(PG_GETARG_TEXT_PP(0));\n```\n\n\nWith this shorter version:\n```c\npg_file_unlink(PG_FUNCTION_ARGS)\n{\nrequireSuperuser();\nchar      *filename = convert_and_check_filename(PG_GETARG_TEXT_PP(0));\n```\n\n\n## Why would we want this?\n1. It removes 23328 lines of code that don't have any impact on how the code behaves [1]. This is roughly 2.7% of all the lines of code in the codebase.\n2. Declarations are closer to the actual usage. This is advised by the \"Code Complete\" book [2] and has the following advantages:\n   a. This limits variable scope to what is necessary. Which in turn makes the mental model you have to keep of a function when reading the code simpler.\n   b. In most cases it allows you to see the the type of a variable without needing to go to the top of the function.\n3. You can do input checking and assertions at the top of the function, instead of having to put declarations in front of it. This makes it clear which invariants hold for the function.  (as seen in the example above and the changes for pg_file_rename[3])\n4. Declaring variables after statements is allowed in C99. Postgres already requires C99, so it might as well use this feature too.\n\n\n## How was this changeset created?\n\n\nI created a script that modifies all C files in the following way:\n\n\n1. Find a non `static` declaration.\n2. If it has an initializer and it is not a single variable/constant, don't consider replacing it. (reason: a function call initializer might have sideffects).\n3. Otherwise (it's a simple initializer or it has no initializer at all), take the type and variable from that declaration.\n4. Find the next use of the variable.\n5. If the next use is not an assignment, don't do anything (the value of the original initialization is used).\n6. If the next use is an assignment:\n    1. Remove the old declaration\n    2. Prefix the found assignment with the type\n    3. Unless the variable is also used in the same line of the new initialization, e.g:\n      ```c\n      int a = 1;\n      a = a + a;\n      ```\n\n\n## How does this script work?\n\n\nIt uses a Perl regex to search and replace! (obligatory jokes at the bottom of the email) This regex is based on the ones used in this PR to citus[4] and the similar PR to pg_auto_failover[5]. The script is in the 3rd commit of this patchset.\n\n\nTo visualize the regex in the script in a reasonable way, copy paste the search part of it:\n```\n\\n\\t(?!(return|static)\\b)(?P<type>(\\w+[\\t ])+[\\t *]*)(?>(?P<variable>\\w+)( = [\\w>\\s\\n-]*?)?;\\n(?P<code_between>(?>(?P<comment_or_string_or_not_preprocessor>\\/\\*.*?\\*\\/|\"(?>\\\\\"|.)*?\"|(?!goto)[^#]))*?)(\\t)?(?=\\b(?P=variable)\\b))(?<=\\n\\t)(?<!:\\n\\t)(?P=variable)\n =(?![^;]*?[^>_]\\b(?P=variable)\\b[^_])\n```\n\n\nAnd paste that into https://www.debuggex.com/, then select PCRE from the dropdown. (Sharing seems to be down at this point, so this is the only way to do it at the moment) Try it out! The regex is not as crazy as it looks.\n\n\nThere's two important assumptions this regex makes:\n1. Code is indented using tabs, and the intent level determines the scope. (this is true, because of `pgindent`)\n2. Declared variables are actually used. (this is true, because we would get compiler warnings otherwise)\n\n\nThere's two cases where this regex has some special behaviour:\n1. Stop searching for the first usage of a variable when either a `goto` or a preprocessor command is found (outside a string or comment). These things affect the control flow in a way that the regex does not understand. (any `#` character is assumed to\n be a preprocessor commands). \n2. Don't replace if the assignment is right after a `label:`, by checking if there was a `:` as the last character on the previous line. This works around errors like this:\n```\nhashovfl.c:865:3: error: a label can only be part of a statement and a declaration is not a statement\n   OffsetNumber maxroffnum = PageGetMaxOffsetNumber(rpage);\n   ^~~~~~~~~~~~\n```\nDetecting this case in this way is not perfect, because sometimes there is an extra newline or a comment between the label and the assignment. This is not easily detectable by the regex, because lookbehinds cannot have a variable length in Perl (or most\n regex engines for that matter). For these few cases (5 in the entire codebase) a manual change was done either before or after the automatic replacement to fix them so the code compiles again. (2nd and 5th commits of this patchset)\n\n\nAfter all these changes `make -s world` doesn't show any warnings or errors and `make check-world` succeeds. I configured compilation like this:\n```\n./configure --enable-cassert --enable-depend --enable-debug --with-openssl --with-libxml --with-libxslt --with-uuid=e2fs --with-icu\n```\n\n\n## What I want to achieve with this email\n\n\n1. For people to look at a small sample of the changes made by this script. I will try to send patches with the actual changes made to the code as attachments in a followup email. However, I don't know if that will succeed since the patch files are very\n big and it might run into some mailserver limits. So in case that doesn't work, the full changeset is available on Github[6]. This make viewing this enormous diff quite a bit easier IMHO anyaway. If you see something weird that is not covered in the \"Known\n issues\" section below, please share it. That way it can be discussed and/or fixed.\n2. A discussion on if this type of code change would be a net positive for Postgres codebase. Please explain clearly why or why not.\n3. Some links to resources on what's necessary to get a big refactoring patch like this merged.\n\n\n## What I don't want to achieve with this email\n\n\n1. For someone to go over all the changes right now. There's likely to be changes to the script or something else. Doing a full review of the changes would be better saved for later during a final review.\n\n\n## Known issues with the currently generated code\n\n\nThere's a few issues with the final generated code that I've already spotted. These should all be relatively easy to fix in an automated way. However, I think doing so is probably better done by `pgindent` or some other auto formatting tool, instead of\n with the regex. Note that I did run `pgindent`, it just didn't address these things:\n\n\n1. Whitespace between type and variable is kept the same as it was before moving the declaration. If the original declaration had whitespace added in such a way that all variable names of declarations aligned, then this whitespace is preserved. This looks\n weird in various cases. See [3] for an example.\n2. `pgindent` adds a newline after each block of declarations, even if they are not at the start of function. If this is desired is debatable, but to me it seems like it adds excessive newlines. See [7] for an example.\n3. If all declarations are moved away from the top of the function, then an empty newline is kept at the top of the function. This seems like an unnecessary newline to me. See [3] for an example.\n\n\nSources:\n1. `tokei`[8] results of lines of code:\nBefore:\n```\n$ tokei --type C\n===============================================================================\n Language            Files        Lines         Code     Comments       Blanks\n===============================================================================\n C                    1389      1361309       866514       330933       163862\n===============================================================================\n Total                1389      1361309       866514       330933       163862\n===============================================================================\n```\nAfter:\n```\n$ tokei --type C\n===============================================================================\n Language            Files        Lines         Code     Comments       Blanks\n===============================================================================\n C                    1389      1347515       843186       330952       173377\n===============================================================================\n Total                1389      1347515       843186       330952       173377\n===============================================================================\n```\n2. https://github.com/mgp/book-notes/blob/master/code-complete.markdown#103-guidelines-for-initializing-variables\n3. \n```patch\n@@ -401,11 +389,10 @@ pg_file_rename_internal(text *file1, text *file2, text *file3)\n Datum\n pg_file_unlink(PG_FUNCTION_ARGS)\n {\n- char   *filename;\n \n  requireSuperuser();\n \n- filename = convert_and_check_filename(PG_GETARG_TEXT_PP(0));\n+ char   *filename = convert_and_check_filename(PG_GETARG_TEXT_PP(0));\n \n  if (access(filename, W_OK) < 0)\n```\n4. https://github.com/citusdata/citus/pull/3181\n5. https://github.com/citusdata/pg_auto_failover/pull/266\n6. https://github.com/JelteF/postgres/pull/2\n7. \n```patch\n@@ -2863,7 +2886,8 @@ palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum)\n  * longer than we must.\n  */\n  Buffer buffer = ReadBufferExtended(state->rel, MAIN_FORKNUM, blocknum, RBM_NORMAL,\n- state->checkstrategy);\n+ state->checkstrategy);\n+\n  LockBuffer(buffer, BT_READ);\n \n  /*\n```\n8. https://github.com/XAMPPRocky/tokei\n\n\n\n\nObligatory jokes:\n1. https://xkcd.com/1171/\n2. https://xkcd.com/208/\n3. https://stackoverflow.com/a/1732454/2570866 (and serious response to it \nhttps://neilmadden.blog/2019/02/24/why-you-really-can-parse-html-and-anything-else-with-regular-expressions/)-1 in short.C needs readability, not fewer lines.Aside from horrible code, it doesn't improve 0.1% on anything.I think it's a bad idea and I'm strongly against it.regards,Ranier Vilela", "msg_date": "Thu, 19 Aug 2021 10:38:28 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow declaration after statement and reformat code to use it" }, { "msg_contents": "Ranier Vilela <ranier.vf@gmail.com> writes:\n> Em qui., 19 de ago. de 2021 às 08:50, Jelte Fennema <\n> Jelte.Fennema@microsoft.com> escreveu:\n>> ## Why would we want this?\n>> 1. It removes 23328 lines of code that don't have any impact on how the\n>> code behaves [1]. This is roughly 2.7% of all the lines of code in the\n>> codebase.\n\n> C needs readability, not fewer lines.\n> Aside from horrible code, it doesn't improve 0.1% on anything.\n> I think it's a bad idea and I'm strongly against it.\n\nSame here. We have thirty-ish years worth of coding habits developed\naround the existing C90-based layout rules. I really doubt that a\nquasi-mechanical transformation is going to result in better code style.\nWhat it certainly will do, though, is create a pile of hazards for\nback-patching.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 19 Aug 2021 10:34:04 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow declaration after statement and reformat code to use it" }, { "msg_contents": "On 08/19/21 09:38, Ranier Vilela wrote:\n>> 2. Declarations are closer to the actual usage. This is advised by the\n>> \"Code Complete\" book [2] and has the following advantages:\n>> a. This limits variable scope to what is necessary. Which in turn makes\n>> the mental model you have to keep of a function when reading the code\n>> simpler.\n>> b. In most cases it allows you to see the the type of a variable\n>> without needing to go to the top of the function.\n>> 3. You can do input checking and assertions at the top of the function,\n>> instead of having to put declarations in front of it. This makes it clear\n>> which invariants hold for the function. (as seen in the example above and\n>> the changes for pg_file_rename[3])\n\nI'm in sympathy with all of those points. I've never believed that the\narbitrary separation of declaration from use that was forced by C < 99\nmade anything more readable. If the project were started now from scratch,\nI would be all in favor of declaring at first use.\n\nBut I think Tom's concern about backpatching hazards may carry a lot\nof weight in practice.\n\n>> It uses a Perl regex to search and replace! (obligatory jokes at the\n>> bottom of the email)\n\nHowever, even if such an idea were to get the green light, I think I would\ntake the obligatory regex jokes seriously, and instead use something like\nsrcML [0] and do the analysis and modification on proper parse trees.\n\nRegards,\n-Chap\n\n\n[0] https://www.srcml.org/about.html\n\n\n", "msg_date": "Thu, 19 Aug 2021 11:40:44 -0400", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": false, "msg_subject": "Re: Allow declaration after statement and reformat code to use it" }, { "msg_contents": "Chapman Flack <chap@anastigmatix.net> writes:\n> I'm in sympathy with all of those points. I've never believed that the\n> arbitrary separation of declaration from use that was forced by C < 99\n> made anything more readable. If the project were started now from scratch,\n> I would be all in favor of declaring at first use.\n\nYeah, if we were starting today, I'm sure we'd use C99 or C++ as our\nbaseline and not arbitrarily exclude some language features. But ...\nwe're not. The rule against declaration-after-statement was kept\nafter significant discussion, which you can find in the archives if you\nlook. We're not going to drop it just because one person shows up with\na patch to do so.\n\n>>> It uses a Perl regex to search and replace! (obligatory jokes at the\n>>> bottom of the email)\n\n> However, even if such an idea were to get the green light, I think I would\n> take the obligatory regex jokes seriously, and instead use something like\n> srcML [0] and do the analysis and modification on proper parse trees.\n\nAgreed. I think the odds of introducing bugs are near 100% if it's done\nwithout using a tool that actually understands the code semantics.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 19 Aug 2021 12:27:25 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow declaration after statement and reformat code to use it" }, { "msg_contents": "On Thu, Aug 19, 2021 at 11:40:44AM -0400, Chapman Flack wrote:\n> I'm in sympathy with all of those points. I've never believed that the\n> arbitrary separation of declaration from use that was forced by C < 99\n> made anything more readable. If the project were started now from scratch,\n> I would be all in favor of declaring at first use.\n> \n> But I think Tom's concern about backpatching hazards may carry a lot\n> of weight in practice.\n\nI think effectively it would need to be run on all supported versions,\nwhich means the risk of introducing errors would have to be very low.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Thu, 19 Aug 2021 14:57:18 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Allow declaration after statement and reformat code to use it" }, { "msg_contents": "On Thu, Aug 19, 2021 at 10:34:04AM -0400, Tom Lane wrote:\n> Ranier Vilela <ranier.vf@gmail.com> writes:\n>> C needs readability, not fewer lines.\n>> Aside from horrible code, it doesn't improve 0.1% on anything.\n>> I think it's a bad idea and I'm strongly against it.\n> \n> Same here. We have thirty-ish years worth of coding habits developed\n> around the existing C90-based layout rules. I really doubt that a\n> quasi-mechanical transformation is going to result in better code style.\n> What it certainly will do, though, is create a pile of hazards for\n> back-patching.\n\nThe back-patching hazard this could create is an argument enough to\navoid any of that IMO if done only on HEAD. When a bug is involved,\nup to 7 branches may require a fix. That's already a lot of work.\n--\nMichael", "msg_date": "Fri, 20 Aug 2021 08:51:17 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Allow declaration after statement and reformat code to use it" }, { "msg_contents": "However, even if such an idea were to get the green light, I think I would\ntake the obligatory regex jokes seriously, and instead use something like\nsrcML [0] and do the analysis and modification on proper parse trees.\n@Chapman I think that's a reasonable ask. This is the first time I heard of srcML. It indeed looks like it would be a much better tool than a regex to do this refactor. The refactor logic would still be roughly the same though because the regex essentially extracts and modifies a parse tree too. Just one that only has the bare minimum requirements for this specific refactor. I would like to state, that we've used this regex to refactor both Citus and pg_auto_failover, and no bugs turned up because of it so far. This is probably, because a regex is such a horrible way of writing a parser in the first place. So, any bugs in the regex will very likely create code that does not compile at all, instead of code that can be compiled but has some obscure bug .\nI think effectively it would need to be run on all supported versions,\nwhich means the risk of introducing errors would have to be very low.\n@Bruce @Tom @Chapman I agree that doing this refactor only on the current master branch would cause way more pain due to backpatching, than the amount of happiness it provides by having easier to reason about code. I like the idea of avoiding this backpatching problem by running it . Luckily, running the automatic refactor on all branches should be pretty easy. However, it seems like PG11 and below only require a C89 compatible compiler. Am I correct in assuming increasing that requirement to C99 is not really an option? If so, I think it might be best if I revive this thread in ~27 months when PG11 is not supported anymore.\nThe rule against declaration-after-statement was kept\nafter significant discussion, which you can find in the archives if you\nlook.\n@Tom I guess my search skills in the archives are not very good, because I cannot find any big discussion on about declaration-after-statement. The only discussion I can find is this: https://www.postgresql.org/message-id/877efaol77.fsf@news-spur.riddles.org.uk If you're able to find that thread, could you share it?\nC needs readability, not fewer lines.\nAside from horrible code, it doesn't improve 0.1% on anything.\n@Ranier I tried to explain in my initial email that it not only reduces lines, but more importantly improves readability quite a bit IMHO:\n2. Declarations are closer to the actual usage. This is advised by the \"Code Complete\" book [2] and has the following advantages:\n a. This limits variable scope to what is necessary. Which in turn makes the mental model you have to keep of a function when reading the code simpler.\n b. In most cases it allows you to see the the type of a variable without needing to go to the top of the function.\n3. You can do input checking and assertions at the top of the function, instead of having to put declarations in front of it. This makes it clear which invariants hold for the function. (as seen in the example above and the changes for pg_file_rename[3])\nIf you disagree with those statements, could you explain why?\n\n________________________________\nFrom: Bruce Momjian <bruce@momjian.us>\nSent: Thursday, August 19, 2021 20:57\nTo: Chapman Flack <chap@anastigmatix.net>\nCc: Ranier Vilela <ranier.vf@gmail.com>; Jelte Fennema <Jelte.Fennema@microsoft.com>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>\nSubject: [EXTERNAL] Re: Allow declaration after statement and reformat code to use it\n\n[You don't often get email from bruce@momjian.us. Learn why this is important at http://aka.ms/LearnAboutSenderIdentification.]\n\nOn Thu, Aug 19, 2021 at 11:40:44AM -0400, Chapman Flack wrote:\n> I'm in sympathy with all of those points. I've never believed that the\n> arbitrary separation of declaration from use that was forced by C < 99\n> made anything more readable. If the project were started now from scratch,\n> I would be all in favor of declaring at first use.\n>\n> But I think Tom's concern about backpatching hazards may carry a lot\n> of weight in practice.\n\nI think effectively it would need to be run on all supported versions,\nwhich means the risk of introducing errors would have to be very low.\n\n--\n Bruce Momjian <bruce@momjian.us> https://nam06.safelinks.protection.outlook.com/?url=https%3A%2F%2Fmomjian.us%2F&amp;data=04%7C01%7CJelte.Fennema%40microsoft.com%7C9dc5a18c6b2947842ea408d963432ccf%7C72f988bf86f141af91ab2d7cd011db47%7C1%7C0%7C637649963502570152%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000&amp;sdata=ZVU2bVto4aJkmh5c6Yz1Ey3pJpGHrBhgFzTDBI1Z2jg%3D&amp;reserved=0\n EDB https://nam06.safelinks.protection.outlook.com/?url=https%3A%2F%2Fenterprisedb.com%2F&amp;data=04%7C01%7CJelte.Fennema%40microsoft.com%7C9dc5a18c6b2947842ea408d963432ccf%7C72f988bf86f141af91ab2d7cd011db47%7C1%7C0%7C637649963502570152%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000&amp;sdata=N25dABUPg3FMRdRMihMcZb4m1oB2rvko%2FXd2rfuCDFY%3D&amp;reserved=0\n\n If only the physical world exists, free will is an illusion.\n\n\n\n\n\n\n\n\n\n\nHowever,\n even if such an idea were to get the green light, I think I would\n\n\ntake\n the obligatory regex jokes seriously, and instead use something like\n\n\nsrcML\n [0] and do the analysis and modification on proper parse trees.\n\n\n@Chapman I think that's a reasonable ask. This is the first time I heard of srcML. It indeed looks like it would be a much better tool than a regex to do this refactor. The refactor logic\n would still be roughly the same though because the regex essentially extracts and modifies a parse tree too. Just one that only has the bare minimum requirements for this specific refactor. I would like to state, that we've used this regex to refactor both\n Citus and pg_auto_failover, and no bugs turned up because of it so far. This is probably, because a regex is such a horrible way of writing a parser in the first place. So, any bugs in the regex will very likely create code that does not compile at all, instead\n of code that can be compiled but has some obscure bug .\n\n\nI\n think effectively it would need to be run on all supported versions,\n\nwhich means\n the risk of introducing errors would have to be very low.\n\n\n@Bruce\n @Tom @Chapman I agree that doing this refactor only on the current master branch would cause way more pain due to backpatching, than the amount of happiness it provides by having easier to reason about code. I like the idea of avoiding this backpatching problem\n by running it . Luckily, running the automatic refactor on all branches should be pretty easy. However, it seems like PG11 and below only require a C89 compatible compiler. Am I correct in assuming increasing that requirement to C99 is not really an option?\n If so, I think it might be best if I revive this thread in ~27 months when PG11 is not supported anymore.\n\nThe rule against declaration-after-statement was kept\nafter significant discussion, which you can find in the archives if you\n\nlook. \n\n\n@Tom I guess my search skills in the archives are not very good, because I cannot find any big discussion\n on about declaration-after-statement. The only discussion I can find is this: https://www.postgresql.org/message-id/877efaol77.fsf@news-spur.riddles.org.uk If\n you're able to find that thread, could you share it?\n\nC needs readability, not fewer lines.\n\nAside from horrible code, it doesn't improve 0.1% on anything.\n\n\n@Ranier I tried to explain in my initial email that it not only reduces lines, but more importantly improves readability quite a bit\n IMHO:\n\n2. Declarations are closer to the actual usage. This is advised by the \"Code Complete\" book [2] and has the following advantages:\n\n   a. This limits variable scope to what is necessary. Which in turn makes the mental model you have to keep of a function when reading the code simpler.\n\n   b. In most cases it allows you to see the the type of a variable without needing to go to the top of the function.\n3. You can do input checking and assertions at the top of the function, instead of having to put declarations in front of it.\n This makes it clear which invariants hold for the function.  (as seen in the example above and the changes for pg_file_rename[3])\n\n\nIf you disagree with those statements, could you explain why?\n\n\n\n\nFrom: Bruce Momjian <bruce@momjian.us>\nSent: Thursday, August 19, 2021 20:57\nTo: Chapman Flack <chap@anastigmatix.net>\nCc: Ranier Vilela <ranier.vf@gmail.com>; Jelte Fennema <Jelte.Fennema@microsoft.com>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>\nSubject: [EXTERNAL] Re: Allow declaration after statement and reformat code to use it\n \n\n\n[You don't often get email from bruce@momjian.us. Learn why this is important at\nhttp://aka.ms/LearnAboutSenderIdentification.]\n\nOn Thu, Aug 19, 2021 at 11:40:44AM -0400, Chapman Flack wrote:\n> I'm in sympathy with all of those points. I've never believed that the\n> arbitrary separation of declaration from use that was forced by C < 99\n> made anything more readable. If the project were started now from scratch,\n> I would be all in favor of declaring at first use.\n>\n> But I think Tom's concern about backpatching hazards may carry a lot\n> of weight in practice.\n\nI think effectively it would need to be run on all supported versions,\nwhich means the risk of introducing errors would have to be very low.\n\n--\n  Bruce Momjian  <bruce@momjian.us>        \nhttps://nam06.safelinks.protection.outlook.com/?url=https%3A%2F%2Fmomjian.us%2F&amp;data=04%7C01%7CJelte.Fennema%40microsoft.com%7C9dc5a18c6b2947842ea408d963432ccf%7C72f988bf86f141af91ab2d7cd011db47%7C1%7C0%7C637649963502570152%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000&amp;sdata=ZVU2bVto4aJkmh5c6Yz1Ey3pJpGHrBhgFzTDBI1Z2jg%3D&amp;reserved=0\n  EDB                                      \nhttps://nam06.safelinks.protection.outlook.com/?url=https%3A%2F%2Fenterprisedb.com%2F&amp;data=04%7C01%7CJelte.Fennema%40microsoft.com%7C9dc5a18c6b2947842ea408d963432ccf%7C72f988bf86f141af91ab2d7cd011db47%7C1%7C0%7C637649963502570152%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000&amp;sdata=N25dABUPg3FMRdRMihMcZb4m1oB2rvko%2FXd2rfuCDFY%3D&amp;reserved=0\n\n  If only the physical world exists, free will is an illusion.", "msg_date": "Fri, 20 Aug 2021 15:29:52 +0000", "msg_from": "Jelte Fennema <Jelte.Fennema@microsoft.com>", "msg_from_op": true, "msg_subject": "Re: [EXTERNAL] Re: Allow declaration after statement and reformat\n code to use it" }, { "msg_contents": "Oops. I'm sorry. That previous email looked horrible in plaintext. Please\nregard that as unsent. Same email, but second try:\n\n> However, even if such an idea were to get the green light, I think I would\n> take the obligatory regex jokes seriously, and instead use something like\n> srcML [0] and do the analysis and modification on proper parse trees.\n\n@Chapman I think that's a reasonable ask. This is the first time I heard of\nsrcML. It indeed looks like it would be a much better tool than a regex to do\nthis refactor. The refactor logic would still be roughly the same though\nbecause the regex essentially extracts and modifies a parse tree too. Just one\nthat only has the bare minimum requirements for this specific refactor. I would\nlike to state, that we've used this regex to refactor both Citus and\npg_auto_failover, and no bugs turned up because of it so far. This is probably,\nbecause a regex is such a horrible way of writing a parser in the first place.\nSo, any bugs in the regex will very likely create code that does not compile at\nall, instead of code that can be compiled but has some obscure bug .\n\n> I think effectively it would need to be run on all supported versions, \n> which means the risk of introducing errors would have to be very low.\n\n@Bruce @Tom @Chapman I agree that doing this refactor only on the current\nmaster branch would cause way more pain due to backpatching, than the amount of\nhappiness it provides by having easier to reason about code. I like the idea of\navoiding this backpatching problem by running it . Luckily, running the\nautomatic refactor on all branches should be pretty easy. However, it seems\nlike PG11 and below only require a C89 compatible compiler. Am I correct in\nassuming increasing that requirement to C99 is not really an option? If so, I\nthink it might be best if I revive this thread in ~27 months when PG11 is not\nsupported anymore.\n\n> The rule against declaration-after-statement was kept\n> after significant discussion, which you can find in the archives if you\n> look. \n\n@Tom I guess my search skills in the archives are not very good, because I\ncannot find any big discussion on about declaration-after-statement. The only\ndiscussion I can find is this: \nhttps://www.postgresql.org/message-id/877efaol77.fsf@news-spur.riddles.org.uk \n\nIf you're able to find the thread that you meant, could you please share it?\n\n> C needs readability, not fewer lines.\n> Aside from horrible code, it doesn't improve 0.1% on anything.\n\n@Ranier I tried to explain in my initial email that it not only reduces lines,\nbut more importantly improves readability quite a bit IMHO:\n\n> 2. Declarations are closer to the actual usage. This is advised by the \n> \"Code Complete\" book [2] and has the following advantages:\n>    a. This limits variable scope to what is necessary. Which in turn makes\n> the mental model you have to keep of a function when reading the code\n> simpler.\n>    b. In most cases it allows you to see the the type of a variable without\n> needing to go to the top of the function.\n> 3. You can do input checking and assertions at the top of the function,\n> instead of having to put declarations in front of it. This makes it clear\n> which invariants hold for the function.  (as seen in the example above and\n> the changes for pg_file_rename[3])\n\nIf you disagree with those statements, could you explain why?\n\n", "msg_date": "Fri, 20 Aug 2021 16:01:06 +0000", "msg_from": "Jelte Fennema <Jelte.Fennema@microsoft.com>", "msg_from_op": true, "msg_subject": "Re: [EXTERNAL] Re: Allow declaration after statement and reformat\n code to use it" }, { "msg_contents": "Em sex., 20 de ago. de 2021 às 12:29, Jelte Fennema <\nJelte.Fennema@microsoft.com> escreveu:\n\n> However, even if such an idea were to get the green light, I think I would\n> take the obligatory regex jokes seriously, and instead use something like\n> srcML [0] and do the analysis and modification on proper parse trees.\n>\n> @Chapman I think that's a reasonable ask. This is the first time I heard\n> of srcML. It indeed looks like it would be a much better tool than a regex\n> to do this refactor. The refactor logic would still be roughly the same\n> though because the regex essentially extracts and modifies a parse tree\n> too. Just one that only has the bare minimum requirements for this specific\n> refactor. I would like to state, that we've used this regex to refactor\n> both Citus and pg_auto_failover, and no bugs turned up because of it so\n> far. This is probably, because a regex is such a horrible way of writing a\n> parser in the first place. So, any bugs in the regex will very likely\n> create code that does not compile at all, instead of code that can be\n> compiled but has some obscure bug .\n>\n> I think effectively it would need to be run on all supported versions,\n> which means the risk of introducing errors would have to be very low.\n>\n> @Bruce @Tom @Chapman I agree that doing this refactor only on the current\n> master branch would cause way more pain due to backpatching, than the\n> amount of happiness it provides by having easier to reason about code. I\n> like the idea of avoiding this backpatching problem by running it .\n> Luckily, running the automatic refactor on all branches should be pretty\n> easy. However, it seems like PG11 and below only require a C89 compatible\n> compiler. Am I correct in assuming increasing that requirement to C99 is\n> not really an option? If so, I think it might be best if I revive this\n> thread in ~27 months when PG11 is not supported anymore.\n>\n> The rule against declaration-after-statement was kept\n> after significant discussion, which you can find in the archives if you\n> look.\n>\n> @Tom I guess my search skills in the archives are not very good, because I\n> cannot find any big discussion on about declaration-after-statement. The\n> only discussion I can find is this:\n> https://www.postgresql.org/message-id/877efaol77.fsf@news-spur.riddles.org.uk If\n> you're able to find that thread, could you share it?\n>\n> C needs readability, not fewer lines.\n> Aside from horrible code, it doesn't improve 0.1% on anything.\n>\n> @Ranier I tried to explain in my initial email that it not only reduces\n> lines, but more importantly improves readability quite a bit IMHO:\n>\n> 2. Declarations are closer to the actual usage. This is advised by the\n> \"Code Complete\" book [2] and has the following advantages:\n> a. This limits variable scope to what is necessary. Which in turn makes\n> the mental model you have to keep of a function when reading the code\n> simpler.\n> b. In most cases it allows you to see the the type of a variable\n> without needing to go to the top of the function.\n> 3. You can do input checking and assertions at the top of the function,\n> instead of having to put declarations in front of it. This makes it clear\n> which invariants hold for the function. (as seen in the example above and\n> the changes for pg_file_rename[3])\n>\n> If you disagree with those statements, could you explain why?\n>\n2. Declarations are closer to the actual usage.\na. This limits variable scope to what is necessary\nI don't see this as an advantage, even for someone learning C today, which\nis not the case for 99% of hackers here.\nWith all declarations first, im my mental model, I can see all variables\ntogether and\nand all your relationships and dependencies.\nSpreading out the declarations, I would have to read and reread the code to\nunderstand the interdependencies of all the variables and their types.\n\nb. In most cases it allows you to see the the type of a variable without\nneeding to go to the top of the function.\nFor one variable, perhaps, but I can see all of them and because of one\nvariable I have the opportunity to find some fault in the other variables.\nI agree that the Postgres code does not help much, because there is no\nclear organization.\nAs I do in my codes, where I organize the variables by type and use,\naligned, which greatly facilitates the complete view.\nWhat in my opinion would be the ideal path for Postgres, but it involves\nchanging the habits of people who code for years.\nWhat are you proposing to do now, with a high chance of increasing bugs.\n\n3. You can do input checking and assertions at the top of the function,\ninstead of having to put declarations in front of it. This makes it clear\nwhich invariants hold for the function.\nAnd you can easily forget to validate some variable you're not seeing is\nseveral lines down.\n\nThere is a reason why GMs Brian Kernighan and Dennis Ritchie made the C89,\nless buggy.\nIMHO C99 makes it easy to make more mistakes.\nOne more step and we won't even need to declare a variable.\n\nregards,\nRanier Vilela\n\nEm sex., 20 de ago. de 2021 às 12:29, Jelte Fennema <Jelte.Fennema@microsoft.com> escreveu:\n\n\n\nHowever,\n even if such an idea were to get the green light, I think I would\n\n\ntake\n the obligatory regex jokes seriously, and instead use something like\n\n\nsrcML\n [0] and do the analysis and modification on proper parse trees.\n\n\n@Chapman I think that's a reasonable ask. This is the first time I heard of srcML. It indeed looks like it would be a much better tool than a regex to do this refactor. The refactor logic\n would still be roughly the same though because the regex essentially extracts and modifies a parse tree too. Just one that only has the bare minimum requirements for this specific refactor. I would like to state, that we've used this regex to refactor both\n Citus and pg_auto_failover, and no bugs turned up because of it so far. This is probably, because a regex is such a horrible way of writing a parser in the first place. So, any bugs in the regex will very likely create code that does not compile at all, instead\n of code that can be compiled but has some obscure bug .\n\n\nI\n think effectively it would need to be run on all supported versions,\n\nwhich means\n the risk of introducing errors would have to be very low.\n\n\n@Bruce\n @Tom @Chapman I agree that doing this refactor only on the current master branch would cause way more pain due to backpatching, than the amount of happiness it provides by having easier to reason about code. I like the idea of avoiding this backpatching problem\n by running it . Luckily, running the automatic refactor on all branches should be pretty easy. However, it seems like PG11 and below only require a C89 compatible compiler. Am I correct in assuming increasing that requirement to C99 is not really an option?\n If so, I think it might be best if I revive this thread in ~27 months when PG11 is not supported anymore.\n\nThe rule against declaration-after-statement was kept\nafter significant discussion, which you can find in the archives if you\n\nlook. \n\n\n@Tom I guess my search skills in the archives are not very good, because I cannot find any big discussion\n on about declaration-after-statement. The only discussion I can find is this: https://www.postgresql.org/message-id/877efaol77.fsf@news-spur.riddles.org.uk If\n you're able to find that thread, could you share it?\n\nC needs readability, not fewer lines.\n\nAside from horrible code, it doesn't improve 0.1% on anything.\n\n\n@Ranier I tried to explain in my initial email that it not only reduces lines, but more importantly improves readability quite a bit\n IMHO:\n\n2. Declarations are closer to the actual usage. This is advised by the \"Code Complete\" book [2] and has the following advantages:\n\n   a. This limits variable scope to what is necessary. Which in turn makes the mental model you have to keep of a function when reading the code simpler.\n\n   b. In most cases it allows you to see the the type of a variable without needing to go to the top of the function.\n3. You can do input checking and assertions at the top of the function, instead of having to put declarations in front of it.\n This makes it clear which invariants hold for the function.  (as seen in the example above and the changes for pg_file_rename[3])\n\n\nIf you disagree with those statements, could you explain why?2.\n Declarations are closer to the actual usage. a. This limits variable scope to what is necessary\nI don't see this as an advantage, even for someone learning C today, which is not the case for 99% of hackers here.With all declarations first, im my mental model, I can see all variables together and and all your relationships and dependencies.Spreading out the declarations, I would have to read and reread the code to understand the interdependencies of all the variables and their types.b. In most cases it allows you to see the the type of a variable without needing to go to the top of the function.For one variable, perhaps, but I can see all of them and because of one variable I have the opportunity to find some fault in the other variables.\nI agree that the Postgres code does not help much, because there is no clear organization.As I do in my codes, where I organize the variables by type and use, aligned, which greatly facilitates the complete view.What in my opinion would be the ideal path for Postgres, but it involves changing the habits of people who code for years.What are you proposing to do now, with a high chance of increasing bugs.\n3. You can do input checking and assertions at the top of the function, instead of having to put declarations in front of it.\n This makes it clear which invariants hold for the function.And you can easily forget to validate some variable you're not seeing is several lines down.There is a reason why GMs Brian Kernighan and Dennis Ritchie made the C89, less buggy.IMHO C99 makes it easy to make more mistakes.One more step and we won't even need to declare a variable.regards,Ranier Vilela", "msg_date": "Fri, 20 Aug 2021 13:30:27 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [EXTERNAL] Re: Allow declaration after statement and reformat\n code to use it" }, { "msg_contents": "\nOn 8/20/21 12:30 PM, Ranier Vilela wrote:\n>\n>\n> There is a reason why GMs Brian Kernighan and Dennis Ritchie made the\n> C89, less buggy.\n> IMHO C99 makes it easy to make more mistakes.\n> One more step and we won't even need to declare a variable.\n>\n>\n\nI've used both styles in different languages over the years. I don't\nknow that one is a clearly better way, notwithstanding what various\ntheorists might say.\n\nNote that in C89 it's fantastically easy to put the declaration as close\nas you like to the first use of a variable. All it takes is a pair of\nbraces enclosing the variable scope.\n\nEven if we were to relax our rules on this, making wholesale changes\nalong these lines and even more backpatching them seem out of the question.\n\n\ncheers\n\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Sat, 21 Aug 2021 11:01:57 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: [EXTERNAL] Re: Allow declaration after statement and reformat\n code to use it" }, { "msg_contents": "Em sáb., 21 de ago. de 2021 às 12:02, Andrew Dunstan <andrew@dunslane.net>\nescreveu:\n\n>\n> On 8/20/21 12:30 PM, Ranier Vilela wrote:\n> >\n> >\n> > There is a reason why GMs Brian Kernighan and Dennis Ritchie made the\n> > C89, less buggy.\n> > IMHO C99 makes it easy to make more mistakes.\n> > One more step and we won't even need to declare a variable.\n> >\n> >\n>\n> I've used both styles in different languages over the years. I don't\n> know that one is a clearly better way, notwithstanding what various\n> theorists might say.\n>\nIMO declarations first is better, without a shadow of a doubt.\nMaybe because my mind is vision.\nSeeing the complete view, I can look for bugs and find some way to improve\nperformance.\nIt's one of the reasons for having small, well-defined functions.\nOf course, with extra reward, you can and should reduce the scope.\nIn this case the compiler does a better job and generates more optimized\ncode.\n\nXLogRecPtr\nXLogInsertRecord(XLogRecData *rdata,\n XLogRecPtr fpw_lsn,\n uint8 flags,\n int num_fpi)\n{\n XLogCtlInsert *Insert = &XLogCtl->Insert; /*\nWhat is the purpose of this variable */\n XLogRecord *rechdr = (XLogRecord *) rdata->data; /* What is the\npurpose of this variable */\n XLogRecPtr\nStartPos; /* What is the\npurpose of this variable */\n XLogRecPtr\nEndPos; /* What is the\npurpose of this variable */\n pg_crc32c\nrdata_crc; /* What is the\npurpose of this variable */\n uint8 info = rechdr->xl_info & ~XLR_INFO_MASK;\n bool isLogSwitch = (rechdr->xl_rmid == RM_XLOG_ID && info ==\nXLOG_SWITCH);\n bool prevDoPageWrites = doPageWrites;\n bool inserted;\n\n /* we assume that all of the record header is in the first chunk\n*/\n Assert(rdata->len >= SizeOfXLogRecord);\n\n /* cross-check on whether we should be here or not */\n if (!XLogInsertAllowed())\n elog(ERROR, \"cannot make new WAL entries during recovery\");\n\nAll declarations organized by type and use, almost a structure.\nNo need to find or think, just see.\nWe can immediately connect variable info with isLogSwitch.\n\n\n> Note that in C89 it's fantastically easy to put the declaration as close\n> as you like to the first use of a variable. All it takes is a pair of\n> braces enclosing the variable scope.\n>\nIMO is an exception, which does not follow the C89 pattern.\nIt's a valid last resource, of course, but not as good practice.\n\n\n> Even if we were to relax our rules on this, making wholesale changes\n> along these lines and even more backpatching them seem out of the question.\n>\nIt would be a nightmare.\n\nregards,\nRanier Vilela\n\nEm sáb., 21 de ago. de 2021 às 12:02, Andrew Dunstan <andrew@dunslane.net> escreveu:\r\nOn 8/20/21 12:30 PM, Ranier Vilela wrote:\r\n>\r\n>\r\n> There is a reason why GMs Brian Kernighan and Dennis Ritchie made the\r\n> C89, less buggy.\r\n> IMHO C99 makes it easy to make more mistakes.\r\n> One more step and we won't even need to declare a variable.\r\n>\r\n>\n\r\nI've used both styles in different languages over the years. I don't\r\nknow that one is a clearly better way, notwithstanding what various\r\ntheorists might say.IMO declarations first is better, without a shadow of a doubt.Maybe because my mind is vision.Seeing the complete view, I can look for bugs and find some way to improve performance.It's one of the reasons for having small, well-defined functions.Of course, with extra reward, you can and should reduce the scope.In this case the compiler does a better job and generates more optimized code.XLogRecPtrXLogInsertRecord(XLogRecData *rdata,                               XLogRecPtr fpw_lsn,                              uint8 flags,                              int num_fpi){           XLogCtlInsert *Insert = &XLogCtl->Insert;                   /* What is the purpose of this variable */\r\n           XLogRecord *rechdr = (XLogRecord *) rdata->data;  \r\n/* What is the purpose of this variable */\r\n\r\n\r\n\r\n\r\n           XLogRecPtr\tStartPos;                                                 \r\n/* What is the purpose of this variable */\r\n\r\n           XLogRecPtr\tEndPos;                                                  \r\n/* What is the purpose of this variable */\r\n\r\n\r\n\r\n           pg_crc32c\trdata_crc;                                                 \r\n/* What is the purpose of this variable */\r\n\r\n           uint8\t\tinfo = rechdr->xl_info & ~XLR_INFO_MASK;           bool\t\tisLogSwitch = (rechdr->xl_rmid == RM_XLOG_ID && info == XLOG_SWITCH);           bool\t\tprevDoPageWrites = doPageWrites;\r\n           bool\t\tinserted;\n           /* we assume that all of the record header is in the first chunk */          Assert(rdata->len >= SizeOfXLogRecord);          /* cross-check on whether we should be here or not */         if (!XLogInsertAllowed())             elog(ERROR, \"cannot make new WAL entries during recovery\");All declarations organized by type and use, almost a structure.No need to find or think, just see.We can immediately connect variable info with isLogSwitch.\n\r\nNote that in C89 it's fantastically easy to put the declaration as close\r\nas you like to the first use of a variable. All it takes is a pair of\r\nbraces enclosing the variable scope.IMO is an exception, which does not follow the C89 pattern.It's a valid last resource, of course, but not as good practice. \n\r\nEven if we were to relax our rules on this, making wholesale changes\r\nalong these lines and even more backpatching them seem out of the question.It would be a nightmare.regards,Ranier Vilela", "msg_date": "Sat, 21 Aug 2021 17:05:39 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [EXTERNAL] Re: Allow declaration after statement and reformat\n code to use it" } ]
[ { "msg_contents": "Hi all ,\n\nIt's reported on pgsql-bugs[1] that I/O timings in EXPLAIN don't show\nthe one for temp files. I think it's not a bug but could be an item\nfor PG15. As mentioned on that thread, this would be useful for users\nin a case where temp buffers I/O used most of the time. So I've\nwritten the patch for that. Please note that the patch includes only\nto show temp buffer I/O timing to EXPLAIN but not other possibly\nrelated changes such as pg_stat_statement improvements yet.\n\nBefore (w/o patch):\npostgres(1:14101)=# explain (analyze, buffers) select count(*) from\ngenerate_series(1,100000);\n QUERY PLAN\n-----------------------------------------------------------------------------------------------------------------------------------\n Aggregate (cost=1250.00..1250.01 rows=1 width=8) (actual\ntime=59.025..59.026 rows=1 loops=1)\n Buffers: temp read=171 written=171\n -> Function Scan on generate_series (cost=0.00..1000.00\nrows=100000 width=0) (actual time=21.695..45.524 rows=100000 loops=1)\n Buffers: temp read=171 written=171\n Planning Time: 0.041 ms\n Execution Time: 70.867 ms\n(6 rows)\n\nAfter (w/ patch):\npostgres(1:28754)=# explain (analyze, buffers) select count(*) from\ngenerate_series(1,100000);\n QUERY PLAN\n-----------------------------------------------------------------------------------------------------------------------------------\n Aggregate (cost=1250.00..1250.01 rows=1 width=8) (actual\ntime=56.189..56.190 rows=1 loops=1)\n Buffers: temp read=171 written=171\n I/O Timings: temp read=0.487 write=2.073\n -> Function Scan on generate_series (cost=0.00..1000.00\nrows=100000 width=0) (actual time=21.072..42.886 rows=100000 loops=1)\n Buffers: temp read=171 written=171\n I/O Timings: temp read=0.487 write=2.073\n Planning Time: 0.041 ms\n Execution Time: 59.928 ms\n(8 rows)\n\nFeedback is very welcome.\n\nRegards,\n\n[1] https://www.postgresql.org/message-id/20210709084355.GA6251%40depesz.com\n\n--\nMasahiko Sawada\nEDB: https://www.enterprisedb.com/", "msg_date": "Thu, 19 Aug 2021 21:20:38 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": true, "msg_subject": "Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "Em qui., 19 de ago. de 2021 às 09:21, Masahiko Sawada <sawada.mshk@gmail.com>\nescreveu:\n\n> Hi all ,\n>\n> It's reported on pgsql-bugs[1] that I/O timings in EXPLAIN don't show\n> the one for temp files. I think it's not a bug but could be an item\n> for PG15. As mentioned on that thread, this would be useful for users\n> in a case where temp buffers I/O used most of the time. So I've\n> written the patch for that. Please note that the patch includes only\n> to show temp buffer I/O timing to EXPLAIN but not other possibly\n> related changes such as pg_stat_statement improvements yet.\n>\n> Before (w/o patch):\n> postgres(1:14101)=# explain (analyze, buffers) select count(*) from\n> generate_series(1,100000);\n> QUERY PLAN\n>\n> -----------------------------------------------------------------------------------------------------------------------------------\n> Aggregate (cost=1250.00..1250.01 rows=1 width=8) (actual\n> time=59.025..59.026 rows=1 loops=1)\n> Buffers: temp read=171 written=171\n> -> Function Scan on generate_series (cost=0.00..1000.00\n> rows=100000 width=0) (actual time=21.695..45.524 rows=100000 loops=1)\n> Buffers: temp read=171 written=171\n> Planning Time: 0.041 ms\n> Execution Time: 70.867 ms\n> (6 rows)\n>\n> After (w/ patch):\n> postgres(1:28754)=# explain (analyze, buffers) select count(*) from\n> generate_series(1,100000);\n> QUERY PLAN\n>\n> -----------------------------------------------------------------------------------------------------------------------------------\n> Aggregate (cost=1250.00..1250.01 rows=1 width=8) (actual\n> time=56.189..56.190 rows=1 loops=1)\n> Buffers: temp read=171 written=171\n> I/O Timings: temp read=0.487 write=2.073\n> -> Function Scan on generate_series (cost=0.00..1000.00\n> rows=100000 width=0) (actual time=21.072..42.886 rows=100000 loops=1)\n> Buffers: temp read=171 written=171\n> I/O Timings: temp read=0.487 write=2.073\n> Planning Time: 0.041 ms\n> Execution Time: 59.928 ms\n> (8 rows)\n>\n> Feedback is very welcome.\n>\nThe presentation seems a little confusing, wouldn't it be better?\n\nI/O Timings: shared/local read=xxxx write=xxx temp read=0.487 write=2.073\n\nI think can remove this lines:\n+ if (has_temp_timing)\n+ appendStringInfoChar(es->str, ',');\n\nregards,\nRanier Vilela\n\nEm qui., 19 de ago. de 2021 às 09:21, Masahiko Sawada <sawada.mshk@gmail.com> escreveu:Hi all ,\n\nIt's reported on pgsql-bugs[1] that I/O timings in EXPLAIN don't show\nthe one for temp files. I think it's not a bug but could be an item\nfor PG15. As mentioned on that thread, this would be useful for users\nin a case where temp buffers I/O used most of the time. So I've\nwritten the patch for that. Please note that the patch includes only\nto show temp buffer I/O timing to EXPLAIN but not other possibly\nrelated changes such as pg_stat_statement improvements yet.\n\nBefore (w/o patch):\npostgres(1:14101)=# explain (analyze, buffers) select count(*) from\ngenerate_series(1,100000);\n                                                            QUERY PLAN\n-----------------------------------------------------------------------------------------------------------------------------------\n Aggregate  (cost=1250.00..1250.01 rows=1 width=8) (actual\ntime=59.025..59.026 rows=1 loops=1)\n   Buffers: temp read=171 written=171\n   ->  Function Scan on generate_series  (cost=0.00..1000.00\nrows=100000 width=0) (actual time=21.695..45.524 rows=100000 loops=1)\n         Buffers: temp read=171 written=171\n Planning Time: 0.041 ms\n Execution Time: 70.867 ms\n(6 rows)\n\nAfter (w/ patch):\npostgres(1:28754)=# explain (analyze, buffers) select count(*) from\ngenerate_series(1,100000);\n                                                            QUERY PLAN\n-----------------------------------------------------------------------------------------------------------------------------------\n Aggregate  (cost=1250.00..1250.01 rows=1 width=8) (actual\ntime=56.189..56.190 rows=1 loops=1)\n   Buffers: temp read=171 written=171\n   I/O Timings: temp read=0.487 write=2.073\n   ->  Function Scan on generate_series  (cost=0.00..1000.00\nrows=100000 width=0) (actual time=21.072..42.886 rows=100000 loops=1)\n         Buffers: temp read=171 written=171\n         I/O Timings: temp read=0.487 write=2.073\n Planning Time: 0.041 ms\n Execution Time: 59.928 ms\n(8 rows)\n\nFeedback is very welcome.The presentation seems a little confusing, wouldn't it be better?\nI/O Timings: shared/local \nread=xxxx write=xxx\n\n\n\ntemp read=0.487 write=2.073 I think can remove this lines:+\t\t\t\tif (has_temp_timing)+\t\t\t\t\tappendStringInfoChar(es->str, ',');regards,Ranier Vilela", "msg_date": "Thu, 19 Aug 2021 10:52:36 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Thu, Aug 19, 2021 at 10:52 PM Ranier Vilela <ranier.vf@gmail.com> wrote:\n>\n> Em qui., 19 de ago. de 2021 às 09:21, Masahiko Sawada <sawada.mshk@gmail.com> escreveu:\n>>\n>> Hi all ,\n>>\n>> It's reported on pgsql-bugs[1] that I/O timings in EXPLAIN don't show\n>> the one for temp files. I think it's not a bug but could be an item\n>> for PG15. As mentioned on that thread, this would be useful for users\n>> in a case where temp buffers I/O used most of the time. So I've\n>> written the patch for that. Please note that the patch includes only\n>> to show temp buffer I/O timing to EXPLAIN but not other possibly\n>> related changes such as pg_stat_statement improvements yet.\n>>\n>> Before (w/o patch):\n>> postgres(1:14101)=# explain (analyze, buffers) select count(*) from\n>> generate_series(1,100000);\n>> QUERY PLAN\n>> -----------------------------------------------------------------------------------------------------------------------------------\n>> Aggregate (cost=1250.00..1250.01 rows=1 width=8) (actual\n>> time=59.025..59.026 rows=1 loops=1)\n>> Buffers: temp read=171 written=171\n>> -> Function Scan on generate_series (cost=0.00..1000.00\n>> rows=100000 width=0) (actual time=21.695..45.524 rows=100000 loops=1)\n>> Buffers: temp read=171 written=171\n>> Planning Time: 0.041 ms\n>> Execution Time: 70.867 ms\n>> (6 rows)\n>>\n>> After (w/ patch):\n>> postgres(1:28754)=# explain (analyze, buffers) select count(*) from\n>> generate_series(1,100000);\n>> QUERY PLAN\n>> -----------------------------------------------------------------------------------------------------------------------------------\n>> Aggregate (cost=1250.00..1250.01 rows=1 width=8) (actual\n>> time=56.189..56.190 rows=1 loops=1)\n>> Buffers: temp read=171 written=171\n>> I/O Timings: temp read=0.487 write=2.073\n>> -> Function Scan on generate_series (cost=0.00..1000.00\n>> rows=100000 width=0) (actual time=21.072..42.886 rows=100000 loops=1)\n>> Buffers: temp read=171 written=171\n>> I/O Timings: temp read=0.487 write=2.073\n>> Planning Time: 0.041 ms\n>> Execution Time: 59.928 ms\n>> (8 rows)\n>>\n>> Feedback is very welcome.\n>\n\nThank you for the comments!\n\n> The presentation seems a little confusing, wouldn't it be better?\n>\n> I/O Timings: shared/local read=xxxx write=xxx temp read=0.487 write=2.073\n\nYeah, it looks better to add \"shared/local\".\n\n>\n> I think can remove this lines:\n> + if (has_temp_timing)\n> + appendStringInfoChar(es->str, ',');\n\nBut I think that it's consistent with buffers statistics in EXPLAIN\ncommand. For example, \"Buffers\" in the output of EXPLAIN command could\nbe like:\n\nBuffers: shared hit=1398, temp read=526 written=526\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Mon, 23 Aug 2021 10:46:42 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Mon, Aug 23, 2021 at 10:46 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Thu, Aug 19, 2021 at 10:52 PM Ranier Vilela <ranier.vf@gmail.com> wrote:\n> >\n> > Em qui., 19 de ago. de 2021 às 09:21, Masahiko Sawada <sawada.mshk@gmail.com> escreveu:\n> >>\n> >> Hi all ,\n> >>\n> >> It's reported on pgsql-bugs[1] that I/O timings in EXPLAIN don't show\n> >> the one for temp files. I think it's not a bug but could be an item\n> >> for PG15. As mentioned on that thread, this would be useful for users\n> >> in a case where temp buffers I/O used most of the time. So I've\n> >> written the patch for that. Please note that the patch includes only\n> >> to show temp buffer I/O timing to EXPLAIN but not other possibly\n> >> related changes such as pg_stat_statement improvements yet.\n> >>\n> >> Before (w/o patch):\n> >> postgres(1:14101)=# explain (analyze, buffers) select count(*) from\n> >> generate_series(1,100000);\n> >> QUERY PLAN\n> >> -----------------------------------------------------------------------------------------------------------------------------------\n> >> Aggregate (cost=1250.00..1250.01 rows=1 width=8) (actual\n> >> time=59.025..59.026 rows=1 loops=1)\n> >> Buffers: temp read=171 written=171\n> >> -> Function Scan on generate_series (cost=0.00..1000.00\n> >> rows=100000 width=0) (actual time=21.695..45.524 rows=100000 loops=1)\n> >> Buffers: temp read=171 written=171\n> >> Planning Time: 0.041 ms\n> >> Execution Time: 70.867 ms\n> >> (6 rows)\n> >>\n> >> After (w/ patch):\n> >> postgres(1:28754)=# explain (analyze, buffers) select count(*) from\n> >> generate_series(1,100000);\n> >> QUERY PLAN\n> >> -----------------------------------------------------------------------------------------------------------------------------------\n> >> Aggregate (cost=1250.00..1250.01 rows=1 width=8) (actual\n> >> time=56.189..56.190 rows=1 loops=1)\n> >> Buffers: temp read=171 written=171\n> >> I/O Timings: temp read=0.487 write=2.073\n> >> -> Function Scan on generate_series (cost=0.00..1000.00\n> >> rows=100000 width=0) (actual time=21.072..42.886 rows=100000 loops=1)\n> >> Buffers: temp read=171 written=171\n> >> I/O Timings: temp read=0.487 write=2.073\n> >> Planning Time: 0.041 ms\n> >> Execution Time: 59.928 ms\n> >> (8 rows)\n> >>\n> >> Feedback is very welcome.\n> >\n>\n> Thank you for the comments!\n>\n> > The presentation seems a little confusing, wouldn't it be better?\n> >\n> > I/O Timings: shared/local read=xxxx write=xxx temp read=0.487 write=2.073\n>\n> Yeah, it looks better to add \"shared/local\".\n\nI've attached the updated patch that incorporates the above comment.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/", "msg_date": "Tue, 24 Aug 2021 15:10:24 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "Em ter., 24 de ago. de 2021 às 03:11, Masahiko Sawada <sawada.mshk@gmail.com>\nescreveu:\n\n> On Mon, Aug 23, 2021 at 10:46 AM Masahiko Sawada <sawada.mshk@gmail.com>\n> wrote:\n> >\n> > On Thu, Aug 19, 2021 at 10:52 PM Ranier Vilela <ranier.vf@gmail.com>\n> wrote:\n> > >\n> > > Em qui., 19 de ago. de 2021 às 09:21, Masahiko Sawada <\n> sawada.mshk@gmail.com> escreveu:\n> > >>\n> > >> Hi all ,\n> > >>\n> > >> It's reported on pgsql-bugs[1] that I/O timings in EXPLAIN don't show\n> > >> the one for temp files. I think it's not a bug but could be an item\n> > >> for PG15. As mentioned on that thread, this would be useful for users\n> > >> in a case where temp buffers I/O used most of the time. So I've\n> > >> written the patch for that. Please note that the patch includes only\n> > >> to show temp buffer I/O timing to EXPLAIN but not other possibly\n> > >> related changes such as pg_stat_statement improvements yet.\n> > >>\n> > >> Before (w/o patch):\n> > >> postgres(1:14101)=# explain (analyze, buffers) select count(*) from\n> > >> generate_series(1,100000);\n> > >> QUERY PLAN\n> > >>\n> -----------------------------------------------------------------------------------------------------------------------------------\n> > >> Aggregate (cost=1250.00..1250.01 rows=1 width=8) (actual\n> > >> time=59.025..59.026 rows=1 loops=1)\n> > >> Buffers: temp read=171 written=171\n> > >> -> Function Scan on generate_series (cost=0.00..1000.00\n> > >> rows=100000 width=0) (actual time=21.695..45.524 rows=100000 loops=1)\n> > >> Buffers: temp read=171 written=171\n> > >> Planning Time: 0.041 ms\n> > >> Execution Time: 70.867 ms\n> > >> (6 rows)\n> > >>\n> > >> After (w/ patch):\n> > >> postgres(1:28754)=# explain (analyze, buffers) select count(*) from\n> > >> generate_series(1,100000);\n> > >> QUERY PLAN\n> > >>\n> -----------------------------------------------------------------------------------------------------------------------------------\n> > >> Aggregate (cost=1250.00..1250.01 rows=1 width=8) (actual\n> > >> time=56.189..56.190 rows=1 loops=1)\n> > >> Buffers: temp read=171 written=171\n> > >> I/O Timings: temp read=0.487 write=2.073\n> > >> -> Function Scan on generate_series (cost=0.00..1000.00\n> > >> rows=100000 width=0) (actual time=21.072..42.886 rows=100000 loops=1)\n> > >> Buffers: temp read=171 written=171\n> > >> I/O Timings: temp read=0.487 write=2.073\n> > >> Planning Time: 0.041 ms\n> > >> Execution Time: 59.928 ms\n> > >> (8 rows)\n> > >>\n> > >> Feedback is very welcome.\n> > >\n> >\n> > Thank you for the comments!\n> >\n> > > The presentation seems a little confusing, wouldn't it be better?\n> > >\n> > > I/O Timings: shared/local read=xxxx write=xxx temp read=0.487\n> write=2.073\n> >\n> > Yeah, it looks better to add \"shared/local\".\n>\n> I've attached the updated patch that incorporates the above comment.\n>\nThe patch looks fine to me.\n\nregards,\nRanier Vilela\n\nEm ter., 24 de ago. de 2021 às 03:11, Masahiko Sawada <sawada.mshk@gmail.com> escreveu:On Mon, Aug 23, 2021 at 10:46 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Thu, Aug 19, 2021 at 10:52 PM Ranier Vilela <ranier.vf@gmail.com> wrote:\n> >\n> > Em qui., 19 de ago. de 2021 às 09:21, Masahiko Sawada <sawada.mshk@gmail.com> escreveu:\n> >>\n> >> Hi all ,\n> >>\n> >> It's reported on pgsql-bugs[1] that I/O timings in EXPLAIN don't show\n> >> the one for temp files. I think it's not a bug but could be an item\n> >> for PG15. As mentioned on that thread, this would be useful for users\n> >> in a case where temp buffers I/O used most of the time. So I've\n> >> written the patch for that. Please note that the patch includes only\n> >> to show temp buffer I/O timing to EXPLAIN but not other possibly\n> >> related changes such as pg_stat_statement improvements yet.\n> >>\n> >> Before (w/o patch):\n> >> postgres(1:14101)=# explain (analyze, buffers) select count(*) from\n> >> generate_series(1,100000);\n> >>                                                             QUERY PLAN\n> >> -----------------------------------------------------------------------------------------------------------------------------------\n> >>  Aggregate  (cost=1250.00..1250.01 rows=1 width=8) (actual\n> >> time=59.025..59.026 rows=1 loops=1)\n> >>    Buffers: temp read=171 written=171\n> >>    ->  Function Scan on generate_series  (cost=0.00..1000.00\n> >> rows=100000 width=0) (actual time=21.695..45.524 rows=100000 loops=1)\n> >>          Buffers: temp read=171 written=171\n> >>  Planning Time: 0.041 ms\n> >>  Execution Time: 70.867 ms\n> >> (6 rows)\n> >>\n> >> After (w/ patch):\n> >> postgres(1:28754)=# explain (analyze, buffers) select count(*) from\n> >> generate_series(1,100000);\n> >>                                                             QUERY PLAN\n> >> -----------------------------------------------------------------------------------------------------------------------------------\n> >>  Aggregate  (cost=1250.00..1250.01 rows=1 width=8) (actual\n> >> time=56.189..56.190 rows=1 loops=1)\n> >>    Buffers: temp read=171 written=171\n> >>    I/O Timings: temp read=0.487 write=2.073\n> >>    ->  Function Scan on generate_series  (cost=0.00..1000.00\n> >> rows=100000 width=0) (actual time=21.072..42.886 rows=100000 loops=1)\n> >>          Buffers: temp read=171 written=171\n> >>          I/O Timings: temp read=0.487 write=2.073\n> >>  Planning Time: 0.041 ms\n> >>  Execution Time: 59.928 ms\n> >> (8 rows)\n> >>\n> >> Feedback is very welcome.\n> >\n>\n> Thank you for the comments!\n>\n> > The presentation seems a little confusing, wouldn't it be better?\n> >\n> > I/O Timings: shared/local read=xxxx write=xxx temp read=0.487 write=2.073\n>\n> Yeah, it looks better to add \"shared/local\".\n\nI've attached the updated patch that incorporates the above comment.The patch looks fine to me.regards,Ranier Vilela", "msg_date": "Tue, 24 Aug 2021 08:20:16 -0300", "msg_from": "Ranier Vilela <ranier.vf@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "Hi,\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn Tuesday, August 24th, 2021 at 13:20, Ranier Vilela <ranier.vf@gmail.com> wrote:\n\n> Em ter., 24 de ago. de 2021 às 03:11, Masahiko Sawada <sawada.mshk@gmail.com> escreveu:\n>\n> > On Mon, Aug 23, 2021 at 10:46 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > >\n> > > On Thu, Aug 19, 2021 at 10:52 PM Ranier Vilela <ranier.vf@gmail.com> wrote:\n> > > >\n> > > > Em qui., 19 de ago. de 2021 às 09:21, Masahiko Sawada <sawada.mshk@gmail.com> escreveu:\n> > > >>\n> > > >> Hi all ,\n> > > >>\n> > > >> It's reported on pgsql-bugs[1] that I/O timings in EXPLAIN don't show\n\n<snip>\n\n> >\n> > I've attached the updated patch that incorporates the above comment.\n>\n> The patch looks fine to me.\n>\n\nThe patch looks good to me too. However I do wonder why the timing is added only on\nthe\n\n if (es->format == EXPLAIN_FORMAT_TEXT)\n\nblock and is not added when, for example, the format is json. The instrumentation has\nclearly recorded the timings regardless of the output format.\n\nAlso, it might be worth while to consider adding some regression tests. To my\nunderstanding, explain.sql provides a function, explain_filter, which helps create\na stable result. For example, such a test case can be:\n\n set track_io_timing = 'on';\n select explain_filter('explain (analyze, buffers) select count(*) from generate_series(1,100000)');\n\nthen it would be enough to verify that the line:\n\n I/O Timings: temp read=N.N write=N.N\n\nis present. The above would apply on the json output via `explain_filter_to_json`\nof course.\n\nThoughts?\n\nCheers,\n//Georgios\n\n\n", "msg_date": "Mon, 06 Sep 2021 15:02:50 +0000", "msg_from": "gkokolatos@pm.me", "msg_from_op": false, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Tue, Sep 7, 2021 at 12:02 AM <gkokolatos@pm.me> wrote:\n>\n> Hi,\n>\n> ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\n> On Tuesday, August 24th, 2021 at 13:20, Ranier Vilela <ranier.vf@gmail.com> wrote:\n>\n> > Em ter., 24 de ago. de 2021 às 03:11, Masahiko Sawada <sawada.mshk@gmail.com> escreveu:\n> >\n> > > On Mon, Aug 23, 2021 at 10:46 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> > >\n> > > >\n> > > > On Thu, Aug 19, 2021 at 10:52 PM Ranier Vilela <ranier.vf@gmail.com> wrote:\n> > > > >\n> > > > > Em qui., 19 de ago. de 2021 às 09:21, Masahiko Sawada <sawada.mshk@gmail.com> escreveu:\n> > > > >>\n> > > > >> Hi all ,\n> > > > >>\n> > > > >> It's reported on pgsql-bugs[1] that I/O timings in EXPLAIN don't show\n>\n> <snip>\n>\n> > >\n> > > I've attached the updated patch that incorporates the above comment.\n> >\n> > The patch looks fine to me.\n> >\n>\n\nThank you for the comments!\n\n> The patch looks good to me too. However I do wonder why the timing is added only on\n> the\n>\n> if (es->format == EXPLAIN_FORMAT_TEXT)\n>\n> block and is not added when, for example, the format is json. The instrumentation has\n> clearly recorded the timings regardless of the output format.\n\nGood point. Fixed.\n\n>\n> Also, it might be worth while to consider adding some regression tests. To my\n> understanding, explain.sql provides a function, explain_filter, which helps create\n> a stable result. For example, such a test case can be:\n>\n> set track_io_timing = 'on';\n> select explain_filter('explain (analyze, buffers) select count(*) from generate_series(1,100000)');\n>\n> then it would be enough to verify that the line:\n>\n> I/O Timings: temp read=N.N write=N.N\n>\n> is present. The above would apply on the json output via `explain_filter_to_json`\n> of course.\n\nAgreed. I've added regression tests.\n\nI've attached an updated patch. Please review it.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/", "msg_date": "Tue, 16 Nov 2021 16:37:44 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Sun, Aug 22, 2021 at 9:47 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Thu, Aug 19, 2021 at 10:52 PM Ranier Vilela <ranier.vf@gmail.com> wrote:\n> >\n> > Em qui., 19 de ago. de 2021 às 09:21, Masahiko Sawada <sawada.mshk@gmail.com> escreveu:\n>\n> > The presentation seems a little confusing, wouldn't it be better?\n> >\n> > I/O Timings: shared/local read=xxxx write=xxx temp read=0.487 write=2.073\n>\n> Yeah, it looks better to add \"shared/local\".\n\n Using the patch, I do feel like the EXPLAIN format of\n\n shared/local xxx, temp xxx\n\n is a bit confusing. If temp is going to be its own EXPLAIN IO timing\n category (as opposed to being summed with relation data block IO from\n local and shared buffers), then it seems like local and shared should\n be separated as well.\n\n shared xxx, local xxx, temp xxx\n\n With your patch applied, below is the top of the EXPLAIN output for a\n query joining a temporary table (so using local buffers) to a regular\n table (using shared buffers) and spilling the hash join (temp files).\n\nAggregate (actual rows=1 loops=1)\n Buffers: shared read=4425, local read=4425 dirtied=4425\nwritten=4423, temp read=5963 written=5963\n I/O Timings: shared/local read=23.546, temp read=13.309 write=74.198\n\n I found that using the same terminology as the \"EXPLAIN BUFFERS\" output\n but not using the same categories was kind of confusing.\n\n If it is only meaningful to distinguish between relation data IO and\n query temp file IO, then maybe the words used in I/O Timings in EXPLAIN\n should be \"rel data\" and \"temp\" or something like that.\n\n- Melanie\n\n\n", "msg_date": "Thu, 18 Nov 2021 17:23:54 -0500", "msg_from": "Melanie Plageman <melanieplageman@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "Hi,\n\nOn Tue, Nov 16, 2021 at 04:37:44PM +0900, Masahiko Sawada wrote:\n> \n> I've attached an updated patch. Please review it.\n\nIt seems that the regression tests aren't entirely stable, per cfbot:\nhttps://cirrus-ci.com/github/postgresql-cfbot/postgresql/commitfest/36/3298.\n\nThe failures look like:\n\ndiff -U3 /tmp/cirrus-ci-build/src/test/recovery/../regress/expected/explain.out /tmp/cirrus-ci-build/src/test/recovery/tmp_check/results/explain.out\n--- /tmp/cirrus-ci-build/src/test/recovery/../regress/expected/explain.out\t2022-01-19 03:50:37.087931908 +0000\n+++ /tmp/cirrus-ci-build/src/test/recovery/tmp_check/results/explain.out\t2022-01-19 03:57:41.013616137 +0000\n@@ -512,9 +512,10 @@\n I/O Timings: temp read=N.N write=N.N\n -> Function Scan on generate_series (cost=N.N..N.N rows=N width=N) (actual time=N.N..N.N rows=N loops=N)\n I/O Timings: temp read=N.N write=N.N\n+ I/O Timings: shared/local read=N.N\n Planning Time: N.N ms\n Execution Time: N.N ms\n-(6 rows)\n+(7 rows)\n\n select explain_filter('explain (analyze, buffers, format json) select count(*) from generate_series(1, 100000)');\n explain_filter\n\n\nI don't see any obvious error in the code, so I'm wondering if it's simply\nthe result of populating the cache with generate_series() info.\n\n\n", "msg_date": "Wed, 19 Jan 2022 16:52:36 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "Hi,\n\nSorry for the late reply.\n\nOn Fri, Nov 19, 2021 at 7:24 AM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n>\n> On Sun, Aug 22, 2021 at 9:47 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > On Thu, Aug 19, 2021 at 10:52 PM Ranier Vilela <ranier.vf@gmail.com> wrote:\n> > >\n> > > Em qui., 19 de ago. de 2021 às 09:21, Masahiko Sawada <sawada.mshk@gmail.com> escreveu:\n> >\n> > > The presentation seems a little confusing, wouldn't it be better?\n> > >\n> > > I/O Timings: shared/local read=xxxx write=xxx temp read=0.487 write=2.073\n> >\n> > Yeah, it looks better to add \"shared/local\".\n>\n> Using the patch, I do feel like the EXPLAIN format of\n>\n> shared/local xxx, temp xxx\n>\n> is a bit confusing. If temp is going to be its own EXPLAIN IO timing\n> category (as opposed to being summed with relation data block IO from\n> local and shared buffers), then it seems like local and shared should\n> be separated as well.\n>\n> shared xxx, local xxx, temp xxx\n\nI think the I/O timing shown as shared/local is the time spent on disk\nI/O so it doesn't matter if these disk I/O are for shared buffers or\nlocal buffers.\n\n>\n> With your patch applied, below is the top of the EXPLAIN output for a\n> query joining a temporary table (so using local buffers) to a regular\n> table (using shared buffers) and spilling the hash join (temp files).\n>\n> Aggregate (actual rows=1 loops=1)\n> Buffers: shared read=4425, local read=4425 dirtied=4425\n> written=4423, temp read=5963 written=5963\n> I/O Timings: shared/local read=23.546, temp read=13.309 write=74.198\n>\n> I found that using the same terminology as the \"EXPLAIN BUFFERS\" output\n> but not using the same categories was kind of confusing.\n>\n> If it is only meaningful to distinguish between relation data IO and\n> query temp file IO, then maybe the words used in I/O Timings in EXPLAIN\n> should be \"rel data\" and \"temp\" or something like that.\n\nBut if we do that, we end up using different terminology in \"I/O\nTiming\" and \"Buffers\". I think it's better to use consistent words\nused in them.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Tue, 1 Mar 2022 09:46:32 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Wed, Jan 19, 2022 at 5:52 PM Julien Rouhaud <rjuju123@gmail.com> wrote:\n>\n> Hi,\n>\n> On Tue, Nov 16, 2021 at 04:37:44PM +0900, Masahiko Sawada wrote:\n> >\n> > I've attached an updated patch. Please review it.\n>\n> It seems that the regression tests aren't entirely stable, per cfbot:\n> https://cirrus-ci.com/github/postgresql-cfbot/postgresql/commitfest/36/3298.\n>\n> The failures look like:\n>\n> diff -U3 /tmp/cirrus-ci-build/src/test/recovery/../regress/expected/explain.out /tmp/cirrus-ci-build/src/test/recovery/tmp_check/results/explain.out\n> --- /tmp/cirrus-ci-build/src/test/recovery/../regress/expected/explain.out 2022-01-19 03:50:37.087931908 +0000\n> +++ /tmp/cirrus-ci-build/src/test/recovery/tmp_check/results/explain.out 2022-01-19 03:57:41.013616137 +0000\n> @@ -512,9 +512,10 @@\n> I/O Timings: temp read=N.N write=N.N\n> -> Function Scan on generate_series (cost=N.N..N.N rows=N width=N) (actual time=N.N..N.N rows=N loops=N)\n> I/O Timings: temp read=N.N write=N.N\n> + I/O Timings: shared/local read=N.N\n> Planning Time: N.N ms\n> Execution Time: N.N ms\n> -(6 rows)\n> +(7 rows)\n>\n> select explain_filter('explain (analyze, buffers, format json) select count(*) from generate_series(1, 100000)');\n> explain_filter\n>\n>\n> I don't see any obvious error in the code, so I'm wondering if it's simply\n> the result of populating the cache with generate_series() info.\n\nThank you for reporting.\n\nYou're right, the regression test with track_io_timing = on is not\nentirely stable because we may read catalog data during planning time,\nresulting in an additional line in the EXPLAIN output. I've removed\nthe regression tests.\n\nI've attached updated patches. I've included an improvement of\npg_stat_statement support to support temp I/O timing.\n\n\nRegards,\n\n--\nMasahiko Sawada\nEDB: https://www.enterprisedb.com/", "msg_date": "Tue, 1 Mar 2022 11:35:32 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "Hi,\n\nOn Tue, Mar 01, 2022 at 11:35:32AM +0900, Masahiko Sawada wrote:\n> On Wed, Jan 19, 2022 at 5:52 PM Julien Rouhaud <rjuju123@gmail.com> wrote:\n> >\n> > It seems that the regression tests aren't entirely stable, per cfbot:\n> > https://cirrus-ci.com/github/postgresql-cfbot/postgresql/commitfest/36/3298.\n> >\n> > The failures look like:\n> >\n> > diff -U3 /tmp/cirrus-ci-build/src/test/recovery/../regress/expected/explain.out /tmp/cirrus-ci-build/src/test/recovery/tmp_check/results/explain.out\n> > --- /tmp/cirrus-ci-build/src/test/recovery/../regress/expected/explain.out 2022-01-19 03:50:37.087931908 +0000\n> > +++ /tmp/cirrus-ci-build/src/test/recovery/tmp_check/results/explain.out 2022-01-19 03:57:41.013616137 +0000\n> > @@ -512,9 +512,10 @@\n> > I/O Timings: temp read=N.N write=N.N\n> > -> Function Scan on generate_series (cost=N.N..N.N rows=N width=N) (actual time=N.N..N.N rows=N loops=N)\n> > I/O Timings: temp read=N.N write=N.N\n> > + I/O Timings: shared/local read=N.N\n> > Planning Time: N.N ms\n> > Execution Time: N.N ms\n> > -(6 rows)\n> > +(7 rows)\n> >\n> > select explain_filter('explain (analyze, buffers, format json) select count(*) from generate_series(1, 100000)');\n> > explain_filter\n> >\n> >\n> > I don't see any obvious error in the code, so I'm wondering if it's simply\n> > the result of populating the cache with generate_series() info.\n> \n> Thank you for reporting.\n> \n> You're right, the regression test with track_io_timing = on is not\n> entirely stable because we may read catalog data during planning time,\n> resulting in an additional line in the EXPLAIN output. I've removed\n> the regression tests.\n\nHmm, but AFAICS the json format would be stable as the counters are always\nshown even if zero. So just doing the json format first and then the text\nformat should also work. Although if you're really unlucky there could be a\ncache invalidation in between so we could just ignore the text format. But I\nthink we should at least keep a regression test with the json format, with a\ncomment explain why only this one is tested.\n\n> I've attached updated patches. I've included an improvement of\n> pg_stat_statement support to support temp I/O timing.\n\nGreat!\n\nSome other considerations:\n\n- should we update pg_stat_statements documentation (and comments) for\n blk_(read|write)_time to mention that it's for *data file* blocks rather than\n simply blocks? It seems obvious now that we'd have\n temp_blk_(read|write)_time, but still. This part should probably be\n backpatched.\n\n- not really your patch fault I guess, but I see that extendBufFile() isn't\n handled. There shouldn't be much activity there so maybe it's ok.\n This is likely because smgr_extend is also not handled, but this one seems\n much more likely to take quite some time, and therefore should bump the\n timing counters.\n\n\n", "msg_date": "Mon, 4 Apr 2022 12:30:20 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Mon, Apr 4, 2022 at 1:30 PM Julien Rouhaud <rjuju123@gmail.com> wrote:\n>\n> Hi,\n>\n> On Tue, Mar 01, 2022 at 11:35:32AM +0900, Masahiko Sawada wrote:\n> > On Wed, Jan 19, 2022 at 5:52 PM Julien Rouhaud <rjuju123@gmail.com> wrote:\n> > >\n> > > It seems that the regression tests aren't entirely stable, per cfbot:\n> > > https://cirrus-ci.com/github/postgresql-cfbot/postgresql/commitfest/36/3298.\n> > >\n> > > The failures look like:\n> > >\n> > > diff -U3 /tmp/cirrus-ci-build/src/test/recovery/../regress/expected/explain.out /tmp/cirrus-ci-build/src/test/recovery/tmp_check/results/explain.out\n> > > --- /tmp/cirrus-ci-build/src/test/recovery/../regress/expected/explain.out 2022-01-19 03:50:37.087931908 +0000\n> > > +++ /tmp/cirrus-ci-build/src/test/recovery/tmp_check/results/explain.out 2022-01-19 03:57:41.013616137 +0000\n> > > @@ -512,9 +512,10 @@\n> > > I/O Timings: temp read=N.N write=N.N\n> > > -> Function Scan on generate_series (cost=N.N..N.N rows=N width=N) (actual time=N.N..N.N rows=N loops=N)\n> > > I/O Timings: temp read=N.N write=N.N\n> > > + I/O Timings: shared/local read=N.N\n> > > Planning Time: N.N ms\n> > > Execution Time: N.N ms\n> > > -(6 rows)\n> > > +(7 rows)\n> > >\n> > > select explain_filter('explain (analyze, buffers, format json) select count(*) from generate_series(1, 100000)');\n> > > explain_filter\n> > >\n> > >\n> > > I don't see any obvious error in the code, so I'm wondering if it's simply\n> > > the result of populating the cache with generate_series() info.\n> >\n> > Thank you for reporting.\n> >\n> > You're right, the regression test with track_io_timing = on is not\n> > entirely stable because we may read catalog data during planning time,\n> > resulting in an additional line in the EXPLAIN output. I've removed\n> > the regression tests.\n>\n> Hmm, but AFAICS the json format would be stable as the counters are always\n> shown even if zero. So just doing the json format first and then the text\n> format should also work. Although if you're really unlucky there could be a\n> cache invalidation in between so we could just ignore the text format. But I\n> think we should at least keep a regression test with the json format, with a\n> comment explain why only this one is tested.\n\nFair point. By commit 7e12256b478 we disabled track_io_timing, but\nprobably we can temporarily enable it and run one query with \"buffers\"\nand \"format json\" options.\n\n>\n> > I've attached updated patches. I've included an improvement of\n> > pg_stat_statement support to support temp I/O timing.\n>\n> Great!\n>\n> Some other considerations:\n>\n> - should we update pg_stat_statements documentation (and comments) for\n> blk_(read|write)_time to mention that it's for *data file* blocks rather than\n> simply blocks? It seems obvious now that we'd have\n> temp_blk_(read|write)_time, but still. This part should probably be\n> backpatched.\n\nAgreed.\n\n>\n> - not really your patch fault I guess, but I see that extendBufFile() isn't\n> handled. There shouldn't be much activity there so maybe it's ok.\n> This is likely because smgr_extend is also not handled, but this one seems\n> much more likely to take quite some time, and therefore should bump the\n> timing counters.\n\nYou mean we should include the time for opening files as write time?\nIIUC smgrextend() writes data while extending file whereas\nextendBufFile() doesn't do that but just opens a new file.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Tue, 5 Apr 2022 00:51:12 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Tue, Apr 05, 2022 at 12:51:12AM +0900, Masahiko Sawada wrote:\n> On Mon, Apr 4, 2022 at 1:30 PM Julien Rouhaud <rjuju123@gmail.com> wrote:\n> >\n> > Hmm, but AFAICS the json format would be stable as the counters are always\n> > shown even if zero. So just doing the json format first and then the text\n> > format should also work. Although if you're really unlucky there could be a\n> > cache invalidation in between so we could just ignore the text format. But I\n> > think we should at least keep a regression test with the json format, with a\n> > comment explain why only this one is tested.\n> \n> Fair point. By commit 7e12256b478 we disabled track_io_timing, but\n> probably we can temporarily enable it and run one query with \"buffers\"\n> and \"format json\" options.\n\nYes, enabling it for just this query. It can't really find any problem with\nthe values themselves but at least the new code path would be partially\nexecuted.\n\n> >\n> > - not really your patch fault I guess, but I see that extendBufFile() isn't\n> > handled. There shouldn't be much activity there so maybe it's ok.\n> > This is likely because smgr_extend is also not handled, but this one seems\n> > much more likely to take quite some time, and therefore should bump the\n> > timing counters.\n> \n> You mean we should include the time for opening files as write time?\n\nYes. In normal circumstances it shouldn't need a lot of time to do that, but\nI'm not so sure with e.g. network filesystems. I'm not strongly in favor of\ncounting it, especially since smgrextend doesn't either.\n\n> IIUC smgrextend() writes data while extending file whereas\n> extendBufFile() doesn't do that but just opens a new file.\n\nNote that smgrextend can also call register_dirty_segment(), which can also\ntake some time, so we can't just assume that all the time there is IO time.\n\n\n", "msg_date": "Tue, 5 Apr 2022 00:31:38 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Tue, Apr 5, 2022 at 1:31 AM Julien Rouhaud <rjuju123@gmail.com> wrote:\n>\n> On Tue, Apr 05, 2022 at 12:51:12AM +0900, Masahiko Sawada wrote:\n> > On Mon, Apr 4, 2022 at 1:30 PM Julien Rouhaud <rjuju123@gmail.com> wrote:\n> > >\n> > > Hmm, but AFAICS the json format would be stable as the counters are always\n> > > shown even if zero. So just doing the json format first and then the text\n> > > format should also work. Although if you're really unlucky there could be a\n> > > cache invalidation in between so we could just ignore the text format. But I\n> > > think we should at least keep a regression test with the json format, with a\n> > > comment explain why only this one is tested.\n> >\n> > Fair point. By commit 7e12256b478 we disabled track_io_timing, but\n> > probably we can temporarily enable it and run one query with \"buffers\"\n> > and \"format json\" options.\n>\n> Yes, enabling it for just this query. It can't really find any problem with\n> the values themselves but at least the new code path would be partially\n> executed.\n>\n> > >\n> > > - not really your patch fault I guess, but I see that extendBufFile() isn't\n> > > handled. There shouldn't be much activity there so maybe it's ok.\n> > > This is likely because smgr_extend is also not handled, but this one seems\n> > > much more likely to take quite some time, and therefore should bump the\n> > > timing counters.\n> >\n> > You mean we should include the time for opening files as write time?\n>\n> Yes. In normal circumstances it shouldn't need a lot of time to do that, but\n> I'm not so sure with e.g. network filesystems. I'm not strongly in favor of\n> counting it, especially since smgrextend doesn't either.\n\nGood point. I think that adding a new place to track I/O timing can be\na separate patch so probably we can work on it for PG16 or later.\n\nI've attached updated patches, please review it.\n\nRegards,\n\n--\nMasahiko Sawada\nEDB: https://www.enterprisedb.com/", "msg_date": "Tue, 5 Apr 2022 10:40:04 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Tue, Apr 05, 2022 at 10:40:04AM +0900, Masahiko Sawada wrote:\n> On Tue, Apr 5, 2022 at 1:31 AM Julien Rouhaud <rjuju123@gmail.com> wrote:\n> >\n> > Yes. In normal circumstances it shouldn't need a lot of time to do that, but\n> > I'm not so sure with e.g. network filesystems. I'm not strongly in favor of\n> > counting it, especially since smgrextend doesn't either.\n> \n> Good point. I think that adding a new place to track I/O timing can be\n> a separate patch so probably we can work on it for PG16 or later.\n\nAgreed.\n\n> I've attached updated patches, please review it.\n\nIt looks good to me, just one minor thing in 002:\n\n@@ -183,8 +184,10 @@ typedef struct Counters\n \tint64\t\tlocal_blks_written; /* # of local disk blocks written */\n \tint64\t\ttemp_blks_read; /* # of temp blocks read */\n \tint64\t\ttemp_blks_written;\t/* # of temp blocks written */\n-\tdouble\t\tblk_read_time;\t/* time spent reading, in msec */\n-\tdouble\t\tblk_write_time; /* time spent writing, in msec */\n+\tdouble\t\tblk_read_time;\t/* time spent reading blocks, in msec */\n+\tdouble\t\tblk_write_time; /* time spent writing blocks, in msec */\n+\tdouble\t\ttemp_blk_read_time;\t/* time spent reading temp blocks, in msec */\n+\tdouble\t\ttemp_blk_write_time; /* time spent writing temp blocks, in msec */\n\nmaybe the comments should respectively be data file blocks and temp file\nblocks.\n\nThis is a minor detail and the rest of the patch looks good to me, so I'm\nmarking the patch as Ready for Committer!\n\n\n", "msg_date": "Tue, 5 Apr 2022 11:57:14 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Tue, Apr 05, 2022 at 11:57:14AM +0800, Julien Rouhaud wrote:\n> This is a minor detail and the rest of the patch looks good to me, so I'm\n> marking the patch as Ready for Committer!\n\n@@ -440,10 +442,14 @@ BufFileLoadBuffer(BufFile *file)\n+ if (track_io_timing)\n+ INSTR_TIME_SET_CURRENT(io_start);\n\nIn places where we don't have clock_gettime(), this means using\ngettimeofday(). I would not underestimate the performance impact of\nsuch a change, even if track_io_timing is already known to have a\ncertain overhead on some platforms.\n--\nMichael", "msg_date": "Thu, 7 Apr 2022 15:58:46 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Thu, Apr 07, 2022 at 03:58:46PM +0900, Michael Paquier wrote:\n> On Tue, Apr 05, 2022 at 11:57:14AM +0800, Julien Rouhaud wrote:\n> > This is a minor detail and the rest of the patch looks good to me, so I'm\n> > marking the patch as Ready for Committer!\n> \n> @@ -440,10 +442,14 @@ BufFileLoadBuffer(BufFile *file)\n> + if (track_io_timing)\n> + INSTR_TIME_SET_CURRENT(io_start);\n> \n> In places where we don't have clock_gettime(), this means using\n> gettimeofday(). I would not underestimate the performance impact of\n> such a change, even if track_io_timing is already known to have a\n> certain overhead on some platforms.\n\nSure, but gettimeofday() has been implemented in vDSO for quite some time on\nmost platforms, so it shouldn't hurt that much on mainstream platforms\nespecially compared to the cost of whatever operation is actually using that\ntemporary file.\n\nI don't think that having an extra GUC for temp IO is sensible, if that's why\nyou're suggesting? Or are you just asking to do some benchmarking on some\nplatform where getting the time is known to be slow (Windows?).\n\n\n", "msg_date": "Thu, 7 Apr 2022 15:14:01 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Thu, Apr 07, 2022 at 03:14:01PM +0800, Julien Rouhaud wrote:\n> Sure, but gettimeofday() has been implemented in vDSO for quite some time on\n> most platforms, so it shouldn't hurt that much on mainstream platforms\n> especially compared to the cost of whatever operation is actually using that\n> temporary file.\n> \n> I don't think that having an extra GUC for temp IO is sensible, if that's why\n> you're suggesting? Or are you just asking to do some benchmarking on some\n> platform where getting the time is known to be slow (Windows?).\n\nI am asking about the latter, but the former could be one solution if\nthe latter proves to be a problem, and this has not been discussed on\nthe thread yet. So, with some kind of worst-case scenario, how much\nworse the performance gets once you add those extra calls when\ncompared to HEAD? I think that we'd better be careful with any\nadditions of INSTR_TIME_SET_CURRENT().\n--\nMichael", "msg_date": "Thu, 7 Apr 2022 16:24:54 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Thu, Apr 07, 2022 at 04:24:54PM +0900, Michael Paquier wrote:\n> On Thu, Apr 07, 2022 at 03:14:01PM +0800, Julien Rouhaud wrote:\n> > Sure, but gettimeofday() has been implemented in vDSO for quite some time on\n> > most platforms, so it shouldn't hurt that much on mainstream platforms\n> > especially compared to the cost of whatever operation is actually using that\n> > temporary file.\n> > \n> > I don't think that having an extra GUC for temp IO is sensible, if that's why\n> > you're suggesting? Or are you just asking to do some benchmarking on some\n> > platform where getting the time is known to be slow (Windows?).\n> \n> I am asking about the latter, but the former could be one solution if\n> the latter proves to be a problem, and this has not been discussed on\n> the thread yet. So, with some kind of worst-case scenario, how much\n> worse the performance gets once you add those extra calls when\n> compared to HEAD? I think that we'd better be careful with any\n> additions of INSTR_TIME_SET_CURRENT().\n\nI just did a quick test on my linux box, using this data:\nCREATE TABLE tt AS select generate_series(1, 10000) id;\nVACUUM ANALYZE tt;\n\nand this scenario:\nSET work_mem TO '64kB';\nSELECT count(*) FROM (SELECT id FROM tt ORDER BY id) s;\n\nwhich yields this plan:\n\n QUERY PLAN\n------------------------------------------------------------------------------------------------------------------\n Aggregate (cost=1349.39..1349.40 rows=1 width=8) (actual time=5.417..5.417 rows=1 loops=1)\n -> Sort (cost=1199.39..1224.39 rows=10000 width=4) (actual time=2.910..4.422 rows=10000 loops=1)\n Sort Key: tt.id\n Sort Method: external merge Disk: 144kB\n -> Seq Scan on tt (cost=0.00..145.00 rows=10000 width=4) (actual time=0.008..1.239 rows=10000 loops=1)\n Planning Time: 0.405 ms\n Execution Time: 5.524 ms\n\nSo maybe not the worst that could be tested, but probably bad enough for this\npatch.\n\nI ran that with pgbench, 4 clients (I have 4 cores) for 30 seconds, 3 times.\n\nComparing master and this patch with track_io_timing activated, I see a 0.95%\noverhead, with a 2.6% noise level.\n\n\n", "msg_date": "Thu, 7 Apr 2022 15:55:45 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Thu, Apr 7, 2022 at 4:55 PM Julien Rouhaud <rjuju123@gmail.com> wrote:\n>\n> On Thu, Apr 07, 2022 at 04:24:54PM +0900, Michael Paquier wrote:\n> > On Thu, Apr 07, 2022 at 03:14:01PM +0800, Julien Rouhaud wrote:\n> > > Sure, but gettimeofday() has been implemented in vDSO for quite some time on\n> > > most platforms, so it shouldn't hurt that much on mainstream platforms\n> > > especially compared to the cost of whatever operation is actually using that\n> > > temporary file.\n> > >\n> > > I don't think that having an extra GUC for temp IO is sensible, if that's why\n> > > you're suggesting? Or are you just asking to do some benchmarking on some\n> > > platform where getting the time is known to be slow (Windows?).\n> >\n> > I am asking about the latter, but the former could be one solution if\n> > the latter proves to be a problem, and this has not been discussed on\n> > the thread yet. So, with some kind of worst-case scenario, how much\n> > worse the performance gets once you add those extra calls when\n> > compared to HEAD? I think that we'd better be careful with any\n> > additions of INSTR_TIME_SET_CURRENT().\n>\n> I just did a quick test on my linux box, using this data:\n> CREATE TABLE tt AS select generate_series(1, 10000) id;\n> VACUUM ANALYZE tt;\n>\n> and this scenario:\n> SET work_mem TO '64kB';\n> SELECT count(*) FROM (SELECT id FROM tt ORDER BY id) s;\n>\n> which yields this plan:\n>\n> QUERY PLAN\n> ------------------------------------------------------------------------------------------------------------------\n> Aggregate (cost=1349.39..1349.40 rows=1 width=8) (actual time=5.417..5.417 rows=1 loops=1)\n> -> Sort (cost=1199.39..1224.39 rows=10000 width=4) (actual time=2.910..4.422 rows=10000 loops=1)\n> Sort Key: tt.id\n> Sort Method: external merge Disk: 144kB\n> -> Seq Scan on tt (cost=0.00..145.00 rows=10000 width=4) (actual time=0.008..1.239 rows=10000 loops=1)\n> Planning Time: 0.405 ms\n> Execution Time: 5.524 ms\n>\n> So maybe not the worst that could be tested, but probably bad enough for this\n> patch.\n>\n> I ran that with pgbench, 4 clients (I have 4 cores) for 30 seconds, 3 times.\n>\n> Comparing master and this patch with track_io_timing activated, I see a 0.95%\n> overhead, with a 2.6% noise level.\n\nI've done the same test with a larger data set (10M tuples) on my\nmachine (MacOS):\n\nHEAD: 5418.869 ms\nPatched: 5367.234 ms\n\nI can see about 1% overhead.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Thu, 7 Apr 2022 17:52:19 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Thu, Apr 7, 2022 at 5:52 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Thu, Apr 7, 2022 at 4:55 PM Julien Rouhaud <rjuju123@gmail.com> wrote:\n> >\n> > On Thu, Apr 07, 2022 at 04:24:54PM +0900, Michael Paquier wrote:\n> > > On Thu, Apr 07, 2022 at 03:14:01PM +0800, Julien Rouhaud wrote:\n> > > > Sure, but gettimeofday() has been implemented in vDSO for quite some time on\n> > > > most platforms, so it shouldn't hurt that much on mainstream platforms\n> > > > especially compared to the cost of whatever operation is actually using that\n> > > > temporary file.\n> > > >\n> > > > I don't think that having an extra GUC for temp IO is sensible, if that's why\n> > > > you're suggesting? Or are you just asking to do some benchmarking on some\n> > > > platform where getting the time is known to be slow (Windows?).\n> > >\n> > > I am asking about the latter, but the former could be one solution if\n> > > the latter proves to be a problem, and this has not been discussed on\n> > > the thread yet. So, with some kind of worst-case scenario, how much\n> > > worse the performance gets once you add those extra calls when\n> > > compared to HEAD? I think that we'd better be careful with any\n> > > additions of INSTR_TIME_SET_CURRENT().\n> >\n> > I just did a quick test on my linux box, using this data:\n> > CREATE TABLE tt AS select generate_series(1, 10000) id;\n> > VACUUM ANALYZE tt;\n> >\n> > and this scenario:\n> > SET work_mem TO '64kB';\n> > SELECT count(*) FROM (SELECT id FROM tt ORDER BY id) s;\n> >\n> > which yields this plan:\n> >\n> > QUERY PLAN\n> > ------------------------------------------------------------------------------------------------------------------\n> > Aggregate (cost=1349.39..1349.40 rows=1 width=8) (actual time=5.417..5.417 rows=1 loops=1)\n> > -> Sort (cost=1199.39..1224.39 rows=10000 width=4) (actual time=2.910..4.422 rows=10000 loops=1)\n> > Sort Key: tt.id\n> > Sort Method: external merge Disk: 144kB\n> > -> Seq Scan on tt (cost=0.00..145.00 rows=10000 width=4) (actual time=0.008..1.239 rows=10000 loops=1)\n> > Planning Time: 0.405 ms\n> > Execution Time: 5.524 ms\n> >\n> > So maybe not the worst that could be tested, but probably bad enough for this\n> > patch.\n> >\n> > I ran that with pgbench, 4 clients (I have 4 cores) for 30 seconds, 3 times.\n> >\n> > Comparing master and this patch with track_io_timing activated, I see a 0.95%\n> > overhead, with a 2.6% noise level.\n>\n> I've done the same test with a larger data set (10M tuples) on my\n> machine (MacOS):\n>\n> HEAD: 5418.869 ms\n> Patched: 5367.234 ms\n\nOops, the results are opposite:\n\nHEAD: 5367.234 ms\nPatched: 5418.869 ms\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Thu, 7 Apr 2022 21:48:02 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Thu, Apr 07, 2022 at 09:48:02PM +0900, Masahiko Sawada wrote:\n> Oops, the results are opposite:\n> \n> HEAD: 5367.234 ms\n> Patched: 5418.869 ms\n\nI have been playing with external sorts & friends after running an\ninstance on scissors (fsync=off, PGDATA on tmpfs, etc.), even forcing\na compilation of the code with gettimeofday(), and I can see a\ntendency of a ~1% impact with the patch in this configuration. So\nthere is a tendency, while this is also rather close to the usual\nnoise range. Anyway, this is going to be helpful for debugging when\ntemp file I/O is a bottleneck, so.. Applied 0001 with some tweaks to\nthe docs and some indentation fixes.\n\nNow, 0002 is straight-forward but I need more coffee and lunch..\n--\nMichael", "msg_date": "Fri, 8 Apr 2022 11:34:17 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Fri, Apr 08, 2022 at 11:34:17AM +0900, Michael Paquier wrote:\n> Now, 0002 is straight-forward but I need more coffee and lunch..\n\nDone this one as well, as of 76cbf7e with few tweaks. 1.9 and 1.10\nchanged the definition of pg_stat_statements, so I have added two\nextra queries for those upgrade paths in oldextversions.sql.\n--\nMichael", "msg_date": "Fri, 8 Apr 2022 13:37:38 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" }, { "msg_contents": "On Fri, Apr 8, 2022 at 1:37 PM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> On Fri, Apr 08, 2022 at 11:34:17AM +0900, Michael Paquier wrote:\n> > Now, 0002 is straight-forward but I need more coffee and lunch..\n>\n> Done this one as well, as of 76cbf7e with few tweaks. 1.9 and 1.10\n> changed the definition of pg_stat_statements, so I have added two\n> extra queries for those upgrade paths in oldextversions.sql.\n\nThank you for committing both patches. Agreed with these changes.\n\nRegards,\n\n-- \nMasahiko Sawada\nEDB: https://www.enterprisedb.com/\n\n\n", "msg_date": "Fri, 8 Apr 2022 14:19:39 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Showing I/O timings spent reading/writing temp buffers in EXPLAIN" } ]
[ { "msg_contents": "A customer recently hit this error message:\n\nERROR: t_xmin is uncommitted in tuple to be updated\n\nThis was not very informative, so without any clues, we had to let it\ngo. But it did occur to me that we can improve this message so that we\nknow details such as the TID and the relation that caused the issue, so\nthat if it ever occurs again we can at least look at the WAL stream for\nanything affecting the tuple, maybe it'd help to understand the problem.\n\nSo I propose the following patch.\n\n-- \nÁlvaro Herrera", "msg_date": "Thu, 19 Aug 2021 12:37:58 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": true, "msg_subject": "reporting TID/table with corruption error" }, { "msg_contents": "On Thu, Aug 19, 2021 at 9:38 AM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> A customer recently hit this error message:\n>\n> ERROR: t_xmin is uncommitted in tuple to be updated\n>\n> This was not very informative, so without any clues, we had to let it\n> go. But it did occur to me that we can improve this message so that we\n> know details such as the TID and the relation that caused the issue, so\n> that if it ever occurs again we can at least look at the WAL stream for\n> anything affecting the tuple, maybe it'd help to understand the problem.\n\nI think that this is a very good idea. Ideally this stuff would be\nmore standardized.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Thu, 19 Aug 2021 09:44:09 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: reporting TID/table with corruption error" }, { "msg_contents": "\n\n> 19 авг. 2021 г., в 21:44, Peter Geoghegan <pg@bowt.ie> написал(а):\n> \n> I think that this is a very good idea. Ideally this stuff would be\n> more standardized.\n\n+1\nIt would be great to see relation, block, offset, xmin\\xmax and, probably, flags whenever ERRCODE_DATA_CORRUPTED\\ERRCODE_INDEX_CORRUPTED is used. Iif it's possible to extract this information, of cause. This is needed especially in amcheck functions.\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Thu, 19 Aug 2021 22:17:41 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: reporting TID/table with corruption error" }, { "msg_contents": "\n\n> 19 авг. 2021 г., в 21:37, Alvaro Herrera <alvherre@alvh.no-ip.org> написал(а):\n> \n> A customer recently hit this error message:\n> \n> ERROR: t_xmin is uncommitted in tuple to be updated\n\nSorry for one more message, it occurred to me only after sending previous one that I know this exact message.\n\nWe encountered this error twice:\n1. When dealing with broken WAL-delta backups in WAL-G (a kind of fast incremental backup, the bug was fixed back in 2019) The page simply was of an old version.\n2. As a result of broken page cache in patched linux kernel (clog was fsynced succesfully, but the page fsync was lost before restart)\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Thu, 19 Aug 2021 22:28:40 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: reporting TID/table with corruption error" }, { "msg_contents": "Peter Geoghegan <pg@bowt.ie> writes:\n\n> On Thu, Aug 19, 2021 at 9:38 AM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>> A customer recently hit this error message:\n>>\n>> ERROR: t_xmin is uncommitted in tuple to be updated\n>>\n>> This was not very informative, so without any clues, we had to let it\n>> go. But it did occur to me that we can improve this message so that we\n>> know details such as the TID and the relation that caused the issue, so\n>> that if it ever occurs again we can at least look at the WAL stream for\n>> anything affecting the tuple, maybe it'd help to understand the problem.\n>\n> I think that this is a very good idea. Ideally this stuff would be\n> more standardized.\n\nThere are various functions for adding auxilliary fields to the error\nreport, e.g. errtable() for the schema and table names, but that only\nseems to be reported to the client, not logged on the server.\n\nShould we be logging auxiliary error fields? If not by default, maybe\nby a higher log_error_verbosity level (possibly a new one between\ndefault and verbose).\n\n- ilmari\n\n\n", "msg_date": "Thu, 19 Aug 2021 18:36:15 +0100", "msg_from": "=?utf-8?Q?Dagfinn_Ilmari_Manns=C3=A5ker?= <ilmari@ilmari.org>", "msg_from_op": false, "msg_subject": "Re: reporting TID/table with corruption error" }, { "msg_contents": "\n\n> On Aug 19, 2021, at 10:17 AM, Andrey Borodin <x4mmm@yandex-team.ru> wrote:\n> \n> It would be great to see relation, block, offset, xmin\\xmax and, probably, flags whenever ERRCODE_DATA_CORRUPTED\\ERRCODE_INDEX_CORRUPTED is used. Iif it's possible to extract this information, of cause. This is needed especially in amcheck functions.\n\nblockno, offnum and attnum are already included in every result for amcheck functions over heap relations, though attnum may be null if the corruption is not specific to any particular column.\n\nxmin, xmax and various flags may occur in the corruption message if they are relevant, but they are not always present.\n\nThere was some disagreement during the development of verify_heapam on this point. We went with the idea that the user could find and inspect the corrupt data with another tool if they had the (blockno, offnum, attnum) information. As such, it wasn't necessary to include all the data in the output.\n\nIt shouldn't be too complicated to have a second interface that returns all of the 23 byte main table tuple header information and also the 23 byte toast tuple header (when relevant) along with the corruption message. The guts of the corruption check would be shared between the two interfaces. I haven't tried writing a patch yet, but it seems the patch shouldn't be terribly complicated.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Thu, 19 Aug 2021 10:49:09 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: reporting TID/table with corruption error" }, { "msg_contents": "On Thu, Aug 19, 2021 at 10:49 AM Mark Dilger\n<mark.dilger@enterprisedb.com> wrote:\n> There was some disagreement during the development of verify_heapam on this point. We went with the idea that the user could find and inspect the corrupt data with another tool if they had the (blockno, offnum, attnum) information. As such, it wasn't necessary to include all the data in the output.\n\nI find that kind of dubious. By definition you're never supposed to\nsee any verify_heapam errors. If you do end up seeing one, it\nshould be exceptional -- something that you'll learn from. High\nverbosity makes a lot of sense here.\n\n\n--\nPeter Geoghegan\n\n\n", "msg_date": "Thu, 19 Aug 2021 10:57:58 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: reporting TID/table with corruption error" }, { "msg_contents": "\n\n> On Aug 19, 2021, at 10:57 AM, Peter Geoghegan <pg@bowt.ie> wrote:\n> \n> High\n> verbosity makes a lot of sense here.\n\nWorks for me. We could create another function, \"verify_heapam_full\" perhaps, that returns additional columns matching those from pageinspect's heap_page_items():\n\n OUT lp smallint,\n OUT lp_off smallint,\n OUT lp_flags smallint,\n OUT lp_len smallint,\n OUT t_xmin xid,\n OUT t_xmax xid,\n OUT t_field3 int4,\n OUT t_ctid tid,\n OUT t_infomask2 integer,\n OUT t_infomask integer,\n OUT t_hoff smallint,\n OUT t_bits text,\n OUT t_oid oid,\n OUT t_data bytea\n\nShould it also return the full page? That would be quite verbose (an extra 8k per row), but it could be fed into any of pageinspect's functions for further analysis.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Thu, 19 Aug 2021 11:19:36 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: reporting TID/table with corruption error" }, { "msg_contents": "\n\n> 19 авг. 2021 г., в 23:19, Mark Dilger <mark.dilger@enterprisedb.com> написал(а):\n> \n> \n> \n>> On Aug 19, 2021, at 10:57 AM, Peter Geoghegan <pg@bowt.ie> wrote:\n>> \n>> High\n>> verbosity makes a lot of sense here.\n> \n> Works for me. We could create another function, \"verify_heapam_full\" perhaps, that returns additional columns matching those from pageinspect's heap_page_items():\n\nCurrently I'm mostly interested in index functions to investigate CIC bug.\nI see 4 different cases for corruption checks:\n1. Developer tackling a bug\n2. Backup smoke test\n3. DBA recovering corrupted data\n4. Running system detects anomaly\n\nIn case 1 you want to find corruption and trace back events that lead to it. You need all the bits that can connect current state with events in the past.\n\nIn case 2 you want succinct check, that in case of fire provides initial information for case 3. Ideally you want a check that is symbiosis of \"all indexed\" check and heap check. Meanwhile, it's preferred that you can share heap scan between many index checks.\n\nIn case 3 you want to collect all corrupted data (find everything with same xmin\\xmax, or on the same page, or with near xmin\\xmax). In this case returning heap page right away would be quite useful.\nSometimes you want to create backup copy of the page to try some surgery. (create table backup_pages as select from verify_heapam_full())\n\nIn case 4 you want to alarm DBA and provide all the necessary information to start 3. Adding standardised corruption info to all ERRCODE_DATA_CORRUPTED\\ERRCODE_INDEX_CORRUPTED would suffice. Also, when monitoring wakes you at night you want to know:\n- How many tuples are corrupted?\n- How long ago data was corrupted? Is corrupted data within PITR window yet?\n- Where to seek a manual for recovery?\nBut I don't think we can have this logged in case of \"ERROR: t_xmin is uncommitted in tuple to be updated\"\n\nThanks!\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Fri, 20 Aug 2021 10:45:44 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: reporting TID/table with corruption error" }, { "msg_contents": "Pushed to all branches, thanks.\n\n-- \nÁlvaro Herrera Valdivia, Chile — https://www.EnterpriseDB.com/\n\n\n", "msg_date": "Mon, 30 Aug 2021 16:31:51 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": true, "msg_subject": "Re: reporting TID/table with corruption error" }, { "msg_contents": "\n\n> 19 авг. 2021 г., в 21:37, Alvaro Herrera <alvherre@alvh.no-ip.org> написал(а):\n> \n> A customer recently hit this error message:\n> \n> ERROR: t_xmin is uncommitted in tuple to be updated\n\nHi!\n\nCurrently I'm observing this on one of our production clusters. The problem occurs at random points in time, seems to be covered by retries on client's side and so far did not inflict any harm (except woken engineers).\n\nFew facts:\n0. PostgreSQL 12.9 (with some unrelated patches)\n1. amcheck\\heapcheck\\pg_visibility never suspected the cluster and remain silent\n2. I observe the problem ~once a day\n3. The tuple seems to be updated in a high-contention concurrency trigger function, autovacuum keeks in ~20-30 seconds after the message in logs\n\n[ 2022-01-10 09:07:17.671 MSK [unknown],????,????_????s,310759,XX001 ]:ERROR: t_xmin 696079792 is uncommitted in tuple (1419011,109) to be updated in table \"????s_statistics\"\n[ 2022-01-10 09:07:17.671 MSK [unknown],????,????_????s,310759,XX001 ]:CONTEXT: SQL statement \"UPDATE ????_????s.????s_statistics os\n SET ????_????_found_ts = COALESCE(os.????_????_found_ts, NOW()),\n last_????_found_ts = NOW(),\n num_????s = os.num_????s + 1\n WHERE ????_id = NEW.????_id\"\n PL/pgSQL function statistics__update_from_new_????() line 3 at SQL statement\n[ 2022-01-10 09:07:17.671 MSK [unknown],????,????_????s,310759,XX001 ]:STATEMENT: \n INSERT INTO ????_????s.????s_????s AS ????s \n\n4. t_xmin is relatevely new, not ancient\n5. pageinspect shows dead tuple after some time\n6. no suspicious activity in logs nearby\n7. vacuum (disable_page_skipping) and repack of indexes did not change anything\n\n\nI suspect this can be relatively new concurrency stuff. At least I never saw this before on clusters with clean amcheck and heapcheck results.\n\nAlvaro, did you observe this on binaries from August 13 minor release or older?\n\nThanks!\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Mon, 10 Jan 2022 14:10:47 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: reporting TID/table with corruption error" }, { "msg_contents": "On 2022-Jan-10, Andrey Borodin wrote:\n\n> 3. The tuple seems to be updated in a high-contention concurrency\n> trigger function, autovacuum keeks in ~20-30 seconds after the message\n> in logs\n\nHmm, I bet this is related.\n\n> [ 2022-01-10 09:07:17.671 MSK [unknown],????,????_????s,310759,XX001 ]:ERROR: t_xmin 696079792 is uncommitted in tuple (1419011,109) to be updated in table \"????s_statistics\"\n> [ 2022-01-10 09:07:17.671 MSK [unknown],????,????_????s,310759,XX001 ]:CONTEXT: SQL statement \"UPDATE ????_????s.????s_statistics os\n> SET ????_????_found_ts = COALESCE(os.????_????_found_ts, NOW()),\n> last_????_found_ts = NOW(),\n> num_????s = os.num_????s + 1\n> WHERE ????_id = NEW.????_id\"\n> PL/pgSQL function statistics__update_from_new_????() line 3 at SQL statement\n> [ 2022-01-10 09:07:17.671 MSK [unknown],????,????_????s,310759,XX001 ]:STATEMENT: \n> INSERT INTO ????_????s.????s_????s AS ????s \n> \n> 4. t_xmin is relatevely new, not ancient\n> 5. pageinspect shows dead tuple after some time\n> 6. no suspicious activity in logs nearby\n> 7. vacuum (disable_page_skipping) and repack of indexes did not change anything\n> \n> \n> I suspect this can be relatively new concurrency stuff. At least I never saw this before on clusters with clean amcheck and heapcheck results.\n\nAh. I've been thinking that it'd be some very old tuple that is in\ntrouble, but that seems to be proven false. I think we should examine\nthe affected tuples more closely while they're in the state that causes\nthe problem. Can you set up things so that pageinspect's\nheap_page_items() is run on the broken page, before the problem\ndisappears? Maybe extract the page number from the log line, have\nget_raw_page() store the page in a separate table, so that we can run\nheap_page_items() at leisure later. I would also grep through\npg_waldump output to see what changes have been done to that tuple.\n\nMaybe the reason the problem fixes itself is that something else deletes\nthe tuple.\n\n> Alvaro, did you observe this on binaries from August 13 minor release or older?\n\nWell, the only reports I have of this problem are with the original\nerror message that didn't give any clues at to what the problem was or\nwhere to look for it, so I don't know if the xmin was recent or not.\n\n-- \nÁlvaro Herrera 39°49'30\"S 73°17'W — https://www.EnterpriseDB.com/\n\n\n", "msg_date": "Mon, 10 Jan 2022 11:52:35 -0300", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": true, "msg_subject": "Re: reporting TID/table with corruption error" } ]
[ { "msg_contents": "-hackers,\n\nEnclosed, find a POC patch that implements \"special values\" for int GUCs. We have quite a few GUCs\nwith values that have special meaning atop other settings. I have attempted to identify these and\nmake it so you can specify a symbol name for these values instead of just relying on the magic\nnumber instead.\n\nFor instance, many GUCs have -1 for \"disabled\", so I've just made it so you can\nspecify something like:\n\n SET log_min_duration_statement = disabled;\n\nAnd the raw value will be set to -1 in this case. For the purposes of testing, I have also added a\nnew GUC \"output_special_values\" to affect whether `SHOW` or anything that relies on _ShowOption()\ncan show with the special value instead of just the raw magic value, allowing tools to consume the\noriginal raw value, or provide the output to the user in the nicer format.\n\nThis has only been done for ints, and the passthru I did was very quick, so I have probably missed\nsome options that didn't explicitly have their interpretations in the file and/or I didn't know\nabout it already. I do not think there are these sorts of values in other non-int GUCs, but there\nmight be, so a similar approach could be taken to expand things to other config types in the future.\n\nLet me know your thoughts; I personally find this to be useful, and would be a nicer way for some\nconfigs to be displayed in the postgresql.conf file.\n\nBest,\n\nDavid\n\n\n\n\n--", "msg_date": "Thu, 19 Aug 2021 17:09:25 -0500", "msg_from": "David Christensen <david.christensen@crunchydata.com>", "msg_from_op": true, "msg_subject": "[PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "On 8/20/21 12:09 AM, David Christensen wrote:\n> -hackers,\n> \n> Enclosed, find a POC patch that implements \"special values\" for int GUCs. We have quite a few GUCs\n> with values that have special meaning atop other settings. I have attempted to identify these and\n> make it so you can specify a symbol name for these values instead of just relying on the magic\n> number instead.\n> \n> For instance, many GUCs have -1 for \"disabled\", so I've just made it so you can\n> specify something like:\n> \n> SET log_min_duration_statement = disabled;\n> \n> And the raw value will be set to -1 in this case. For the purposes of testing, I have also added a\n> new GUC \"output_special_values\" to affect whether `SHOW` or anything that relies on _ShowOption()\n> can show with the special value instead of just the raw magic value, allowing tools to consume the\n> original raw value, or provide the output to the user in the nicer format.\n> \n> This has only been done for ints, and the passthru I did was very quick, so I have probably missed\n> some options that didn't explicitly have their interpretations in the file and/or I didn't know\n> about it already. I do not think there are these sorts of values in other non-int GUCs, but there\n> might be, so a similar approach could be taken to expand things to other config types in the future.\n> \n> Let me know your thoughts; I personally find this to be useful, and would be a nicer way for some\n> configs to be displayed in the postgresql.conf file.\n\nAs discussed on IRC, I am in favor of this improvement. (I have not yet\nlooked at the patch.)\n-- \nVik Fearing\n\n\n", "msg_date": "Fri, 20 Aug 2021 00:30:31 +0200", "msg_from": "Vik Fearing <vik@postgresfriends.org>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "> Hi,\n> For parse_special_int():\n>\n> + * true. If it's not found, return false and retval is set to 0.\n> ...\n> + /* don't touch the return value in other case */\n> + return false;\n>\n> It seems the two comments are not consistent with each other (retval is not set in case no entry is found).\n>\n> For special_int_to_value():\n>\n> + * true. If it's not found, return false and retval is set to 0.\n>\n> First, there is no assignment to retval at the end of the method. Second, retval points to string, so it shouldn't be set to 0.\n>\n> Cheers\n\nThanks, I actually noticed on a re-read that the comments didn't\nmatch, but they'll be fixed in the next version. (Will wait to collect\nadditional feedback.)\n\nFunctionality-wise, any thoughts on the overall approach or the specific patch?\n\nThanks,\n\nDavid\n\n\n", "msg_date": "Thu, 19 Aug 2021 17:43:55 -0500", "msg_from": "David Christensen <david.christensen@crunchydata.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "On Thu, Aug 19, 2021 at 3:17 PM David Christensen <\ndavid.christensen@crunchydata.com> wrote:\n\n> -hackers,\n>\n> Enclosed, find a POC patch that implements \"special values\" for int GUCs.\n> We have quite a few GUCs\n> with values that have special meaning atop other settings. I have\n> attempted to identify these and\n> make it so you can specify a symbol name for these values instead of just\n> relying on the magic\n> number instead.\n>\n> For instance, many GUCs have -1 for \"disabled\", so I've just made it so\n> you can\n> specify something like:\n>\n> SET log_min_duration_statement = disabled;\n>\n> And the raw value will be set to -1 in this case. For the purposes of\n> testing, I have also added a\n> new GUC \"output_special_values\" to affect whether `SHOW` or anything that\n> relies on _ShowOption()\n> can show with the special value instead of just the raw magic value,\n> allowing tools to consume the\n> original raw value, or provide the output to the user in the nicer format.\n>\n> This has only been done for ints, and the passthru I did was very quick,\n> so I have probably missed\n> some options that didn't explicitly have their interpretations in the file\n> and/or I didn't know\n> about it already. I do not think there are these sorts of values in other\n> non-int GUCs, but there\n> might be, so a similar approach could be taken to expand things to other\n> config types in the future.\n>\n> Let me know your thoughts; I personally find this to be useful, and would\n> be a nicer way for some\n> configs to be displayed in the postgresql.conf file.\n>\n> Best,\n>\n> David\n>\n>\n> --\n>\nHi,\nFor parse_special_int():\n\n+ * true. If it's not found, return false and retval is set to 0.\n...\n+ /* don't touch the return value in other case */\n+ return false;\n\nIt seems the two comments are not consistent with each other (retval is not\nset in case no entry is found).\n\nFor special_int_to_value():\n\n+ * true. If it's not found, return false and retval is set to 0.\n\nFirst, there is no assignment to retval at the end of the method. Second,\nretval points to string, so it shouldn't be set to 0.\n\nCheers\n\nOn Thu, Aug 19, 2021 at 3:17 PM David Christensen <david.christensen@crunchydata.com> wrote:-hackers,\n\nEnclosed, find a POC patch that implements \"special values\" for int GUCs.  We have quite a few GUCs\nwith values that have special meaning atop other settings.  I have attempted to identify these and\nmake it so you can specify a symbol name for these values instead of just relying on the magic\nnumber instead.\n\nFor instance, many GUCs have -1 for \"disabled\", so I've just made it so you can\nspecify something like:\n\n  SET log_min_duration_statement = disabled;\n\nAnd the raw value will be set to -1 in this case.  For the purposes of testing, I have also added a\nnew GUC \"output_special_values\" to affect whether `SHOW` or anything that relies on _ShowOption()\ncan show with the special value instead of just the raw magic value, allowing tools to consume the\noriginal raw value, or provide the output to the user in the nicer format.\n\nThis has only been done for ints, and the passthru I did was very quick, so I have probably missed\nsome options that didn't explicitly have their interpretations in the file and/or I didn't know\nabout it already.  I do not think there are these sorts of values in other non-int GUCs, but there\nmight be, so a similar approach could be taken to expand things to other config types in the future.\n\nLet me know your thoughts; I personally find this to be useful, and would be a nicer way for some\nconfigs to be displayed in the postgresql.conf file.\n\nBest,\n\nDavid\n\n\n-- Hi,For parse_special_int():+ * true. If it's not found, return false and retval is set to 0....+   /* don't touch the return value in other case */+   return false;It seems the two comments are not consistent with each other (retval is not set in case no entry is found).For special_int_to_value():+ * true. If it's not found, return false and retval is set to 0.First, there is no assignment to retval at the end of the method. Second, retval points to string, so it shouldn't be set to 0.Cheers", "msg_date": "Thu, 19 Aug 2021 15:47:33 -0700", "msg_from": "Zhihong Yu <zyu@yugabyte.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "On Thu, Aug 19, 2021 at 3:44 PM David Christensen <\ndavid.christensen@crunchydata.com> wrote:\n\n> Functionality-wise, any thoughts on the overall approach or the specific\n> patch?\n>\n\nIf this information was exposed only by an addition to pg_settings, and\nthus not changeable via a GUC or affecting SHOW, I think it would be more\nlikely to get accepted. Being more liberal in the accepting of these\nvalues as input seems less problematic so that aspect could just stay. But\nthe display changes should be done with new outputs, not repurposing\nexisting ones.\n\nI'm at -0.5 as to whether such a patch would actually be an improvement or\nwhether the added possibilities would just be confusing and, because it is\nall optional, indefinitely so.\n\nDavid J.\n\nOn Thu, Aug 19, 2021 at 3:44 PM David Christensen <david.christensen@crunchydata.com> wrote: \nFunctionality-wise, any thoughts on the overall approach or the specific patch?If this information was exposed only by an addition to pg_settings, and thus not changeable via a GUC or affecting SHOW, I think it would be more likely to get accepted.  Being more liberal in the accepting of these values as input seems less problematic so that aspect could just stay.  But the display changes should be done with new outputs, not repurposing existing ones.I'm at -0.5 as to whether such a patch would actually be an improvement or whether the added possibilities would just be confusing and, because it is all optional, indefinitely so.David J.", "msg_date": "Thu, 19 Aug 2021 15:58:57 -0700", "msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "On Thu, Aug 19, 2021 at 03:58:57PM -0700, David G. Johnston wrote:\n> I'm at -0.5 as to whether such a patch would actually be an improvement or\n> whether the added possibilities would just be confusing and, because it is\n> all optional, indefinitely so.\n\nFWIW, I find this proposition of introducing a set of optional\nsynonyms to map with some special-case values we have in the\nconfigurations a bit confusing, as that's basically introducing\nenum-like options into GUCs that already have a type assigned.\n\nThe patch, with its set of options like special_disabled0,\nspecial_disabled_all is not really easy to parse either so that's just\na recipe to make the set of synonyms to grow on an GUC-basis.\n\nWhat I am wondering, though, is if there are cases in the existing\nGUCs, with their existing types, where the situation of a default or\ndisabled value could be improved, though, to make the overall picture\nmore consistent.\n--\nMichael", "msg_date": "Fri, 27 Aug 2021 15:19:04 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "On Fri, Aug 27, 2021 at 1:19 AM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> On Thu, Aug 19, 2021 at 03:58:57PM -0700, David G. Johnston wrote:\n> > I'm at -0.5 as to whether such a patch would actually be an improvement or\n> > whether the added possibilities would just be confusing and, because it is\n> > all optional, indefinitely so.\n>\n> FWIW, I find this proposition of introducing a set of optional\n> synonyms to map with some special-case values we have in the\n> configurations a bit confusing, as that's basically introducing\n> enum-like options into GUCs that already have a type assigned.\n\nIt does use enum-like mappings, but that is just because I needed to\ntie together name + value and just reused the already similar data\nstructure. That could be changed if the code itself is less\nunderstandable based on the struct names.\n\n> The patch, with its set of options like special_disabled0,\n> special_disabled_all is not really easy to parse either so that's just\n> a recipe to make the set of synonyms to grow on an GUC-basis.\n\nYes, when I started out on this, I expected maybe 2-3 different\ninterpretations at most, with more common overlap. I am not tied to\nmaking *every* GUC support this; maybe we support the special_disabled\nor special_disabled0 with differing names.\n\n> What I am wondering, though, is if there are cases in the existing\n> GUCs, with their existing types, where the situation of a default or\n> disabled value could be improved, though, to make the overall picture\n> more consistent.\n\nI think this would be possible, although the benefit of what I've\nwritten is that it doesn't change the interpretation of the value\nanywhere else, just in GUC parsing (and optionally GUC display). The\nparsing was where I felt this improved understanding, I'm less tied to\noutputting in the \"canonical\" way.\n\n\n", "msg_date": "Fri, 27 Aug 2021 13:22:24 -0500", "msg_from": "David Christensen <david.christensen@crunchydata.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "It looks like this patch rotted a little and needs to be rebased. Please see http://cfbot.cputube.org/\n\nThe new status of this patch is: Waiting on Author\n", "msg_date": "Thu, 09 Sep 2021 09:48:37 +0000", "msg_from": "Aleksander Alekseev <afiskon@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "Updated version attached with comment fixes and updated for new GUC.", "msg_date": "Wed, 15 Sep 2021 09:54:44 -0500", "msg_from": "David Christensen <david.christensen@crunchydata.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "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 quite like the feature this patch provides, it makes special int values more meaningful to user. I like that you added a configuration to allow the original int value to be outputted or the special value, this adds some flexibility in case returning special value breaks some old applications. I scanned through the GUC list and found that the following parameters can potentially be categorized in the \"special_disabled0\" group,\r\njust for your reference.\r\n\r\nmax_prepared_transactions\r\nvacuum_cost_delay\r\neffective_io_concurrency\r\nmax_parallel_workers\r\nmax_parallel_maintenance_workers\r\nmax_parallel_workers_per_gather\r\nmax_logical_replication_workers\r\nmax_sync_workers_per_subscription\r\njit_above_cost\r\njit_inline_above_cost\r\njit_optimize_above_cost\r\nlog_rotation_age\r\nlog_rotation_size\r\nlog_transaction_sample_rate\r\n\r\nCary Huang\r\n-----------------\r\nHighGo Software Canada\r\nwww.highgo.ca", "msg_date": "Fri, 15 Oct 2021 21:54:21 +0000", "msg_from": "Cary Huang <cary.huang@highgo.ca>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "> On 15 Oct 2021, at 23:54, Cary Huang <cary.huang@highgo.ca> wrote:\n\n> I scanned through the GUC list and found that the following parameters can\n> potentially be categorized in the \"special_disabled0\" group, just for your\n> reference.\n\n\nThis patch no longer applies, can you please submit a rebased version? Also,\ndo you have any thoughts on Cary's suggestion in the above review?\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Wed, 3 Nov 2021 11:35:31 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "> On Nov 3, 2021, at 5:35 AM, Daniel Gustafsson <daniel@yesql.se> wrote:\n> \n> \n>> \n>>> On 15 Oct 2021, at 23:54, Cary Huang <cary.huang@highgo.ca> wrote:\n>> \n>> I scanned through the GUC list and found that the following parameters can\n>> potentially be categorized in the \"special_disabled0\" group, just for your\n>> reference.\n> \n> \n> This patch no longer applies, can you please submit a rebased version? Also,\n> do you have any thoughts on Cary's suggestion in the above review?\n\nHi, enclosed is a v3, which includes the rebase as well as the additional int GUCs mentioned in Cary’s review. I can add support for Reals (required for the JIT and several other ones), but wanted to get feedback/buy-in on the overall idea first. \n\nBest,\n\nDavid", "msg_date": "Wed, 3 Nov 2021 16:50:20 -0500", "msg_from": "David Christensen <david@pgguru.net>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "Hi,\n\nOn Thu, Nov 4, 2021 at 5:50 AM David Christensen <david@pgguru.net> wrote:\n>\n> Hi, enclosed is a v3 [...]\n\nAccording to the cfbot, the patch doesn't apply anymore and needs a\nrebase: http://cfbot.cputube.org/patch_36_3290.log\n\n> 43 out of 133 hunks FAILED -- saving rejects to file src/backend/utils/misc/guc.c.rej\n\nI'm switching the patch to Waiting on Author.\n\n\n", "msg_date": "Wed, 12 Jan 2022 14:55:16 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "> Hi,\n> \n> According to the cfbot, the patch doesn't apply anymore and needs a\n> rebase: http://cfbot.cputube.org/patch_36_3290.log\n\nV4 rebased attached.", "msg_date": "Wed, 12 Jan 2022 12:57:02 -0600", "msg_from": "David Christensen <david@pgguru.net>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "Hi,\n\nOn 2022-01-12 12:57:02 -0600, David Christensen wrote:\n> > Hi,\n> > \n> > According to the cfbot, the patch doesn't apply anymore and needs a\n> > rebase: http://cfbot.cputube.org/patch_36_3290.log\n> \n> V4 rebased attached. \n\nDoesn't apply anymore, again: http://cfbot.cputube.org/patch_37_3290.log\n\nMy impression is that there's not a lot of enthusiasm for the concept? If\nthat's true we maybe ought to mark the CF entry as rejected?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 21 Mar 2022 17:37:00 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> My impression is that there's not a lot of enthusiasm for the concept? If\n> that's true we maybe ought to mark the CF entry as rejected?\n\nYeah, I'm kind of leaning that way too. I don't see how we can\nincorporate the symbolic values into any existing display paths\nwithout breaking applications that expect the old output.\nThat being the case, it seems like we'd have \"two ways to do it\"\nindefinitely, which would add enough confusion that I'm not\nsure there's a net gain. In particular, I foresee novice questions\nalong the lines of \"I set foo to disabled, why is it showing\nas zero?\".\n\nIf we'd done it like this from the beginning, it'd have been\ngreat, but retrofitting it now is a lot less appealing.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 21 Mar 2022 20:53:44 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "\n> On Mar 21, 2022, at 7:53 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Andres Freund <andres@anarazel.de> writes:\n>> My impression is that there's not a lot of enthusiasm for the concept? If\n>> that's true we maybe ought to mark the CF entry as rejected?\n> \n> Yeah, I'm kind of leaning that way too. I don't see how we can\n> incorporate the symbolic values into any existing display paths\n> without breaking applications that expect the old output.\n> That being the case, it seems like we'd have \"two ways to do it\"\n> indefinitely, which would add enough confusion that I'm not\n> sure there's a net gain. In particular, I foresee novice questions\n> along the lines of \"I set foo to disabled, why is it showing\n> as zero?\"\n\nYeah, my main motivation here was about trying to have less special values in the config files, but I guess it would effectively be making everything effectively an enum and still relies on knowing just what the specific magic values are, no not really a net gain in this department. \n\nFor the record, I thought this would have a fairly low chance of getting in, was mainly curious what level of effort it would take to get something like this going and get some feedback on the actual idea. \n\n> If we'd done it like this from the beginning, it'd have been\n> great, but retrofitting it now is a lot less appealing.\n\nYeah, agreed on this. As far as I’m concerned we can reject. \n\nThanks,\n\nDavid\n\n", "msg_date": "Tue, 22 Mar 2022 13:15:34 -0500", "msg_from": "David Christensen <david@pgguru.net>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" }, { "msg_contents": "On 2022-03-22 13:15:34 -0500, David Christensen wrote:\n> > On Mar 21, 2022, at 7:53 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > If we'd done it like this from the beginning, it'd have been\n> > great, but retrofitting it now is a lot less appealing.\n>\n> Yeah, agreed on this. As far as I’m concerned we can reject.\n\nUpdated CF entry to say so...\n\n\n", "msg_date": "Tue, 22 Mar 2022 12:04:06 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Proof of concept for GUC improvements" } ]
[ { "msg_contents": "While poking at a report of slow regexp matching [1], I happened\nto notice that citerdissect and creviterdissect are being remarkably\nstupid about how to backtrack after a match failure. Specifically,\nhaving used the DFA logic to identify K possible submatches, they\nthen start the slow recursive \"cdissect\" check of each submatch.\nBut, if the I'th submatch fails dissection, their response is to\nsee about adjusting the length of the last submatch ... which will\ndo nothing at all to make the result of the I'th submatch change,\nif it's before K. When this happens, we should immediately\nstart adjusting the length of the I'th submatch.\n\nAttached is a simple patch to do this. It passes check-world, and\nshows the same results as before on Jacobson's web-regexps corpus,\nas well as on a sample of random regexps made by Dilger's script.\nI don't really see any performance difference on Jacobson's corpus,\nbut Dilger's script did find an example where this makes a huge\ndifference:\n\nHEAD:\n\nregexp=# select regexp_match('nefajztngmsvfajztngmsvlwhjsq', '(.*)((\\1)){9}');\n regexp_match \n--------------\n \n(1 row)\n\nTime: 9655.141 ms (00:09.655)\n\nregexp=# select regexp_match('nefajztngmsvfajztngmsvlwhxxxxxxxxxxjsq', '(.*)((\\1)){9}');\n regexp_match \n--------------\n {x,x,x}\n(1 row)\n\nTime: 271106.324 ms (04:31.106)\n\nWith patch:\n\nregexp=# select regexp_match('nefajztngmsvfajztngmsvlwhjsq', '(.*)((\\1)){9}');\n regexp_match \n--------------\n \n(1 row)\n\nTime: 9.385 ms\n\nregexp=# select regexp_match('nefajztngmsvfajztngmsvlwhxxxxxxxxxxjsq', '(.*)((\\1)){9}');\n regexp_match \n--------------\n {x,x,x}\n(1 row)\n\nTime: 25.103 ms\n\nAdmittedly this is a bit contrived. (In v14/HEAD, you can make the\nperformance problem go away by getting rid of the redundant capturing\nparens, as then we don't invoke citerdissect at all. That trick doesn't\nhelp in the back branches though.)\n\nI think this is a pretty clear performance bug, and unless there are\nobjections I plan to push this fix into all branches.\n\n\t\t\tregards, tom lane\n\n[1] https://www.postgresql.org/message-id/CALZg0g4FA1Xc5UMLrGBKM--erUGEAhe8GGLE-YcN7%3DO6rw2%3D0A%40mail.gmail.com", "msg_date": "Thu, 19 Aug 2021 18:31:09 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Silliness in regexp's citerdissect/creviterdissect" } ]
[ { "msg_contents": "I'm using an ongoing patch review to educate myself on parts of the\ncodebase.\n\nIn src/backend/access/transam/xact.c, I'm noticing a code style\ninconsistency.\n\nIn some cases, a function will declare a variable of some struct pointer\ntype, assign it to a globally declared struct, and then use it like this:\n\nbool\nIsTransactionState(void)\n{\n TransactionState s = CurrentTransactionState;\n\n\n /*\n * TRANS_DEFAULT and TRANS_ABORT are obviously unsafe states. However,\nwe\n * also reject the startup/shutdown states TRANS_START, TRANS_COMMIT,\n * TRANS_PREPARE since it might be too soon or too late within those\n * transition states to do anything interesting. Hence, the only\n\"valid\"\n * state is TRANS_INPROGRESS.\n */\n return (s->state == TRANS_INPROGRESS);\n}\n\n\nAnd in other cases, the function will just reference the global directly\n\nbool\nTransactionStartedDuringRecovery(void)\n{\n return CurrentTransactionState->startedInRecovery;\n}\n\n\nClearly, this isn't a big deal. I'm willing to bet that the compiler looks\nat the variable declaration and thinks \"welp, it's just going to end up in\nan address register anyway, may as well optimize it away\" at even really\nlow optimization levels, so I'd be surprised if there's even a difference\nin the machine code generated, though it might hinder inlining the function\nas a whole. Mostly I'm just noticing the inconsistent coding style.\n\nGood points about the alias: I can see where the alias variable acts as a\nreminder of the data type, but even that is the type of a pointer to the\nstruct, so we're still 1 level of indirection away instead of 2. I can also\nsee where it might just be an artifact of getting stuff to fit within 80\nchars.\n\nBad points about the alias: I can see where things might hinder function\ninlining, and might also hinder git grep searches for the global variable\nname (though the global in question is scoped to the file, so that's not a\nbig concern).\n\nIs this something worth standardizing, and if so, which style do we like\nbetter?\n\nI'm using an ongoing patch review to educate myself on parts of the codebase.In src/backend/access/transam/xact.c, I'm noticing a code style inconsistency.In some cases, a function will declare a variable of some struct pointer type, assign it to a globally declared struct, and then use it like this:boolIsTransactionState(void){    TransactionState s = CurrentTransactionState;    /*     * TRANS_DEFAULT and TRANS_ABORT are obviously unsafe states.  However, we     * also reject the startup/shutdown states TRANS_START, TRANS_COMMIT,     * TRANS_PREPARE since it might be too soon or too late within those     * transition states to do anything interesting.  Hence, the only \"valid\"     * state is TRANS_INPROGRESS.     */    return (s->state == TRANS_INPROGRESS);}And in other cases, the function will just reference the global directlyboolTransactionStartedDuringRecovery(void){    return CurrentTransactionState->startedInRecovery;}Clearly, this isn't a big deal. I'm willing to bet that the compiler looks at the variable declaration and thinks \"welp, it's just going to end up in an address register anyway, may as well optimize it away\" at even really low optimization levels, so I'd be surprised if there's even a difference in the machine code generated, though it might hinder inlining the function as a whole. Mostly I'm just noticing the inconsistent coding style.Good points about the alias: I can see where the alias variable acts as a reminder of the data type, but even that is the type of a pointer to the struct, so we're still 1 level of indirection away instead of 2. I can also see where it might just be an artifact of getting stuff to fit within 80 chars.Bad points about the alias: I can see where things might hinder function inlining, and might also hinder git grep searches for the global variable name (though the global in question is scoped to the file, so that's not a big concern).Is this something worth standardizing, and if so, which style do we like better?", "msg_date": "Thu, 19 Aug 2021 22:57:20 -0400", "msg_from": "Corey Huinker <corey.huinker@gmail.com>", "msg_from_op": true, "msg_subject": "Nitpick/question: Use of aliases for global variables in functions" }, { "msg_contents": "Corey Huinker <corey.huinker@gmail.com> writes:\n> In src/backend/access/transam/xact.c, I'm noticing a code style\n> inconsistency.\n> [ to wit, local variable alias for CurrentTransactionState or not ]\n> Is this something worth standardizing, and if so, which style do we like\n> better?\n\nI can't get excited about changing this. There may be historical\nreasons for the differences, eg maybe at one time there was more\nthan one reference to the struct in IsTransactionState(). Or maybe\nit was just different people doing it a bit differently. It's not\nreally a big enough difference to be a hindrance to readers, IMO\nanyway, so I'd leave it alone.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 19 Aug 2021 23:25:00 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Nitpick/question: Use of aliases for global variables in\n functions" } ]
[ { "msg_contents": "\n\n> 20 авг. 2021 г., в 09:45, Nikolay Samokhvalov <nik@postgres.ai> написал(а):\n> \n> The patches changing the SLRU algorithm and adding GUCs to control the buffer sizes look really promising. Optimization in this area would really help those who use SAVEPOINTs. I suspect, we have a lot of such users – ORMs like Rails and Hibernate tend to use them for fancy nesting transaction processing.\n\nAwesome analysis, Nik, thanks!\nYes, I think there are many workloads that would benefit a lot from bigger SLRU caches.\n\nI just want to note, that on your screenshot unpatched version runs 400K tps, while patched runs 280K tps. I see the dates are different and this effect is not observed in [0]. Probably, you run tests on different machines. \n\nWhile your experiments clearly shows that patch can save DB from degradation under pathological workload it would be great to ensure patch does not incur penalty on normal workload.\n\nThank you!\n\nBest regards, Andrey Borodin.\n\n[0] https://gitlab.com/postgres-ai/postgresql-consulting/tests-and-benchmarks/-/issues/20\n\n", "msg_date": "Fri, 20 Aug 2021 10:04:42 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Subtransactions + a long-running transaction leading to\n performance degradation on standbys" }, { "msg_contents": "On Thu, Aug 19, 2021 at 10:04 PM Andrey Borodin <x4mmm@yandex-team.ru>\nwrote:\n\n> I just want to note, that on your screenshot unpatched version runs 400K\n> tps, while patched runs 280K tps. I see the dates are different and this\n> effect is not observed in [0]. Probably, you run tests on different\n> machines.\n\n\nIndeed, patched Postgres I was testing on 2x smaller EC2 instances, it is\ndocumented in the GitLab issue. But I added an additional note here:\nhttps://gitlab.com/postgres-ai/postgresql-consulting/tests-and-benchmarks/-/issues/21#note_655731979\n\n\n> While your experiments clearly shows that patch can save DB from\n> degradation under pathological workload it would be great to ensure patch\n> does not incur penalty on normal workload.\n>\n\nMakes sense. I'll try to find time to make a direct comparison.\n\nI documented all the steps in detail in the GitLab issue, so anyone\ninterested can reproduce it and explore the problem at different angles.\n\nOn Thu, Aug 19, 2021 at 10:04 PM Andrey Borodin <x4mmm@yandex-team.ru> wrote:\nI just want to note, that on your screenshot unpatched version runs 400K tps, while patched runs 280K tps. I see the dates are different and this effect is not observed in  [0]. Probably, you run tests on different machines.Indeed, patched Postgres I was testing on 2x smaller EC2 instances, it is documented in the GitLab issue. But I added an additional note here: https://gitlab.com/postgres-ai/postgresql-consulting/tests-and-benchmarks/-/issues/21#note_655731979 \nWhile your experiments clearly shows that patch can save DB from degradation under pathological workload it would be great to ensure patch does not incur penalty on normal workload.Makes sense. I'll try to find time to make a direct comparison.I documented all the steps in detail in the GitLab issue, so anyone interested can reproduce it and explore the problem at different angles.", "msg_date": "Thu, 19 Aug 2021 22:09:45 -0700", "msg_from": "Nikolay Samokhvalov <nik@postgres.ai>", "msg_from_op": false, "msg_subject": "Re: Subtransactions + a long-running transaction leading to\n performance degradation on standbys" } ]
[ { "msg_contents": "In commit 2f48ede08 I copied some error-message wording that had\nexisted in exec_run_select() since 2003. I'm now dissatified\nwith that, after realizing that it can produce output like this:\n\nERROR: query \"WITH a AS (\n SELECT\n regexp_split_to_table(info_out, '\\n') AS info\n FROM\n public.results\n WHERE\n public.results.jid = id\n)\n SELECT\n * INTO tabular_info\n FROM\n a RETURN\" is not a SELECT\nCONTEXT: PL/pgSQL function get_info(text) line 3 at RETURN QUERY\n\nThere are a couple of things wrong with this:\n\n1. The complaint is factually inaccurate, since the query obviously\n*is* a SELECT. It's the INTO part that's the problem, but good luck\nguessing that from the error text. (See [1] for motivation.)\n\n2. It's fairly unreadable when the query is a long multi-line one,\nas it does a great job of burying the lede. This also violates\nour message style guideline that says primary error messages should\nbe one-liners.\n\nThe way to fix #1 is to provide a special case for SELECT INTO.\nIn the attached I propose to fix #2 by moving the query text into\nan errcontext line, thus producing something like\n\nERROR: query is SELECT INTO, but it should be plain SELECT\nCONTEXT: query: WITH a AS (\n SELECT\n regexp_split_to_table(info_out, '\\n') AS info\n FROM\n public.results\n WHERE\n public.results.jid = id\n)\n SELECT\n * INTO tabular_info\n FROM\n a RETURN\nPL/pgSQL function get_info(text) line 3 at RETURN QUERY\n\nA case could also be made for just dropping the query text entirely,\nbut I'm inclined to think that's not such a great idea. Certainly\nwe ought to show the text in case of RETURN QUERY EXECUTE, where it\nwon't be embedded in the function text.\n\nLooking around, I noted that exec_eval_expr() also has the bad\nhabit of quoting the expression text right in the primary message,\nso the attached fixes that too. That case is slightly less bad\nsince expressions are more likely to be short, but they surely\naren't all short.\n\nThoughts? Should I back-patch this into v14 where 2f48ede08\ncame in, or just do it in HEAD?\n\n\t\t\tregards, tom lane\n\n[1] https://www.postgresql.org/message-id/y65a6lco0z4.fsf%40mun.ca", "msg_date": "Fri, 20 Aug 2021 11:50:24 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Improving some plpgsql error messages" }, { "msg_contents": "On Fri, Aug 20, 2021 at 8:50 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Thoughts? Should I back-patch this into v14 where 2f48ede08\n> came in, or just do it in HEAD?\n>\n\nI'd say back-patch in the interest of preventing probably quite a few\nemails from novices at plpgsql coding dealing with all the interplay\nbetween queries and variables and returning syntaxes.\n\nDavid J.\n\nOn Fri, Aug 20, 2021 at 8:50 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:Thoughts?  Should I back-patch this into v14 where 2f48ede08\ncame in, or just do it in HEAD?I'd say back-patch in the interest of preventing probably quite a few emails from novices at plpgsql coding dealing with all the interplay between queries and variables and returning syntaxes.David J.", "msg_date": "Fri, 20 Aug 2021 09:16:33 -0700", "msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Improving some plpgsql error messages" }, { "msg_contents": "pá 20. 8. 2021 v 17:50 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:\n\n> In commit 2f48ede08 I copied some error-message wording that had\n> existed in exec_run_select() since 2003. I'm now dissatified\n> with that, after realizing that it can produce output like this:\n>\n> ERROR: query \"WITH a AS (\n> SELECT\n> regexp_split_to_table(info_out, '\\n') AS info\n> FROM\n> public.results\n> WHERE\n> public.results.jid = id\n> )\n> SELECT\n> * INTO tabular_info\n> FROM\n> a RETURN\" is not a SELECT\n> CONTEXT: PL/pgSQL function get_info(text) line 3 at RETURN QUERY\n>\n> There are a couple of things wrong with this:\n>\n> 1. The complaint is factually inaccurate, since the query obviously\n> *is* a SELECT. It's the INTO part that's the problem, but good luck\n> guessing that from the error text. (See [1] for motivation.)\n>\n> 2. It's fairly unreadable when the query is a long multi-line one,\n> as it does a great job of burying the lede. This also violates\n> our message style guideline that says primary error messages should\n> be one-liners.\n>\n> The way to fix #1 is to provide a special case for SELECT INTO.\n> In the attached I propose to fix #2 by moving the query text into\n> an errcontext line, thus producing something like\n>\n> ERROR: query is SELECT INTO, but it should be plain SELECT\n> CONTEXT: query: WITH a AS (\n> SELECT\n> regexp_split_to_table(info_out, '\\n') AS info\n> FROM\n> public.results\n> WHERE\n> public.results.jid = id\n> )\n> SELECT\n> * INTO tabular_info\n> FROM\n> a RETURN\n> PL/pgSQL function get_info(text) line 3 at RETURN QUERY\n>\n> A case could also be made for just dropping the query text entirely,\n> but I'm inclined to think that's not such a great idea. Certainly\n> we ought to show the text in case of RETURN QUERY EXECUTE, where it\n> won't be embedded in the function text.\n>\n> Looking around, I noted that exec_eval_expr() also has the bad\n> habit of quoting the expression text right in the primary message,\n> so the attached fixes that too. That case is slightly less bad\n> since expressions are more likely to be short, but they surely\n> aren't all short.\n>\n> Thoughts? Should I back-patch this into v14 where 2f48ede08\n> came in, or just do it in HEAD?\n>\n\nIt can be fixed in 14. This is a low risk patch.\n\nRegards\n\nPavel\n\n\n> regards, tom lane\n>\n> [1] https://www.postgresql.org/message-id/y65a6lco0z4.fsf%40mun.ca\n>\n>\n\npá 20. 8. 2021 v 17:50 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:In commit 2f48ede08 I copied some error-message wording that had\nexisted in exec_run_select() since 2003.  I'm now dissatified\nwith that, after realizing that it can produce output like this:\n\nERROR:  query \"WITH a AS (\n    SELECT\n      regexp_split_to_table(info_out, '\\n') AS info\n    FROM\n      public.results\n    WHERE\n      public.results.jid = id\n)\n  SELECT\n    * INTO tabular_info\n  FROM\n    a RETURN\" is not a SELECT\nCONTEXT:  PL/pgSQL function get_info(text) line 3 at RETURN QUERY\n\nThere are a couple of things wrong with this:\n\n1. The complaint is factually inaccurate, since the query obviously\n*is* a SELECT.  It's the INTO part that's the problem, but good luck\nguessing that from the error text.  (See [1] for motivation.)\n\n2. It's fairly unreadable when the query is a long multi-line one,\nas it does a great job of burying the lede.  This also violates\nour message style guideline that says primary error messages should\nbe one-liners.\n\nThe way to fix #1 is to provide a special case for SELECT INTO.\nIn the attached I propose to fix #2 by moving the query text into\nan errcontext line, thus producing something like\n\nERROR:  query is SELECT INTO, but it should be plain SELECT\nCONTEXT:  query: WITH a AS (\n    SELECT\n      regexp_split_to_table(info_out, '\\n') AS info\n    FROM\n      public.results\n    WHERE\n      public.results.jid = id\n)\n  SELECT\n    * INTO tabular_info\n  FROM\n    a RETURN\nPL/pgSQL function get_info(text) line 3 at RETURN QUERY\n\nA case could also be made for just dropping the query text entirely,\nbut I'm inclined to think that's not such a great idea.  Certainly\nwe ought to show the text in case of RETURN QUERY EXECUTE, where it\nwon't be embedded in the function text.\n\nLooking around, I noted that exec_eval_expr() also has the bad\nhabit of quoting the expression text right in the primary message,\nso the attached fixes that too.  That case is slightly less bad\nsince expressions are more likely to be short, but they surely\naren't all short.\n\nThoughts?  Should I back-patch this into v14 where 2f48ede08\ncame in, or just do it in HEAD?It can be fixed in 14. This is a low risk patch.RegardsPavel \n\n                        regards, tom lane\n\n[1] https://www.postgresql.org/message-id/y65a6lco0z4.fsf%40mun.ca", "msg_date": "Fri, 20 Aug 2021 18:41:02 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Improving some plpgsql error messages" }, { "msg_contents": "On Fri, Aug 20, 2021 at 12:41 PM Pavel Stehule <pavel.stehule@gmail.com> wrote:\n> It can be fixed in 14. This is a low risk patch.\n\n+1.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 20 Aug 2021 13:24:29 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Improving some plpgsql error messages" } ]
[ { "msg_contents": "When perusing the pg_amcheck code the other day for the recently pushed fixes I\nfound two small things that seem worth fixing: The help function progname\nparameter shadows the global variable of the same name, which no doubt will\nmake static analyzers complain so we might as well fix that; and there is a\ntiny typo in the test stanza.\n\nBoth fixed in the attached.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/", "msg_date": "Fri, 20 Aug 2021 20:19:56 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": true, "msg_subject": "Minor pg_amcheck fixes spotted while reading code" }, { "msg_contents": "\n\n> On Aug 20, 2021, at 11:19 AM, Daniel Gustafsson <daniel@yesql.se> wrote:\n> \n> When perusing the pg_amcheck code the other day for the recently pushed fixes I\n> found two small things that seem worth fixing: The help function progname\n> parameter shadows the global variable of the same name, which no doubt will\n> make static analyzers complain so we might as well fix that; and there is a\n> tiny typo in the test stanza.\n> \n> Both fixed in the attached.\n> \n> --\n> Daniel Gustafsson\t\thttps://vmware.com/\n> \n> <0001-Fix-variable-shadowing.patch><0002-pg_amcheck-test-typofix.patch>\n\nThese look correct.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Fri, 20 Aug 2021 11:42:09 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Minor pg_amcheck fixes spotted while reading code" }, { "msg_contents": "On Fri, Aug 20, 2021 at 11:42:09AM -0700, Mark Dilger wrote:\n> These look correct.\n\n static void\n-help(const char *progname)\n+help(const char *program_name)\nThese were discussed not long ago, and I recall that they were in the\nwe-don't-care category. Note for example all the tools of\nsrc/scripts/ and pg_dump/.\n--\nMichael", "msg_date": "Sat, 21 Aug 2021 09:43:10 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Minor pg_amcheck fixes spotted while reading code" }, { "msg_contents": "> On 21 Aug 2021, at 02:43, Michael Paquier <michael@paquier.xyz> wrote:\n> \n> On Fri, Aug 20, 2021 at 11:42:09AM -0700, Mark Dilger wrote:\n>> These look correct.\n> \n> static void\n> -help(const char *progname)\n> +help(const char *program_name)\n> These were discussed not long ago, and I recall that they were in the\n> we-don't-care category. Note for example all the tools of\n> src/scripts/ and pg_dump/.\n\nFair enough, I had missed that thread.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Mon, 23 Aug 2021 09:37:40 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": true, "msg_subject": "Re: Minor pg_amcheck fixes spotted while reading code" } ]
[ { "msg_contents": "Hi,\n\nI've been pinged many time over the years to either fix Windows compatibility\nor provide DLL for multiple extensions I'm maintaining. I've finally taken\nsome time to setup a Windows build environment so I could take care of most of\nthe problem, but not all (at least not in a satisfactory way).\n\nI've also been looking a bit around other extensions and I see that the #1\nproblem with compiling extensions on Windows is the lack of PGDLLIMPORT\nannotations, which is 99% of the time for a GUC.\n\nThis topic has been raised multiple time over the years, and I don't see any\nobjection to add such an annotation at least for all GUC variables (either the\ndirect variables or the indirect variables set during the hook execution), so\nPFA a patch that takes care of all the GUC.\n\nI don't now if that's still an option at that point, but backporting to at\nleast pg14 if that patch is accepted would be quite helpful.", "msg_date": "Sun, 22 Aug 2021 16:10:33 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": true, "msg_subject": "Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Sun, Aug 22, 2021 at 04:10:33PM +0800, Julien Rouhaud wrote:\n> This topic has been raised multiple time over the years, and I don't see any\n> objection to add such an annotation at least for all GUC variables (either the\n> direct variables or the indirect variables set during the hook execution), so\n> PFA a patch that takes care of all the GUC.\n> \n> I don't now if that's still an option at that point, but backporting to at\n> least pg14 if that patch is accepted would be quite helpful.\n\nThese are usually just applied on HEAD, and on a parameter-basis based\non requests from extension authors. If you wish to make your\nextensions able to work on Windows, that's a good idea, but I would\nrecommend to limit this exercise to what's really necessary for your\npurpose.\n--\nMichael", "msg_date": "Sun, 22 Aug 2021 20:51:26 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Sun, Aug 22, 2021 at 08:51:26PM +0900, Michael Paquier wrote:\n> On Sun, Aug 22, 2021 at 04:10:33PM +0800, Julien Rouhaud wrote:\n> > This topic has been raised multiple time over the years, and I don't see any\n> > objection to add such an annotation at least for all GUC variables (either the\n> > direct variables or the indirect variables set during the hook execution), so\n> > PFA a patch that takes care of all the GUC.\n> > \n> > I don't now if that's still an option at that point, but backporting to at\n> > least pg14 if that patch is accepted would be quite helpful.\n> \n> These are usually just applied on HEAD\n\nYeah but 14 isn't released yet, and this is a really low risk change.\n\n> , and on a parameter-basis based\n> on requests from extension authors. If you wish to make your\n> extensions able to work on Windows, that's a good idea, but I would\n> recommend to limit this exercise to what's really necessary for your\n> purpose.\n\nI disagree. For random global variables I agree that we shouldn't mark them\nall blindly, but for GUCs it's pretty clear that they're intended to be\naccessible from any caller, including extensions. Why treating Windows as a\nsecond-class citizen, especially when any change can only be used a year after\nsomeone complained?\n\n\n", "msg_date": "Sun, 22 Aug 2021 20:07:43 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "ne 22. 8. 2021 v 14:08 odesílatel Julien Rouhaud <rjuju123@gmail.com>\nnapsal:\n\n> On Sun, Aug 22, 2021 at 08:51:26PM +0900, Michael Paquier wrote:\n> > On Sun, Aug 22, 2021 at 04:10:33PM +0800, Julien Rouhaud wrote:\n> > > This topic has been raised multiple time over the years, and I don't\n> see any\n> > > objection to add such an annotation at least for all GUC variables\n> (either the\n> > > direct variables or the indirect variables set during the hook\n> execution), so\n> > > PFA a patch that takes care of all the GUC.\n> > >\n> > > I don't now if that's still an option at that point, but backporting\n> to at\n> > > least pg14 if that patch is accepted would be quite helpful.\n> >\n> > These are usually just applied on HEAD\n>\n> Yeah but 14 isn't released yet, and this is a really low risk change.\n>\n> > , and on a parameter-basis based\n> > on requests from extension authors. If you wish to make your\n> > extensions able to work on Windows, that's a good idea, but I would\n> > recommend to limit this exercise to what's really necessary for your\n> > purpose.\n>\n> I disagree. For random global variables I agree that we shouldn't mark\n> them\n> all blindly, but for GUCs it's pretty clear that they're intended to be\n> accessible from any caller, including extensions. Why treating Windows as\n> a\n> second-class citizen, especially when any change can only be used a year\n> after\n> someone complained?\n>\n\nI had few problems with access with these variables too when I worked on\norafce.\n\nIs true, so it increases differences between Windows and Unix, and fixing\nthese issues is not fun work. On the other hand, maybe direct access to\nthese variables from extensions is an antipattern, and we should use a\ndirect function call API and functions current_setting and set_config. The\noverhead is usually not too big.\n\nne 22. 8. 2021 v 14:08 odesílatel Julien Rouhaud <rjuju123@gmail.com> napsal:On Sun, Aug 22, 2021 at 08:51:26PM +0900, Michael Paquier wrote:\n> On Sun, Aug 22, 2021 at 04:10:33PM +0800, Julien Rouhaud wrote:\n> > This topic has been raised multiple time over the years, and I don't see any\n> > objection to add such an annotation at least for all GUC variables (either the\n> > direct variables or the indirect variables set during the hook execution), so\n> > PFA a patch that takes care of all the GUC.\n> > \n> > I don't now if that's still an option at that point, but backporting to at\n> > least pg14 if that patch is accepted would be quite helpful.\n> \n> These are usually just applied on HEAD\n\nYeah but 14 isn't released yet, and this is a really low risk change.\n\n> , and on a parameter-basis based\n> on requests from extension authors.  If you wish to make your\n> extensions able to work on Windows, that's a good idea, but I would\n> recommend to limit this exercise to what's really necessary for your\n> purpose.\n\nI disagree.  For random global variables I agree that we shouldn't mark them\nall blindly, but for GUCs it's pretty clear that they're intended to be\naccessible from any caller, including extensions.  Why treating Windows as a\nsecond-class citizen, especially when any change can only be used a year after\nsomeone complained?I had few problems with access with these variables too when I worked on orafce.Is true, so it increases differences between Windows and Unix, and fixing these issues is not fun work. On the other hand, maybe direct access to these variables from extensions is an antipattern, and we should use a direct function call API and functions current_setting and set_config. The overhead is usually not too big.", "msg_date": "Sun, 22 Aug 2021 14:17:16 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Sun, Aug 22, 2021 at 02:17:16PM +0200, Pavel Stehule wrote:\n> \n> Is true, so it increases differences between Windows and Unix, and fixing\n> these issues is not fun work. On the other hand, maybe direct access to\n> these variables from extensions is an antipattern, and we should use a\n> direct function call API and functions current_setting and set_config. The\n> overhead is usually not too big.\n\nYes, and that's what I did for one of my extensions. But that's still a bit of\noverhead, and extra burden only seen when trying to have Windows compatiblity,\nand I hope I can get rid of that at some point.\n\nIf direct variable access shouldn't be possible, then we should explicitly tag\nthose with __attribute__ ((visibility (\"hidden\"))) or something like that to\nhave a more consistent behavior.\n\n\n", "msg_date": "Sun, 22 Aug 2021 20:25:51 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Julien Rouhaud <rjuju123@gmail.com> writes:\n> On Sun, Aug 22, 2021 at 08:51:26PM +0900, Michael Paquier wrote:\n>> ... and on a parameter-basis based\n>> on requests from extension authors. If you wish to make your\n>> extensions able to work on Windows, that's a good idea, but I would\n>> recommend to limit this exercise to what's really necessary for your\n>> purpose.\n\n> I disagree. For random global variables I agree that we shouldn't mark them\n> all blindly, but for GUCs it's pretty clear that they're intended to be\n> accessible from any caller, including extensions.\n\nUh, no, it's exactly *not* clear. There are a lot of GUCs that are only\nof interest to particular subsystems. I do not see why being a GUC makes\nsomething automatically more interesting than any other global variable.\nUsually, the fact that one is global is only so the GUC machinery itself\ncan get at it, otherwise it'd be static in the owning module.\n\nAs for \"extensions should be able to get at the values\", the GUC machinery\nalready provides uniform mechanisms for doing that safely. Direct access\nto the variable's internal value would be unsafe in many cases.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 22 Aug 2021 09:19:42 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Sun, Aug 22, 2021 at 09:19:42AM -0400, Tom Lane wrote:\n> \n> Uh, no, it's exactly *not* clear. There are a lot of GUCs that are only\n> of interest to particular subsystems. I do not see why being a GUC makes\n> something automatically more interesting than any other global variable.\n> Usually, the fact that one is global is only so the GUC machinery itself\n> can get at it, otherwise it'd be static in the owning module.\n> \n> As for \"extensions should be able to get at the values\", the GUC machinery\n> already provides uniform mechanisms for doing that safely. Direct access\n> to the variable's internal value would be unsafe in many cases.\n\nThen shouldn't we try to prevent direct access on all platforms rather than\nonly one?\n\n\n", "msg_date": "Sun, 22 Aug 2021 21:29:01 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Sun, Aug 22, 2021 at 09:29:01PM +0800, Julien Rouhaud wrote:\n> On Sun, Aug 22, 2021 at 09:19:42AM -0400, Tom Lane wrote:\n> > \n> > Uh, no, it's exactly *not* clear. There are a lot of GUCs that are only\n> > of interest to particular subsystems. I do not see why being a GUC makes\n> > something automatically more interesting than any other global variable.\n> > Usually, the fact that one is global is only so the GUC machinery itself\n> > can get at it, otherwise it'd be static in the owning module.\n> > \n> > As for \"extensions should be able to get at the values\", the GUC machinery\n> > already provides uniform mechanisms for doing that safely. Direct access\n> > to the variable's internal value would be unsafe in many cases.\n> \n> Then shouldn't we try to prevent direct access on all platforms rather than\n> only one?\n\nSo since the non currently explicitly exported GUC global variables shouldn't\nbe accessible by third-party code, I'm attaching a POC patch that does the\nopposite of v1: enforce that restriction using a new pg_attribute_hidden()\nmacro, defined with GCC only, to start discussing that topic.\n\nIt would probably be better to have some other macro (e.g. PG_GLOBAL_PUBLIC and\nPG_GLOBAL_PRIVATE or similar) to make declarations more consistent, but given\nthe amount of changes it would represent I prefer to have some feedback before\nspending time on that.", "msg_date": "Mon, 23 Aug 2021 14:53:34 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Sun, Aug 22, 2021 at 09:29:01PM +0800, Julien Rouhaud wrote:\n> On Sun, Aug 22, 2021 at 09:19:42AM -0400, Tom Lane wrote:\n> > \n> > Uh, no, it's exactly *not* clear. There are a lot of GUCs that are only\n> > of interest to particular subsystems. I do not see why being a GUC makes\n> > something automatically more interesting than any other global variable.\n> > Usually, the fact that one is global is only so the GUC machinery itself\n> > can get at it, otherwise it'd be static in the owning module.\n> > \n> > As for \"extensions should be able to get at the values\", the GUC machinery\n> > already provides uniform mechanisms for doing that safely. Direct access\n> > to the variable's internal value would be unsafe in many cases.\n> \n> Then shouldn't we try to prevent direct access on all platforms rather than\n> only one?\n\nAgreed. If Julian says 99% of the non-export problems are GUCs, and we\ncan just export them all, why not do it? We already export every global\nvariable on Unix-like systems, and we have seen no downsides.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Mon, 23 Aug 2021 10:07:16 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Bruce Momjian <bruce@momjian.us> writes:\n> On Sun, Aug 22, 2021 at 09:29:01PM +0800, Julien Rouhaud wrote:\n>> Then shouldn't we try to prevent direct access on all platforms rather than\n>> only one?\n\n> Agreed. If Julian says 99% of the non-export problems are GUCs, and we\n> can just export them all, why not do it? We already export every global\n> variable on Unix-like systems, and we have seen no downsides.\n\nBy that argument, *every* globally-visible variable should be marked\nPGDLLIMPORT. But the mere fact that two backend .c files need to access\nsome variable doesn't mean that we want any random bit of code doing so.\n\nAnd yes, I absolutely would prohibit extensions from accessing many\nof them, if there were a reasonable way to do it. It would be a good\nstart towards establishing a defined API for extensions.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 23 Aug 2021 10:15:04 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, Aug 23, 2021 at 10:15:04AM -0400, Tom Lane wrote:\n> Bruce Momjian <bruce@momjian.us> writes:\n> > On Sun, Aug 22, 2021 at 09:29:01PM +0800, Julien Rouhaud wrote:\n> >> Then shouldn't we try to prevent direct access on all platforms rather than\n> >> only one?\n> \n> > Agreed. If Julian says 99% of the non-export problems are GUCs, and we\n> > can just export them all, why not do it? We already export every global\n> > variable on Unix-like systems, and we have seen no downsides.\n> \n> By that argument, *every* globally-visible variable should be marked\n> PGDLLIMPORT. But the mere fact that two backend .c files need to access\n\nNo, Julien says 99% need only the GUCs, so that is not the argument I am\nmaking.\n\n> some variable doesn't mean that we want any random bit of code doing so.\n> \n> And yes, I absolutely would prohibit extensions from accessing many\n> of them, if there were a reasonable way to do it. It would be a good\n> start towards establishing a defined API for extensions.\n\nWell, if Unix needed it, we would have addressed this more regularly,\nbut since it is only Windows that has this _feature_, it is the rare\nWindows cases that need adjustment, and usually as an afterthought since\nWindows isn't usually a primary tested platform.\n\nWhat I am saying is that if we blocked global variable access on Unix,\ninitial testing would have showed what needs to be exported and it would\nnot be as big a problem.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Mon, 23 Aug 2021 10:19:07 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Bruce Momjian <bruce@momjian.us> writes:\n> On Mon, Aug 23, 2021 at 10:15:04AM -0400, Tom Lane wrote:\n>> By that argument, *every* globally-visible variable should be marked\n>> PGDLLIMPORT. But the mere fact that two backend .c files need to access\n\n> No, Julien says 99% need only the GUCs, so that is not the argument I am\n> making.\n\nThat's a claim unbacked by any evidence that I've seen. More to\nthe point, we already have a mechanism that extensions can/should\nuse to read and write GUC settings, and it's not direct access.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 23 Aug 2021 10:22:51 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, Aug 23, 2021 at 10:22:51AM -0400, Tom Lane wrote:\n> Bruce Momjian <bruce@momjian.us> writes:\n> > On Mon, Aug 23, 2021 at 10:15:04AM -0400, Tom Lane wrote:\n> >> By that argument, *every* globally-visible variable should be marked\n> >> PGDLLIMPORT. But the mere fact that two backend .c files need to access\n> \n> > No, Julien says 99% need only the GUCs, so that is not the argument I am\n> > making.\n> \n> That's a claim unbacked by any evidence that I've seen. More to\n> the point, we already have a mechanism that extensions can/should\n> use to read and write GUC settings, and it's not direct access.\n\nSo the problem is that extensions only _need_ to use that API on\nWindows, so many initially don't, or that the API is too limited?\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Mon, 23 Aug 2021 10:36:17 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, Aug 23, 2021 at 10:22 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Bruce Momjian <bruce@momjian.us> writes:\n> > On Mon, Aug 23, 2021 at 10:15:04AM -0400, Tom Lane wrote:\n> >> By that argument, *every* globally-visible variable should be marked\n> >> PGDLLIMPORT. But the mere fact that two backend .c files need to access\n>\n> > No, Julien says 99% need only the GUCs, so that is not the argument I am\n> > making.\n>\n> That's a claim unbacked by any evidence that I've seen. More to\n> the point, we already have a mechanism that extensions can/should\n> use to read and write GUC settings, and it's not direct access.\n\nI clearly didn't try all single extension available out there. It's\nexcessively annoying to compile extensions on Windows, and also I\ndon't have a lot of dependencies installed so there are some that I\nwasn't able to test since I'm lacking some other lib and given my\nabsolute lack of knowledge of that platform I didn't spent time trying\nto install those.\n\nI think I tested a dozen of \"small\" extensions (I'm assuming that the\nbig one like postgis would require too much effort to build, and they\nprobably already take care of Windows compatibility), and I only faced\nthis problem. That's maybe not a representative set, but I also doubt\nthat I was unlucky enough to find the few only exceptions.\n\n\n", "msg_date": "Mon, 23 Aug 2021 22:45:19 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, Aug 23, 2021 at 10:36 PM Bruce Momjian <bruce@momjian.us> wrote:\n>\n> So the problem is that extensions only _need_ to use that API on\n> Windows, so many initially don't, or that the API is too limited?\n\nThe inconvenience with that API is that it's only returning c strings,\nso you gave to convert it back to the original datatype. That's\nprobably why most of the extensions simply read from the original\nexposed variable rather than using the API, because they're usually\nwritten on Linux or similar, not because they want to mess up the\nstored value.\n\n\n", "msg_date": "Mon, 23 Aug 2021 22:47:54 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, Aug 23, 2021 at 10:15 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> And yes, I absolutely would prohibit extensions from accessing many\n> of them, if there were a reasonable way to do it. It would be a good\n> start towards establishing a defined API for extensions.\n\nThe v2 patch I sent does that, at least when compiling with GCC. I\ndidn't find something similar for clang, but I only checked quickly.\n\nI'm assuming that the unreasonable part is having to add some extra\nattribute to the variable? Would it be acceptable if wrapped into\nsome other macro, as I proposed?\n\n\n", "msg_date": "Mon, 23 Aug 2021 22:50:44 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, Aug 23, 2021 at 10:15 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> And yes, I absolutely would prohibit extensions from accessing many\n> of them, if there were a reasonable way to do it. It would be a good\n> start towards establishing a defined API for extensions.\n\nMostly, it would make extension development more difficult for no\ndiscernable benefit to the project.\n\nYou've made this argument many times over the years ... but we're no\ncloser to having an extension API than we ever were, and we continue\nto get complaints about breaking stuff on Windows on a pretty regular\nbasis.\n\nHonestly, it seems unimaginable that an API is ever really going to be\npossible. It would be a ton of work to maintain, and we'd just end up\nbreaking it every time we discover that there's a new feature we want\nto implement which doesn't fit into the defined API now. That's what\nwe do *now* with functions that third-party extensions actually call,\nand with variables that they access, and it's not something that, in\nmy experience, is any great problem in maintaining an extension.\nYou're running code that is running inside somebody else's executable\nand sometimes you have to adjust it for upstream changes. That's life,\nand I don't think that complaints about that topic are nearly as\nfrequent as complaints about extensions breaking on Windows because of\nmissing PGDLLIMPORT markings.\n\nAnd more than that, I'm pretty sure that you've previously taken the\nview that we shouldn't document all the hook functions that only exist\nin the backend for the purpose of extension use. I think you would\nargue against a patch to go and document all the variables that are\nmarked PGDLLIMPORT now. So it seems to me that you're for an API when\nit means that we don't have to change anything, and against an API\nwhen it means that we don't have to change anything, which doesn't\nreally seem like a consistent position. I think we should be\nresponding to the real, expressed needs of extension developers, and\nthe lack of PGDLLIMPORT markings on various global variables is surely\ntop of the list.\n\nIt's also a bit unfair to say, well we have APIs for accessing GUC\nvalues. It's true that we do. But if the GUC variable is, say, a\nBoolean, you do not want your extension to call some function that\ndoes a bunch of shenanigans and returns a string so that you can then\nturn around and parse the string to recover the Boolean value. Even\nmoreso if the value is an integer or a comma-separated list. You want\nto access the value as the system represents it internally, not\nduplicate the parsing logic in a way that is inefficient and\nbug-prone.\n\nIn short, +1 from me for the original proposal of marking all GUCs as\nPGDLLIMPORT. And, heck, +1 for marking all the other global variables\nthat way, too. We're not solving any problem here. We're just annoying\npeople, mostly people who are loyal community members and steady\ncontributors to the project.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 23 Aug 2021 10:56:52 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On 08/23/21 10:36, Bruce Momjian wrote:\n\n> So the problem is that extensions only _need_ to use that API on\n> Windows, so many initially don't, or that the API is too limited?\n\nI think there can be cases where it's too limited, such as when significant\ncomputation or validation is needed between the form of the setting known\nto the GUC machinery and the form that would otherwise be available in\nthe global.\n\nI'm thinking, for instance, of the old example before session_timezone\nwas PGDLLIMPORTed, and you'd have to GETCONFIGOPTION(\"timezone\") and\nrepeat the work done by pg_tzset to validate and map the timezone name\nthrough the timezone database, to reconstruct the value that was\notherwise already available in session_timezone.\n\nMaybe those cases aren't very numerous ... and maybe they're distinctive\nenough to recognize when creating one (\"hmm, I am creating a check or\nassign hook that does significant work here, will it be worth exposing\na getter API for the product of the work?\").\n\nRegards,\n-Chap\n\n\n", "msg_date": "Mon, 23 Aug 2021 10:57:16 -0400", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On 2021-Aug-23, Robert Haas wrote:\n\n> It's also a bit unfair to say, well we have APIs for accessing GUC\n> values. It's true that we do. But if the GUC variable is, say, a\n> Boolean, you do not want your extension to call some function that\n> does a bunch of shenanigans and returns a string so that you can then\n> turn around and parse the string to recover the Boolean value. Even\n> moreso if the value is an integer or a comma-separated list. You want\n> to access the value as the system represents it internally, not\n> duplicate the parsing logic in a way that is inefficient and\n> bug-prone.\n\nIn that case, why not improve the API with functions that return the\nvalues in some native datatype? For scalars with native C types (int,\nfloats, Boolean etc) this is easy enough; I bet it'll solve 99% of the\nproblems or more.\n\n-- \nÁlvaro Herrera 39°49'30\"S 73°17'W — https://www.EnterpriseDB.com/\n\n\n", "msg_date": "Mon, 23 Aug 2021 11:40:20 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On 08/23/21 10:57, Chapman Flack wrote:\n> Maybe those cases aren't very numerous ... and maybe they're distinctive\n> enough to recognize when creating one (\"hmm, I am creating a check or\n> assign hook that does significant work here, will it be worth exposing\n> a getter API for the product of the work?\").\n\nHow about a generic GetTypedConfigValue(char const *name, void *into) ?\n\nBy default the type of *into would correspond to the type of the GUC\n(int for an enum) and would be returned directly from *conf->variable\nby a getter hook installed by default when the GUC is defined. But the\ndefinition could also supply a getter hook that would store a value of\na different type, or computed a different way, for a GUC where that's\nappropriate.\n\nThe function return could be boolean, true if such a variable exists\nand isn't a placeholder.\n\nPro: provides read access to the typed value of any GUC, without exposing\nit to overwriting. Con: has to bsearch the GUCs every time the value\nis wanted.\n\nWhat I'd really like:\n\nObserveTypedConfigValue(char const *name, void *into, int *flags, int flag)\n\nThis would register an observer of the named GUC: whenever its typed value\nchanges, it is written at *into and flag is ORed into *flags.\n\nThis is more restrictive than allowing arbitrary code to be hooked into\nGUC changes (as changes can happen at delicate times such as error\nrecovery), but allows an extension to always have the current typed\nvalue available and to cheaply know when it has changed. Observers would\nbe updated in the normal course of processing a GUC change, eliminating\nthe bsearch-per-lookup cost of the first approach.\n\nThinkable?\n\nRegards,\n-Chap\n\n\n", "msg_date": "Mon, 23 Aug 2021 11:52:05 -0400", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, Aug 23, 2021 at 11:40 AM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> In that case, why not improve the API with functions that return the\n> values in some native datatype? For scalars with native C types (int,\n> floats, Boolean etc) this is easy enough; I bet it'll solve 99% of the\n> problems or more.\n\nSure, but ... why bother?\n\nThe entire argument rests on the presumption that there is some harm\nbeing done by people accessing the values directly, but I don't think\nthat's true. And, if it were true, it seems likely that this proposed\nAPI would have the exact same problem, because it would let people do\nexactly the same thing. And, going through this proposed API would\nstill be significantly more expensive than just accessing the bare\nvariables, because you'd at least have to do some kind of lookup based\non the GUC name to find the corresponding variable. It's just a\nsolution in search of a problem.\n\nNothing bad happens when people write extensions that access GUC\nvariables directly. It works totally, completely fine. Except on\nWindows.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 23 Aug 2021 14:30:57 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, Aug 23, 2021 at 7:57 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> In short, +1 from me for the original proposal of marking all GUCs as\n> PGDLLIMPORT.\n\n+1\n\n> And, heck, +1 for marking all the other global variables\n> that way, too. We're not solving any problem here. We're just annoying\n> people, mostly people who are loyal community members and steady\n> contributors to the project.\n\nI'm +0.5 on this aspect -- the result might be a lot of verbosity for\nno possible benefit.\n\nI'm not sure how many global variables there are. Hopefully not that\nmany. Maybe making adding new global variables annoying would be a\nuseful disincentive -- sometimes we use global variables when it isn't\nparticularly natural (it's natural with GUCs, but not other things).\nThat might tip the scales, at least for me.\n\nUnnecessary use of global variables are why Postgres 13 went through\nseveral point releases before I accidentally found out that parallel\nVACUUM doesn't respect cost limits -- a very simple bug concerning how\nwe propagate (or fail to propagate) state to parallel workers. I bet\nit would have taken far longer for the bug to be discovered if it\nwasn't for my Postgres 14 VACUUM refactoring work.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Mon, 23 Aug 2021 11:48:35 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, Aug 23, 2021 at 10:56:52AM -0400, Robert Haas wrote:\n> On Mon, Aug 23, 2021 at 10:15 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > And yes, I absolutely would prohibit extensions from accessing many\n> > of them, if there were a reasonable way to do it. It would be a good\n> > start towards establishing a defined API for extensions.\n> \n> Mostly, it would make extension development more difficult for no\n> discernable benefit to the project.\n> \n> You've made this argument many times over the years ... but we're no\n> closer to having an extension API than we ever were, and we continue\n> to get complaints about breaking stuff on Windows on a pretty regular\n> basis.\n> \n> Honestly, it seems unimaginable that an API is ever really going to be\n> possible. It would be a ton of work to maintain, and we'd just end up\n> breaking it every time we discover that there's a new feature we want\n> to implement which doesn't fit into the defined API now. That's what\n> we do *now* with functions that third-party extensions actually call,\n> and with variables that they access, and it's not something that, in\n> my experience, is any great problem in maintaining an extension.\n> You're running code that is running inside somebody else's executable\n> and sometimes you have to adjust it for upstream changes. That's life,\n> and I don't think that complaints about that topic are nearly as\n> frequent as complaints about extensions breaking on Windows because of\n> missing PGDLLIMPORT markings.\n> \n> And more than that, I'm pretty sure that you've previously taken the\n> view that we shouldn't document all the hook functions that only exist\n> in the backend for the purpose of extension use.\n\nAs the person on the receiving end of that one, I was nonplussed, so I\ntook a step back to think it over. I recognized at that time that I\ndidn't have a great answer for a legitimate concern, namely that any\nchange, however trivial, that goes into the core and doesn't go\ndirectly to core database functionality, represents a long-term\nmaintenance burden.\n\nThe thing I'm coming to is that the key architectural feature\nPostgreSQL has that other RDBMSs don't is its extensibility. Because\nthat's been a stable feature over time, I'm pretty sure we actually\nneed to see documenting that as a thing that does actually go to core\ndatabase functionality. Yes, there are resources involved with doing a\nthing like this, but I don't think that they require constant or even\nfrequent attention from committers or even from seasoned DB hackers.\n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate\n\n\n", "msg_date": "Mon, 23 Aug 2021 20:12:12 +0000", "msg_from": "David Fetter <david@fetter.org>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On 08/23/21 14:30, Robert Haas wrote:\n> it seems likely that this proposed\n> API would have the exact same problem, because it would let people do\n> exactly the same thing. And, going through this proposed API would\n> still be significantly more expensive than just accessing the bare\n> variables, because you'd at least have to do some kind of lookup based\n> on the GUC name\n\nI think the API ideas in [0] would not let people do exactly the same thing.\n\nThey would avoid exposing the bare variables to overwrite. Not that\nthere has been any plague of extensions going and overwriting GUCs,\nbut I think in some messages on this thread I detected a sense that\nin principle it's better if an API precludes it, and that makes sense\nto me.\n\nThe second idea also avoids the expense of name-based lookup (except once\nat extension initialization), and in fact minimizes the cost of obtaining\nthe current value when needed, by slightly increasing the infrequent cost\nof updating values.\n\nRegards,\n-Chap\n\n\n[0] https://www.postgresql.org/message-id/6123C425.3080409%40anastigmatix.net\n\n\n", "msg_date": "Mon, 23 Aug 2021 17:07:57 -0400", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "po 23. 8. 2021 v 23:08 odesílatel Chapman Flack <chap@anastigmatix.net>\nnapsal:\n\n> On 08/23/21 14:30, Robert Haas wrote:\n> > it seems likely that this proposed\n> > API would have the exact same problem, because it would let people do\n> > exactly the same thing. And, going through this proposed API would\n> > still be significantly more expensive than just accessing the bare\n> > variables, because you'd at least have to do some kind of lookup based\n> > on the GUC name\n>\n> I think the API ideas in [0] would not let people do exactly the same\n> thing.\n>\n> They would avoid exposing the bare variables to overwrite. Not that\n> there has been any plague of extensions going and overwriting GUCs,\n> but I think in some messages on this thread I detected a sense that\n> in principle it's better if an API precludes it, and that makes sense\n> to me.\n>\n> The second idea also avoids the expense of name-based lookup (except once\n> at extension initialization), and in fact minimizes the cost of obtaining\n> the current value when needed, by slightly increasing the infrequent cost\n> of updating values.\n>\n>\nThere are few GUC variables, where we need extra fast access - work_mem,\nencoding settings, and maybe an application name. For others I hadn't\nneeded to access it for over 20 years. But I understand that more complex\nextensions like timescaledb will use more internal GUC.\n\nMaybe a new light API based on enum identifiers instead of string\nidentifiers that ensure relatively fast access (and safe and secure) can be\na good solution. And for special variables, there can be envelope functions\nfor very fast access. But although the special interface, the\nresponsibility of the extension's author will not be less, and the C\nextensions will not be more trusted, so it is hard to say something about\npossible benefits. I am inclined to Robert's opinion, so the current state\nis not too bad, and maybe the best thing that is possible now is the\ndecreasing difference between supported platforms.\n\nRegards\n\nPavel\n\n\n>\n\npo 23. 8. 2021 v 23:08 odesílatel Chapman Flack <chap@anastigmatix.net> napsal:On 08/23/21 14:30, Robert Haas wrote:\n> it seems likely that this proposed\n> API would have the exact same problem, because it would let people do\n> exactly the same thing. And, going through this proposed API would\n> still be significantly more expensive than just accessing the bare\n> variables, because you'd at least have to do some kind of lookup based\n> on the GUC name\n\nI think the API ideas in [0] would not let people do exactly the same thing.\n\nThey would avoid exposing the bare variables to overwrite. Not that\nthere has been any plague of extensions going and overwriting GUCs,\nbut I think in some messages on this thread I detected a sense that\nin principle it's better if an API precludes it, and that makes sense\nto me.\n\nThe second idea also avoids the expense of name-based lookup (except once\nat extension initialization), and in fact minimizes the cost of obtaining\nthe current value when needed, by slightly increasing the infrequent cost\nof updating values.\nThere are few GUC variables, where we need extra fast access - work_mem, encoding settings, and maybe an application name. For others I hadn't needed to access it for over 20 years. But I understand that more complex extensions like timescaledb will use more internal GUC.Maybe a new light API based on enum identifiers instead of string identifiers that ensure relatively fast access (and safe and secure) can be a good solution. And for special variables, there can be envelope functions for very fast access. But although the special interface, the responsibility of the extension's author will not be less, and the C extensions will not be more trusted, so it is hard to say something about possible benefits. I am inclined to Robert's opinion, so the current state is not too bad, and maybe the best thing that is possible now is the decreasing difference between supported platforms. RegardsPavel", "msg_date": "Tue, 24 Aug 2021 06:35:56 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Tue, Aug 24, 2021 at 12:36 PM Pavel Stehule <pavel.stehule@gmail.com> wrote:\n>\n> There are few GUC variables, where we need extra fast access - work_mem, encoding settings, and maybe an application name. For others I hadn't needed to access it for over 20 years. But I understand that more complex extensions like timescaledb will use more internal GUC.\n\nNote that even trivial extensions require some other GUC access. For\ninstance any single extension that wants to aggregate data based on\nthe query_id has to store an array of query_id in shmem to know what a\nparallel worker is working on. On top of wasting memory and CPU, it\nalso means that computing the maximum number of backends in required.\nSo you need to recompute MaxBackends, which means access to multiple\nGUCs.\n\nUnfortunately the patch to expose the query_id didn't fix that problem\nas it only passes the top level query_id to the pararllel workers, not\nthe current one.\n\n\n", "msg_date": "Tue, 24 Aug 2021 12:58:37 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Sun, 22 Aug 2021 at 21:29, Julien Rouhaud <rjuju123@gmail.com> wrote:\n\n> On Sun, Aug 22, 2021 at 09:19:42AM -0400, Tom Lane wrote:\n> >\n> > Uh, no, it's exactly *not* clear. There are a lot of GUCs that are only\n> > of interest to particular subsystems. I do not see why being a GUC makes\n> > something automatically more interesting than any other global variable.\n> > Usually, the fact that one is global is only so the GUC machinery itself\n> > can get at it, otherwise it'd be static in the owning module.\n> >\n> > As for \"extensions should be able to get at the values\", the GUC\n> machinery\n> > already provides uniform mechanisms for doing that safely. Direct access\n> > to the variable's internal value would be unsafe in many cases.\n>\n> Then shouldn't we try to prevent direct access on all platforms rather than\n> only one?\n>\n\nYes. That's what I think we should be doing if we're not going to\nPGDLLIMPORT them all.\n\nThe current API is painful because it round-trips via a text\nrepresentation. We'd at least want some kind of\n\n GetConfigOptionBool(...)\n GetConfigOptionEnum(...)\n\netc.\n\nI don't understand the objection to marking them all PGDLLIMPORT anyway\nthough.\n\nAny pretense that Pg has any sort of public/private API divide is pure\nfantasy. Whether things are static or not, in public headers or \"internal\"\nheaders, etc, is nearly random. We have absolutely no API surface control\nsuch as __attribute__((visibility(\"hidden\"))) annotations, and proposals to\nadd them have been soundly rejected in the past.\n\nIf we have a defined API, where is it defined and annotated?\n\nIf we don't, then Windows being different and incompatible is a bug, and\nthat bug should be fixed.\n\nOn Sun, 22 Aug 2021 at 21:29, Julien Rouhaud <rjuju123@gmail.com> wrote:On Sun, Aug 22, 2021 at 09:19:42AM -0400, Tom Lane wrote:\n> \n> Uh, no, it's exactly *not* clear.  There are a lot of GUCs that are only\n> of interest to particular subsystems.  I do not see why being a GUC makes\n> something automatically more interesting than any other global variable.\n> Usually, the fact that one is global is only so the GUC machinery itself\n> can get at it, otherwise it'd be static in the owning module.\n> \n> As for \"extensions should be able to get at the values\", the GUC machinery\n> already provides uniform mechanisms for doing that safely.  Direct access\n> to the variable's internal value would be unsafe in many cases.\n\nThen shouldn't we try to prevent direct access on all platforms rather than\nonly one?Yes. That's what I think we should be doing if we're not going to PGDLLIMPORT them all.The current API is painful because it round-trips via a text representation. We'd at least want some kind of    GetConfigOptionBool(...)    GetConfigOptionEnum(...)etc.I don't understand the objection to marking them all PGDLLIMPORT anyway though.Any pretense that Pg has any sort of public/private API divide is pure fantasy. Whether things are static or not, in public headers or \"internal\" headers, etc,  is nearly random. We have absolutely no API surface control such as __attribute__((visibility(\"hidden\"))) annotations, and proposals to add them have been soundly rejected in the past.If we have a defined API, where is it defined and annotated?If we don't, then Windows being different and incompatible is a bug, and that bug should be fixed.", "msg_date": "Tue, 24 Aug 2021 13:02:42 +0800", "msg_from": "Craig Ringer <craig.ringer@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, 23 Aug 2021 at 22:15, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Bruce Momjian <bruce@momjian.us> writes:\n> > On Sun, Aug 22, 2021 at 09:29:01PM +0800, Julien Rouhaud wrote:\n> >> Then shouldn't we try to prevent direct access on all platforms rather\n> than\n> >> only one?\n>\n> > Agreed. If Julian says 99% of the non-export problems are GUCs, and we\n> > can just export them all, why not do it? We already export every global\n> > variable on Unix-like systems, and we have seen no downsides.\n>\n> By that argument, *every* globally-visible variable should be marked\n> PGDLLIMPORT. But the mere fact that two backend .c files need to access\n> some variable doesn't mean that we want any random bit of code doing so.\n>\n> And yes, I absolutely would prohibit extensions from accessing many\n> of them, if there were a reasonable way to do it. It would be a good\n> start towards establishing a defined API for extensions.\n>\n\nThere is: -fvisibility=hidden and __attribute__((visibility(\"default\"))) .\nOr if you prefer to explicitly mark private symbols, use\n__attribute__((visiblity(\"hidden\"))) .\n\nIn addition to API surface control this also gives you a smaller export\nsymbol table for faster dynamic linking, and it improves link-time\noptimization.\n\nI could've sworn I proposed its use in the past but I can't find a relevant\nlist thread except quite a recent one. All I can find is [1] . But that is\nwhere we should start: switch from a linker script for libpq to using\nPGDLLIMPORT (actually it'd be LIBPQDLLIMPORT) in libpq. When\n-DBUILDING_LIBPQ this would expand to __declspec(\"dllexport\") on Windows\nand __attribute__((visibility(\"default\"))) on gcc/clang. Otherwise it\nexpands to __declspec(\"dllimport\") on Windows and empty on other targets.\nThis would also be a good time to rename the confusingly named BUILDING_DLL\nmacro to BUILDING_POSTGRES .\n\nThe next step would be to have PGDLLIMPORT expand to\n__attribute__((visibility(\"default\"))) on gcc/clang when building the\nserver itself. This won't do anything by itself since all symbols are\nalready default visibility. But once the \"public API\" of both function and\ndata symbol is so-annotated, we could switch to building Pg with\n-fvisibility=hidden by default, and on Windows, we'd disable the linker\nscript that exports all functions using a generated .DEF file.\n\n\n[1]\nhttps://www.postgresql.org/message-id/CAMsr%2BYHa3TfA4rKtnZuzurwCSmxxXNQHFE3UE29BoDEQcwfuxA%40mail.gmail.com\n\nOn Mon, 23 Aug 2021 at 22:15, Tom Lane <tgl@sss.pgh.pa.us> wrote:Bruce Momjian <bruce@momjian.us> writes:\n> On Sun, Aug 22, 2021 at 09:29:01PM +0800, Julien Rouhaud wrote:\n>> Then shouldn't we try to prevent direct access on all platforms rather than\n>> only one?\n\n> Agreed.  If Julian says 99% of the non-export problems are GUCs, and we\n> can just export them all, why not do it?  We already export every global\n> variable on Unix-like systems, and we have seen no downsides.\n\nBy that argument, *every* globally-visible variable should be marked\nPGDLLIMPORT.  But the mere fact that two backend .c files need to access\nsome variable doesn't mean that we want any random bit of code doing so.\n\nAnd yes, I absolutely would prohibit extensions from accessing many\nof them, if there were a reasonable way to do it.  It would be a good\nstart towards establishing a defined API for extensions.There is: -fvisibility=hidden and __attribute__((visibility(\"default\"))) . Or if you prefer to explicitly mark private symbols, use __attribute__((visiblity(\"hidden\"))) .In addition to API surface control this also gives you a smaller export symbol table for faster dynamic linking, and it improves link-time optimization.I could've sworn I proposed its use in the past but I can't find a relevant list thread except quite a recent one. All I can find is [1] . But that is where we should start: switch from a linker script for libpq to using PGDLLIMPORT (actually  it'd be LIBPQDLLIMPORT) in libpq. When -DBUILDING_LIBPQ this would expand to __declspec(\"dllexport\") on Windows and __attribute__((visibility(\"default\"))) on gcc/clang. Otherwise it expands to __declspec(\"dllimport\") on Windows and empty on other targets. This would also be a good time to rename the confusingly named BUILDING_DLL macro to BUILDING_POSTGRES .The next step would be to have PGDLLIMPORT expand to __attribute__((visibility(\"default\"))) on gcc/clang when building the server itself. This won't do anything by itself since all symbols are already default visibility. But once the \"public API\" of both function and data symbol is so-annotated, we could switch to building Pg with -fvisibility=hidden by default, and on Windows, we'd disable the linker script that exports all functions using a generated .DEF file.[1] https://www.postgresql.org/message-id/CAMsr%2BYHa3TfA4rKtnZuzurwCSmxxXNQHFE3UE29BoDEQcwfuxA%40mail.gmail.com", "msg_date": "Tue, 24 Aug 2021 13:18:12 +0800", "msg_from": "Craig Ringer <craig.ringer@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Tue, 24 Aug 2021 at 02:31, Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Mon, Aug 23, 2021 at 11:40 AM Alvaro Herrera <alvherre@alvh.no-ip.org>\n> wrote:\n> > In that case, why not improve the API with functions that return the\n> > values in some native datatype? For scalars with native C types (int,\n> > floats, Boolean etc) this is easy enough; I bet it'll solve 99% of the\n> > problems or more.\n>\n> Sure, but ... why bother?\n>\n> The entire argument rests on the presumption that there is some harm\n> being done by people accessing the values directly, but I don't think\n> that's true. And, if it were true, it seems likely that this proposed\n> API would have the exact same problem, because it would let people do\n> exactly the same thing. And, going through this proposed API would\n> still be significantly more expensive than just accessing the bare\n> variables, because you'd at least have to do some kind of lookup based\n> on the GUC name to find the corresponding variable. It's just a\n> solution in search of a problem.\n>\n> Nothing bad happens when people write extensions that access GUC\n> variables directly. It works totally, completely fine. Except on\n> Windows.\n>\n\nNot only that, but postgres already exports every non-static function\nsymbol on both *nix and Windows, and every data symbol on *nix. A lot of\nthose function symbols are very internal and give anything that can call\nthem the ability to wreck absolute havoc on the server's state.\n\nThere is not even the thinnest pretense of Pg having a dedicated extension\nAPI or any sort of internal vs public API separation. This ongoing pain\nwith PGDLLIMPORT on Windows is hard to see as anything but an excuse to\nmake working with and supporting Windows harder because some of us don't\nlike it. I happen to rather dislike working with Windows myself, but I get\nto do it anyway, and I'd be very happy to remove this particular source of\npain.\n\nOn Tue, 24 Aug 2021 at 02:31, Robert Haas <robertmhaas@gmail.com> wrote:On Mon, Aug 23, 2021 at 11:40 AM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> In that case, why not improve the API with functions that return the\n> values in some native datatype?  For scalars with native C types (int,\n> floats, Boolean etc) this is easy enough; I bet it'll solve 99% of the\n> problems or more.\n\nSure, but ... why bother?\n\nThe entire argument rests on the presumption that there is some harm\nbeing done by people accessing the values directly, but I don't think\nthat's true. And, if it were true, it seems likely that this proposed\nAPI would have the exact same problem, because it would let people do\nexactly the same thing. And, going through this proposed API would\nstill be significantly more expensive than just accessing the bare\nvariables, because you'd at least have to do some kind of lookup based\non the GUC name to find the corresponding variable. It's just a\nsolution in search of a problem.\n\nNothing bad happens when people write extensions that access GUC\nvariables directly. It works totally, completely fine. Except on\nWindows.\nNot only that, but postgres already exports every non-static function symbol on both *nix and Windows, and every data symbol on *nix. A lot of those function symbols are very internal and give anything that can call them the ability to wreck absolute havoc on the server's state.There is not even the thinnest pretense of Pg having a dedicated extension API or any sort of internal vs public API separation. This ongoing pain with PGDLLIMPORT on Windows is hard to see as anything but an excuse to make working with and supporting Windows harder because some of us don't like it. I happen to rather dislike working with Windows myself, but I get to do it anyway, and I'd be very happy to remove this particular source of pain.", "msg_date": "Tue, 24 Aug 2021 13:21:51 +0800", "msg_from": "Craig Ringer <craig.ringer@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Tue, 24 Aug 2021 at 13:21, Craig Ringer <craig.ringer@enterprisedb.com>\nwrote:\n\n>\n> There is not even the thinnest pretense of Pg having a dedicated extension\n> API or any sort of internal vs public API separation.\n>\n\nOh, and if we do want such a separation, we'll need to introduce a MUCH\nlower-pain-and-overhead way to get related patches in. Otherwise it'll take\ndecades to add any necessary function wrappers for currently exported data\nsymbols, add necessary hooks, wrap or hide internal symbols and state, etc.\n\nBut ... what is the actual goal and expected outcome of such a hypothetical\npublic/private API separation?\n\nIt won't help meaningfully with server maintenance: We already break\nextensions freely in major releases, and sometimes even minor releases. We\ndon't make any stable API promise at all. So any argument that it would\nmake maintenance of the core server easier is weak at best.\n\nIt won't help protect server runtime stability: The server is written in C,\nand makes heavy use of non-opaque / non-hidden types. Many of which would\nnot be practical to hide without enormous refactoring if at all. Writing\nany sort of \"safe\" C API is very difficult even when the exposed\nfunctionality is very narrow and well defined. Even then such an API can\nonly help prevent inadvertent mistakes, since C programs are free to grovel\naround in memory. Look at the mess with EXPORT_SYMBOL_GPL in the kernel for\njust how ugly that can get. So I don't think there's any realistic way to\nclaim that narrowing the exposed API surface would make it safer to load\nand run extensions that the user has not separately checked and reviewed or\nobtained from a trusted source with robust testing practices. Certainly it\noffers no benefit at all against a bad actor.\n\nIt won't make it safer to use untrusted extensions.\n\nWhat will it do? Not much, in the short term, except cripple existing\nextensions or add a pile of questionably useful code annotations. The only\nreal benefits I see are some improvement in link-time optimization and\nexport symbol table size. Both of which are nice, but IMO not worth the\npain by themselves for a pure C program. In C++, with its enormous symbol\ntables it's absolutely worth it. But not really for Pg.\n\nTo be clear, I actually love the idea of starting to define a solid public\nAPI, with API, ABI and semantic promises and associated tests. But to say\nit's a nontrivial amount of work is an enormous understatement. And unless\ndone by an existing committer who is trusted to largely define a\nprovisional API without bike-shedding and arguing the merits of every\nsingle part of it, it's nearly impossible to do with the way Pg is\ncurrently developed.\n\nIt's completely beyond me why it's OK to export all function symbols on\nWindows, but not all data symbols. Or why it's OK to export all data\nsymbols on *nix, but not on Windows.\n\nOn Tue, 24 Aug 2021 at 13:21, Craig Ringer <craig.ringer@enterprisedb.com> wrote:There is not even the thinnest pretense of Pg having a dedicated extension API or any sort of internal vs public API separation.Oh, and if we do want such a separation, we'll need to introduce a MUCH lower-pain-and-overhead way to get related patches in. Otherwise it'll take decades to add any necessary function wrappers for currently exported data symbols, add necessary hooks, wrap or hide internal symbols and state, etc.But ... what is the actual goal and expected outcome of such a hypothetical public/private API separation?It won't help meaningfully with server maintenance: We already break extensions freely in major releases, and sometimes even minor releases. We don't make any stable API promise at all. So any argument that it would make maintenance of the core server easier is weak at best.It won't help protect server runtime stability: The server is written in C, and makes heavy use of non-opaque / non-hidden types. Many of which would not be practical to hide without enormous refactoring if at all. Writing any sort of \"safe\" C API is very difficult even when the exposed functionality is very narrow and well defined. Even then such an API can only help prevent inadvertent mistakes, since C programs are free to grovel around in memory. Look at the mess with EXPORT_SYMBOL_GPL in the kernel for just how ugly that can get. So I don't think there's any realistic way to claim that narrowing the exposed API surface would make it safer to load and run extensions that the user has not separately checked and reviewed or obtained from a trusted source with robust testing practices. Certainly it offers no benefit at all against a bad actor.It won't make it safer to use untrusted extensions.What will it do? Not much, in the short term, except cripple existing extensions or add a pile of questionably useful code annotations. The only real benefits I see are some improvement in link-time optimization and export symbol table size. Both of which are nice, but IMO not worth the pain by themselves for a pure C program. In C++, with its enormous symbol tables it's absolutely worth it. But not really for Pg.To be clear, I actually love the idea of starting to define a solid public API, with API, ABI and semantic promises and associated tests. But to say it's a nontrivial amount of work is an enormous understatement. And unless done by an existing committer who is trusted to largely define a provisional API without bike-shedding and arguing the merits of every single part of it, it's nearly impossible to do with the way Pg is currently developed.It's completely beyond me why it's OK to export all function symbols on Windows, but not all data symbols. Or why it's OK to export all data symbols on *nix, but not on Windows.", "msg_date": "Tue, 24 Aug 2021 13:35:23 +0800", "msg_from": "Craig Ringer <craig.ringer@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Tue, 24 Aug 2021 at 05:08, Chapman Flack <chap@anastigmatix.net> wrote:\n\n> On 08/23/21 14:30, Robert Haas wrote:\n> > it seems likely that this proposed\n> > API would have the exact same problem, because it would let people do\n> > exactly the same thing. And, going through this proposed API would\n> > still be significantly more expensive than just accessing the bare\n> > variables, because you'd at least have to do some kind of lookup based\n> > on the GUC name\n>\n> I think the API ideas in [0] would not let people do exactly the same\n> thing.\n>\n> They would avoid exposing the bare variables to overwrite. Not that\n> there has been any plague of extensions going and overwriting GUCs,\n> but I think in some messages on this thread I detected a sense that\n> in principle it's better if an API precludes it, and that makes sense\n> to me.\n>\n> The second idea also avoids the expense of name-based lookup (except once\n> at extension initialization), and in fact minimizes the cost of obtaining\n> the current value when needed, by slightly increasing the infrequent cost\n> of updating values.\n>\n\nI'd be generally in favour of something that reduced our reliance on the\ncurrent chaotic and inconsistent jumble of globals which are a semi-random\ncombination of compilation-unit-scoped, globally-scoped-except-on-Windows\nand globally scoped.\n\nTackling GUCs would be a good start. Especially given the number of GUCs\nwhere the actual GUC value isn't the state that anyone should be\ninteracting with directly since a hook maintains the \"real\" state derived\nfrom the GUC storage.\n\nAnd preventing direct writes to GUCs seems like a clearly correct thing to\ndo.\n\nSome consideration of performance would be important for some of the hotter\nGUCs, of course, but most extensions won't be hammering most GUC access a\nlot.\n\nOn Tue, 24 Aug 2021 at 05:08, Chapman Flack <chap@anastigmatix.net> wrote:On 08/23/21 14:30, Robert Haas wrote:\n> it seems likely that this proposed\n> API would have the exact same problem, because it would let people do\n> exactly the same thing. And, going through this proposed API would\n> still be significantly more expensive than just accessing the bare\n> variables, because you'd at least have to do some kind of lookup based\n> on the GUC name\n\nI think the API ideas in [0] would not let people do exactly the same thing.\n\nThey would avoid exposing the bare variables to overwrite. Not that\nthere has been any plague of extensions going and overwriting GUCs,\nbut I think in some messages on this thread I detected a sense that\nin principle it's better if an API precludes it, and that makes sense\nto me.\n\nThe second idea also avoids the expense of name-based lookup (except once\nat extension initialization), and in fact minimizes the cost of obtaining\nthe current value when needed, by slightly increasing the infrequent cost\nof updating values.I'd be generally in favour of something that reduced our reliance on the current chaotic and inconsistent jumble of globals which are a semi-random combination of compilation-unit-scoped, globally-scoped-except-on-Windows and globally scoped.Tackling GUCs would be a good start. Especially given the number of GUCs where the actual GUC value isn't the state that anyone should be interacting with directly since a hook maintains the \"real\" state derived from the GUC storage.And preventing direct writes to GUCs seems like a clearly correct thing to do.Some consideration of performance would be important for some of the hotter GUCs, of course, but most extensions won't be hammering most GUC access a lot.", "msg_date": "Tue, 24 Aug 2021 13:47:14 +0800", "msg_from": "Craig Ringer <craig.ringer@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, 23 Aug 2021 at 22:45, Julien Rouhaud <rjuju123@gmail.com> wrote:\n\n> On Mon, Aug 23, 2021 at 10:22 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >\n> > Bruce Momjian <bruce@momjian.us> writes:\n> > > On Mon, Aug 23, 2021 at 10:15:04AM -0400, Tom Lane wrote:\n> > >> By that argument, *every* globally-visible variable should be marked\n> > >> PGDLLIMPORT. But the mere fact that two backend .c files need to\n> access\n> >\n> > > No, Julien says 99% need only the GUCs, so that is not the argument I\n> am\n> > > making.\n> >\n> > That's a claim unbacked by any evidence that I've seen. More to\n> > the point, we already have a mechanism that extensions can/should\n> > use to read and write GUC settings, and it's not direct access.\n>\n> I clearly didn't try all single extension available out there. It's\n> excessively annoying to compile extensions on Windows, and also I\n> don't have a lot of dependencies installed so there are some that I\n> wasn't able to test since I'm lacking some other lib and given my\n> absolute lack of knowledge of that platform I didn't spent time trying\n> to install those.\n>\n>\nPlenty of them are closed too.\n\nWhile that's not the Pg community's problem, as such, it'd be nice not to\narbitrarily break them all for no actual benefit.\n\nOn Mon, 23 Aug 2021 at 22:45, Julien Rouhaud <rjuju123@gmail.com> wrote:On Mon, Aug 23, 2021 at 10:22 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Bruce Momjian <bruce@momjian.us> writes:\n> > On Mon, Aug 23, 2021 at 10:15:04AM -0400, Tom Lane wrote:\n> >> By that argument, *every* globally-visible variable should be marked\n> >> PGDLLIMPORT.  But the mere fact that two backend .c files need to access\n>\n> > No, Julien says 99% need only the GUCs, so that is not the argument I am\n> > making.\n>\n> That's a claim unbacked by any evidence that I've seen.  More to\n> the point, we already have a mechanism that extensions can/should\n> use to read and write GUC settings, and it's not direct access.\n\nI clearly didn't try all single extension available out there.  It's\nexcessively annoying to compile extensions on Windows, and also I\ndon't have a lot of dependencies installed so there are some that I\nwasn't able to test since I'm lacking some other lib and given my\nabsolute lack of knowledge of that platform I didn't spent time trying\nto install those.\nPlenty of them are closed too.While that's not the Pg community's problem, as such, it'd be nice not to arbitrarily break them all for no actual benefit.", "msg_date": "Tue, 24 Aug 2021 13:49:08 +0800", "msg_from": "Craig Ringer <craig.ringer@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On 23.08.21 16:47, Julien Rouhaud wrote:\n> On Mon, Aug 23, 2021 at 10:36 PM Bruce Momjian <bruce@momjian.us> wrote:\n>>\n>> So the problem is that extensions only _need_ to use that API on\n>> Windows, so many initially don't, or that the API is too limited?\n> \n> The inconvenience with that API is that it's only returning c strings,\n> so you gave to convert it back to the original datatype. That's\n> probably why most of the extensions simply read from the original\n> exposed variable rather than using the API, because they're usually\n> written on Linux or similar, not because they want to mess up the\n> stored value.\n\nIf there were an API, then in-core code should use it as well.\n\nIf, for example, an extension wanted to define a \"float16\" type, then it \nshould be able to access extra_float_digits in the *same way* as \nfloat4out() and float8out() can access it. This is clearly not possible \ntoday.\n\n\n", "msg_date": "Tue, 24 Aug 2021 10:28:24 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Tue, Aug 24, 2021 at 4:28 AM Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n> If there were an API, then in-core code should use it as well.\n\n...which is presumably never going to happen, because the performance\ncost would, I think, be quite terrible. If you really had to force\neverything through an API, I think what you'd want to do is define an\nAPI where code can look up a handle object for a GUC using the name of\nthe GUC, and then hold onto a pointer to the handle and use that for\nfuture accesses, so that you don't have to keep incurring the expense\nof a hash table hit on every access. But even if you did that,\npreventing \"unauthorized\" writes to GUC variables would require a\nfunction call for every access. That function would be pretty trivial,\nbut it would have to exist, and...\n\n> If, for example, an extension wanted to define a \"float16\" type, then it\n> should be able to access extra_float_digits in the *same way* as\n> float4out() and float8out() can access it. This is clearly not possible\n> today.\n\n...if you used it for something like this, it would probably show up\nin the profile, and we would get demands to remove that API and allow\ndirect access to the variables, which is all anybody is asking for\nhere anyway, and which is what pretty much everyone, whether they\ndevelop for core or some extension, does and wants to do.\n\nThis also brings me to another point, which is that I do not think\nthere is anyone who actually wants an API like this. I believe that\nextension developers find it rather convenient that they can make use\nof all of the backend functions and variables that PostgreSQL exposes,\nand that a lot of them would be deeply unhappy if we removed that\naccess. As an occasional extension maintainer myself, I know I would\nbe. And, as Craig quite rightly points out upthread, we would not get\nanything in return for making those people unhappy. I don't know why\nwe would even consider doing something that would benefit nobody,\ngreatly inconvenience some people, and generally stifle innovation in\nthe PostgreSQL ecosystem.\n\nAdding PGDLLIMPORT markings, on the other hand, would hurt nobody, be\nvery convenient for some people, and encourage innovation in the\nPostgreSQL ecosystem.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 24 Aug 2021 14:28:02 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On 08/24/21 14:28, Robert Haas wrote:\n\n> cost would, I think, be quite terrible. If you really had to force\n> everything through an API, I think what you'd want to do is define an\n> API where code can look up a handle object for a GUC using the name of\n> the GUC, and then hold onto a pointer to the handle and use that for\n> future accesses, so that you don't have to keep incurring the expense\n> of a hash table hit on every access. But even if you did that,\n> preventing \"unauthorized\" writes to GUC variables would require a\n> function call for every access.\n\nI don't think that's true of the second proposal in [0]. I don't foresee\na noticeable runtime cost unless there is a plausible workload that\ninvolves very frequent updates to GUC settings that are also of interest\nto a bunch of extensions. Maybe I'll take a stab at a POC.\n\nRegards,\n-Chap\n\n[0] https://www.postgresql.org/message-id/6123C425.3080409%40anastigmatix.net\n\n\n", "msg_date": "Tue, 24 Aug 2021 14:52:23 -0400", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Tue, Aug 24, 2021 at 2:52 PM Chapman Flack <chap@anastigmatix.net> wrote:\n> I don't think that's true of the second proposal in [0]. I don't foresee\n> a noticeable runtime cost unless there is a plausible workload that\n> involves very frequent updates to GUC settings that are also of interest\n> to a bunch of extensions. Maybe I'll take a stab at a POC.\n\nI'm not sure I fully understand that proposal, but I find it hard to\nbelieve that we would seriously consider replacing every direct GUC\nreference in the backend with something that goes through an API. Even\nif didn't hurt performance, I think it would uglify the code a whole\nlot.\n\nAnd as Peter says, if we're not going to do that, then it's not clear\nwhy extensions should have to.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 24 Aug 2021 15:12:45 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On 08/24/21 15:12, Robert Haas wrote:\n> I find it hard to\n> believe that we would seriously consider replacing every direct GUC\n> reference in the backend with something that goes through an API.\n\nPeter may have advocated for that kind of across-the-board adoption;\nmy leaning is more to add an API that /can/ be adopted, initially with\nseparately-linked extensions as the audience. Nothing would stop it being\nused in core as well, but no reason to change any site where it did not\noffer an advantage.\n\nI generally tend to be an incrementalist.\n\nRegards,\n-Chap\n\n\n", "msg_date": "Tue, 24 Aug 2021 15:36:22 -0400", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Tue, Aug 24, 2021 at 3:36 PM Chapman Flack <chap@anastigmatix.net> wrote:\n> Peter may have advocated for that kind of across-the-board adoption;\n> my leaning is more to add an API that /can/ be adopted, initially with\n> separately-linked extensions as the audience. Nothing would stop it being\n> used in core as well, but no reason to change any site where it did not\n> offer an advantage.\n>\n> I generally tend to be an incrementalist.\n\nSure, me too, but the point for me is that there doesn't seem to be a\nshred of a reason to go this way at all. We've turned a discussion\nabout adding PGDLLIMPORT, which ought to be totally uncontroversial,\ninto some kind of a discussion about adding an API layer that no one\nwants to prevent a hypothetical failure mode not in evidence.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 24 Aug 2021 16:31:32 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On 08/24/21 16:31, Robert Haas wrote:\n\n> about adding PGDLLIMPORT, which ought to be totally uncontroversial,\n\nThe thing is, I think I have somewhere a list of all the threads on this\ntopic that I've read through since the first time I had to come with my own\nhat in hand asking for a PGDLLIMPORT on something, years ago now, and\nI don't think I have ever seen one where it was as uncontroversial\nas you suggest.\n\nIn each iteration, I think I've also seen a countervailing view expressed\nin favor of looking into whether globals visibility could be further\n/reduced/. Maybe that view is slowly losing adherents? I don't know; it\ndid get advanced again by some in this thread.\n\nThe positions seem to routinely fall into two boxes:\n\n* Let's look into that, it would be a step toward having a more defined API\n\n* No, what we have now is so far from a defined API that there's nothing\n worth stepping toward.\n\nThe situation seems intermediate to me. The current condition is clearly\nsomething that organically grew without a strong emphasis on defining API.\n\nOn the other hand, there are many corners of it that show evidence of\nthought about encapsulation and API by the developers of those corners.\n\nIt seems to me like the kind of setting where incrementalists can find\nroom for small moves.\n\nRegards,\n-Chap\n\n\n", "msg_date": "Tue, 24 Aug 2021 17:06:54 -0400", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Tue, Aug 24, 2021 at 04:31:32PM -0400, Robert Haas wrote:\n> On Tue, Aug 24, 2021 at 3:36 PM Chapman Flack <chap@anastigmatix.net> wrote:\n> > Peter may have advocated for that kind of across-the-board adoption;\n> > my leaning is more to add an API that /can/ be adopted, initially with\n> > separately-linked extensions as the audience. Nothing would stop it being\n> > used in core as well, but no reason to change any site where it did not\n> > offer an advantage.\n> >\n> > I generally tend to be an incrementalist.\n> \n> Sure, me too, but the point for me is that there doesn't seem to be a\n> shred of a reason to go this way at all. We've turned a discussion\n> about adding PGDLLIMPORT, which ought to be totally uncontroversial,\n> into some kind of a discussion about adding an API layer that no one\n> wants to prevent a hypothetical failure mode not in evidence.\n\n+1\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Tue, 24 Aug 2021 17:26:20 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Tue, Aug 24, 2021 at 05:06:54PM -0400, Chapman Flack wrote:\n> On 08/24/21 16:31, Robert Haas wrote:\n> > about adding PGDLLIMPORT, which ought to be totally uncontroversial,\n> \n> The thing is, I think I have somewhere a list of all the threads on this\n> topic that I've read through since the first time I had to come with my own\n> hat in hand asking for a PGDLLIMPORT on something, years ago now, and\n> I don't think I have ever seen one where it was as uncontroversial\n> as you suggest.\n\nThe \"ought\" above is a load-bearing word. Nonetheless, here's a case, also\ninvolving GUCs, where it was uncontroversial:\nhttps://postgr.es/m/flat/20171120200230.iwcmptwznbvl6y4c%40alap3.anarazel.de\n\n\n", "msg_date": "Tue, 24 Aug 2021 22:32:19 -0700", "msg_from": "Noah Misch <noah@leadboat.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Tue, Aug 24, 2021 at 5:06 PM Chapman Flack <chap@anastigmatix.net> wrote:\n> The thing is, I think I have somewhere a list of all the threads on this\n> topic that I've read through since the first time I had to come with my own\n> hat in hand asking for a PGDLLIMPORT on something, years ago now, and\n> I don't think I have ever seen one where it was as uncontroversial\n> as you suggest.\n\nIt does tend to be controversial, but I think that's basically only\nbecause Tom Lane has reservations about it. I think if Tom dropped his\nopposition to this, nobody else would really care. And I think that\nwould be a good thing for the project.\n\n> In each iteration, I think I've also seen a countervailing view expressed\n> in favor of looking into whether globals visibility could be further\n> /reduced/.\n\nBut, like I say, that's only a view that gets advanced as a reason not\nto mark things PGDLLIMPORT. Nobody ever wants that thing for its own\nsake. I think it's a complete red herring.\n\nIf and when somebody wants to make a serious proposal to do something\nlike that, it can be considered on its own merits. But between now and\nthen, refusing to make things work on Windows as they do on Linux does\nnot benefit anyone. A ton of work has been made into making PostgreSQL\nportable over the years, and abandoning it in just this one case is\nunreasonable.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 25 Aug 2021 10:05:54 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Wed, Aug 25, 2021 at 4:06 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> On Tue, Aug 24, 2021 at 5:06 PM Chapman Flack <chap@anastigmatix.net> wrote:\n> > The thing is, I think I have somewhere a list of all the threads on this\n> > topic that I've read through since the first time I had to come with my own\n> > hat in hand asking for a PGDLLIMPORT on something, years ago now, and\n> > I don't think I have ever seen one where it was as uncontroversial\n> > as you suggest.\n>\n> It does tend to be controversial, but I think that's basically only\n> because Tom Lane has reservations about it. I think if Tom dropped his\n> opposition to this, nobody else would really care. And I think that\n> would be a good thing for the project.\n\n\nI have only one consideration about it, and that's a technical one :)\n\nDoes this in some way have an effect on the size of the binary and/or\nthe time it takes to load it?\n\nI ask, because IIRC back in the prehistoric days, adding all the\n*functions* to the list of exports had a very significant impact on\nthe size of the binary, and some (but not very large) impact on the\nloading time. Of course, we had to do that so that even our own\nlibraries would probably load. And at the time it was decided that we\ndefinitely wanted to export all functions and not just the ones that\nwe would somehow define as an API.\n\nNow, I'm pretty sure that the GUCs are few enough that this should\nhave no measurable effect on size/load time, but it's something that\nshould be verified.\n\nBut in particular, both on that argument, and on the general\nmaintenance argument, I have a very hard time seeing how exporting the\nGUC variables would be any worse than exporting the many hundreds of\nfunctions we already export.\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/\n Work: https://www.redpill-linpro.com/\n\n\n", "msg_date": "Wed, 25 Aug 2021 16:35:33 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Magnus Hagander <magnus@hagander.net> writes:\n> On Wed, Aug 25, 2021 at 4:06 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>> It does tend to be controversial, but I think that's basically only\n>> because Tom Lane has reservations about it. I think if Tom dropped his\n>> opposition to this, nobody else would really care. And I think that\n>> would be a good thing for the project.\n\n> But in particular, both on that argument, and on the general\n> maintenance argument, I have a very hard time seeing how exporting the\n> GUC variables would be any worse than exporting the many hundreds of\n> functions we already export.\n\nMy beef about it has nothing to do with binary-size concerns, although\nthat is an interesting angle. (I wonder whether marking a variable\nPGDLLIMPORT has any negative effect on the cost of accessing it from\nwithin the core code?) Rather, I'm unhappy with spreading even more\nMicrosoft-droppings all over our source. If there were some way to\njust do this automatically for all global variables without any source\nchanges, I'd be content with that. That would *really* make the\nplatforms more nearly equivalent.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 25 Aug 2021 10:41:14 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Wed, Aug 25, 2021 at 4:41 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Magnus Hagander <magnus@hagander.net> writes:\n> > On Wed, Aug 25, 2021 at 4:06 PM Robert Haas <robertmhaas@gmail.com> wrote:\n> >> It does tend to be controversial, but I think that's basically only\n> >> because Tom Lane has reservations about it. I think if Tom dropped his\n> >> opposition to this, nobody else would really care. And I think that\n> >> would be a good thing for the project.\n>\n> > But in particular, both on that argument, and on the general\n> > maintenance argument, I have a very hard time seeing how exporting the\n> > GUC variables would be any worse than exporting the many hundreds of\n> > functions we already export.\n>\n> My beef about it has nothing to do with binary-size concerns, although\n> that is an interesting angle. (I wonder whether marking a variable\n> PGDLLIMPORT has any negative effect on the cost of accessing it from\n> within the core code?)\n\nIt should have no effect on local code.\n\nPGDLLIMPORT turns into \"__declspec (dllexport)\" when building the\nbackend, which should have no effect on imports\n\n(it turns into __declspec (dllimport) when building a frontend only,\nbut that's why we need it in the headers, iirc)\n\nThe only overhead I've seen discussions about int he docs around that\nis the overhead of exporting by name vs exporting by ordinal.\n\n\n> Rather, I'm unhappy with spreading even more\n> Microsoft-droppings all over our source. If there were some way to\n> just do this automatically for all global variables without any source\n> changes, I'd be content with that. That would *really* make the\n> platforms more nearly equivalent.\n\nActually, ti's clearly been a while since I dug into this\n\nAFAICT we *do* actually export all the data symbols as well? At least\nin the MSVC build where we use gendef.pl? Specifically, see\na5eed4d770.\n\nThe thing we need the PGDLLIMPORT definition for is to *import* them\non the other end?\n\n--\n Magnus Hagander\n Me: https://www.hagander.net/\n Work: https://www.redpill-linpro.com/\n\n\n", "msg_date": "Wed, 25 Aug 2021 17:00:12 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On 2021-Aug-25, Magnus Hagander wrote:\n\n> The thing we need the PGDLLIMPORT definition for is to *import* them\n> on the other end?\n\nOh ... so modules that are willing to cheat can include their own\ndeclarations of the variables they need, and mark them __declspec\n(dllimport)?\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"The Gord often wonders why people threaten never to come back after they've\nbeen told never to return\" (www.actsofgord.com)\n\n\n", "msg_date": "Wed, 25 Aug 2021 13:51:17 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Thu, Aug 26, 2021 at 1:51 AM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>\n> On 2021-Aug-25, Magnus Hagander wrote:\n>\n> > The thing we need the PGDLLIMPORT definition for is to *import* them\n> > on the other end?\n>\n> Oh ... so modules that are willing to cheat can include their own\n> declarations of the variables they need, and mark them __declspec\n> (dllimport)?\n\nI just tried and msvc doesn't like it. It errors out with a C2370\nerror \"redefinition; different storage class\". According to\nhttps://docs.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/compiler-error-c2370\nchanging __declspec() on the other side is not possible.\n\n\n", "msg_date": "Thu, 26 Aug 2021 09:38:28 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Wed, Aug 25, 2021 at 10:41:14AM -0400, Tom Lane wrote:\n> Magnus Hagander <magnus@hagander.net> writes:\n> > On Wed, Aug 25, 2021 at 4:06 PM Robert Haas <robertmhaas@gmail.com> wrote:\n> >> It does tend to be controversial, but I think that's basically only\n> >> because Tom Lane has reservations about it. I think if Tom dropped his\n> >> opposition to this, nobody else would really care. And I think that\n> >> would be a good thing for the project.\n> \n> > But in particular, both on that argument, and on the general\n> > maintenance argument, I have a very hard time seeing how exporting the\n> > GUC variables would be any worse than exporting the many hundreds of\n> > functions we already export.\n> \n> My beef about it has nothing to do with binary-size concerns, although\n> that is an interesting angle. (I wonder whether marking a variable\n> PGDLLIMPORT has any negative effect on the cost of accessing it from\n> within the core code?) Rather, I'm unhappy with spreading even more\n> Microsoft-droppings all over our source. If there were some way to\n> just do this automatically for all global variables without any source\n> changes, I'd be content with that. That would *really* make the\n> platforms more nearly equivalent.\n\nOK, so the big question is how can we minimize the code impact of this\nfeature? Can we add some kind of checking so we don't forget to mark\nanything? Can we automate this somehow?\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Wed, 25 Aug 2021 22:48:58 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Thu, Aug 26, 2021 at 3:38 AM Julien Rouhaud <rjuju123@gmail.com> wrote:\n>\n> On Thu, Aug 26, 2021 at 1:51 AM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> >\n> > On 2021-Aug-25, Magnus Hagander wrote:\n> >\n> > > The thing we need the PGDLLIMPORT definition for is to *import* them\n> > > on the other end?\n> >\n> > Oh ... so modules that are willing to cheat can include their own\n> > declarations of the variables they need, and mark them __declspec\n> > (dllimport)?\n>\n> I just tried and msvc doesn't like it. It errors out with a C2370\n> error \"redefinition; different storage class\". According to\n> https://docs.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/compiler-error-c2370\n> changing __declspec() on the other side is not possible.\n\nYeah, but that does move the problem to the other side doesn't it? So\nif you (as a pure test of course) were to remove the variable\ncompletely from the included header and just declare it manually with\nPGDLLSPEC in your file, it should work?\n\nUgly as it is, I wonder if there's a chance we could just process all\nthe headers at install times and inject the PGDLLIMPORT. We know which\nsymvols it is on account of what we're getting in the DEF file.\n\nNot saying that's not a very ugly solution, but it might work?\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/\n Work: https://www.redpill-linpro.com/\n\n\n", "msg_date": "Thu, 26 Aug 2021 21:42:09 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Thu, Aug 26, 2021 at 3:42 PM Magnus Hagander <magnus@hagander.net> wrote:\n> Ugly as it is, I wonder if there's a chance we could just process all\n> the headers at install times and inject the PGDLLIMPORT. We know which\n> symvols it is on account of what we're getting in the DEF file.\n>\n> Not saying that's not a very ugly solution, but it might work?\n\nIf it's ugly, that might mean it's a bad idea and we shouldn't do it\n... but if it can be made not-too-ugly, it would certainly be nice to\nbe able to stop worrying about this.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 26 Aug 2021 15:57:14 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "\nOn 8/26/21 3:57 PM, Robert Haas wrote:\n> On Thu, Aug 26, 2021 at 3:42 PM Magnus Hagander <magnus@hagander.net> wrote:\n>> Ugly as it is, I wonder if there's a chance we could just process all\n>> the headers at install times and inject the PGDLLIMPORT. We know which\n>> symvols it is on account of what we're getting in the DEF file.\n>>\n>> Not saying that's not a very ugly solution, but it might work?\n> If it's ugly, that might mean it's a bad idea and we shouldn't do it\n> ... but if it can be made not-too-ugly, it would certainly be nice to\n> be able to stop worrying about this.\n>\n\nHow is this going to affect msys builds? No gendef there IIRC. I guess\nsome similar procedure might be possible ...\n\n\ncheers\n\n\nandrew\n\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Thu, 26 Aug 2021 17:10:39 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Thu, Aug 26, 2021 at 05:10:39PM -0400, Andrew Dunstan wrote:\n> On 8/26/21 3:57 PM, Robert Haas wrote:\n>> On Thu, Aug 26, 2021 at 3:42 PM Magnus Hagander <magnus@hagander.net> wrote:\n>>> Ugly as it is, I wonder if there's a chance we could just process all\n>>> the headers at install times and inject the PGDLLIMPORT. We know which\n>>> symvols it is on account of what we're getting in the DEF file.\n>>> Not saying that's not a very ugly solution, but it might work?\n\nI missed the word \"install\" first here :)\n\n>> If it's ugly, that might mean it's a bad idea and we shouldn't do it\n>> ... but if it can be made not-too-ugly, it would certainly be nice to\n>> be able to stop worrying about this.\n> \n> How is this going to affect msys builds? No gendef there IIRC. I guess\n> some similar procedure might be possible ...\n\nWouldn't that be needed for cygwin as well? If we go down to enable\nthat for a maximum number of parameters, I would really agree for\ndoing things so as this never gets forgotten for new parameters and we\ndon't have to discuss the matter anymore. With all that in mind, that\nwould mean a new perl script that does the job, callable by both MSVC\nand normal make builds. But we have nothing that does a manipulation\nof the installation contents. And couldn't it be a problem if an\ninstallation is overwritten, updated or upgradedd, where there may be\ncontents not coming from the in-core build process but from some\nextension?\n--\nMichael", "msg_date": "Fri, 27 Aug 2021 08:57:36 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Fri, Aug 27, 2021 at 3:42 AM Magnus Hagander <magnus@hagander.net> wrote:\n>\n> Yeah, but that does move the problem to the other side doesn't it? So\n> if you (as a pure test of course) were to remove the variable\n> completely from the included header and just declare it manually with\n> PGDLLSPEC in your file, it should work?\n>\n> Ugly as it is, I wonder if there's a chance we could just process all\n> the headers at install times and inject the PGDLLIMPORT. We know which\n> symvols it is on account of what we're getting in the DEF file.\n>\n> Not saying that's not a very ugly solution, but it might work?\n\nIt's apparently not enough. I tried with autovacuum_max_workers GUC,\nand it still errors out.\nIf I add a PGDLLIMPORT, there's a link error when trying to access the variable:\nerror LNK2019: unresolved external symbol __imp_autovacuum_max_workers\nreferenced in function...\n\nI think that it means that msvc tries to link that to a DLL while it's\nexpected to be in postgres.lib as the __imp_ prefix is added in that\ncase.\n\nIf I use PGDLLEXPORT I simply get:\nerror LNK2001: unresolved external symbol aytovacuum_max_workers\n\n\n", "msg_date": "Fri, 27 Aug 2021 08:59:13 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Wed, 25 Aug 2021 at 03:13, Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Tue, Aug 24, 2021 at 2:52 PM Chapman Flack <chap@anastigmatix.net>\n> wrote:\n> > I don't think that's true of the second proposal in [0]. I don't foresee\n> > a noticeable runtime cost unless there is a plausible workload that\n> > involves very frequent updates to GUC settings that are also of interest\n> > to a bunch of extensions. Maybe I'll take a stab at a POC.\n>\n> I'm not sure I fully understand that proposal, but I find it hard to\n> believe that we would seriously consider replacing every direct GUC\n> reference in the backend with something that goes through an API. Even\n> if didn't hurt performance, I think it would uglify the code a whole\n> lot.\n>\n\nIt'd probably have to be something that resolves the GUC storage addresses\nat compile-time or once at runtime, if it's going to be used by core code.\nWhile some code doesn't hit a lot of GUCs, some *really* hammers some\ncommon GUCs.\n\nThere are various issues with cache lines and pointer chasing that are\nbeyond my low-level fu at work here. Adding a level of pointer indirection\ncan be very expensive in the wrong situations.\n\nSo you're probably looking at some kind of mess with token pasting, macros\nand static inlines. Ew.\n\nOn Wed, 25 Aug 2021 at 03:13, Robert Haas <robertmhaas@gmail.com> wrote:On Tue, Aug 24, 2021 at 2:52 PM Chapman Flack <chap@anastigmatix.net> wrote:\n> I don't think that's true of the second proposal in [0]. I don't foresee\n> a noticeable runtime cost unless there is a plausible workload that\n> involves very frequent updates to GUC settings that are also of interest\n> to a bunch of extensions. Maybe I'll take a stab at a POC.\n\nI'm not sure I fully understand that proposal, but I find it hard to\nbelieve that we would seriously consider replacing every direct GUC\nreference in the backend with something that goes through an API. Even\nif didn't hurt performance, I think it would uglify the code a whole\nlot.It'd probably have to be something that resolves the GUC storage addresses at compile-time or once at runtime, if it's going to be used by core code. While some code doesn't hit a lot of GUCs, some *really* hammers some common GUCs.There are various issues with cache lines and pointer chasing that are beyond my low-level fu at work here. Adding a level of pointer indirection can be very expensive in the wrong situations.So you're probably looking at some kind of mess with token pasting, macros and static inlines. Ew.", "msg_date": "Fri, 27 Aug 2021 17:32:21 +0800", "msg_from": "Craig Ringer <craig.ringer@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Wed, 25 Aug 2021 at 22:36, Magnus Hagander <magnus@hagander.net> wrote:\n\n> On Wed, Aug 25, 2021 at 4:06 PM Robert Haas <robertmhaas@gmail.com> wrote:\n> >\n> > On Tue, Aug 24, 2021 at 5:06 PM Chapman Flack <chap@anastigmatix.net>\n> wrote:\n> > > The thing is, I think I have somewhere a list of all the threads on\n> this\n> > > topic that I've read through since the first time I had to come with\n> my own\n> > > hat in hand asking for a PGDLLIMPORT on something, years ago now, and\n> > > I don't think I have ever seen one where it was as uncontroversial\n> > > as you suggest.\n> >\n> > It does tend to be controversial, but I think that's basically only\n> > because Tom Lane has reservations about it. I think if Tom dropped his\n> > opposition to this, nobody else would really care. And I think that\n> > would be a good thing for the project.\n>\n>\n> I have only one consideration about it, and that's a technical one :)\n>\n> Does this in some way have an effect on the size of the binary and/or\n> the time it takes to load it?\n>\n\nOn *nix, no.\n\nOn Windows, very, very minimally.\n\nWe *should* be looking into making private symbols we can't make\nnon-static have hidden visibility at link time, i.e. be DSO-private. This\ncan have a huge impact on link-time optimisation and inlining.\n\nBut doing so is quite orthogonal to the matter of fixing a linkage issue on\nWindows. By making select symbols hidden we'd be *reducing* the exposed set\nof functions and data symbols in a disciplined and progressive way on all\nplatforms. Useful but different.\n\nOn Wed, 25 Aug 2021 at 22:36, Magnus Hagander <magnus@hagander.net> wrote:On Wed, Aug 25, 2021 at 4:06 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> On Tue, Aug 24, 2021 at 5:06 PM Chapman Flack <chap@anastigmatix.net> wrote:\n> > The thing is, I think I have somewhere a list of all the threads on this\n> > topic that I've read through since the first time I had to come with my own\n> > hat in hand asking for a PGDLLIMPORT on something, years ago now, and\n> > I don't think I have ever seen one where it was as uncontroversial\n> > as you suggest.\n>\n> It does tend to be controversial, but I think that's basically only\n> because Tom Lane has reservations about it. I think if Tom dropped his\n> opposition to this, nobody else would really care. And I think that\n> would be a good thing for the project.\n\n\nI have only one consideration about it, and that's a technical one :)\n\nDoes this in some way have an effect on the size of the binary and/or\nthe time it takes to load it?On *nix, no.On Windows, very, very minimally.We *should* be looking into making  private symbols we can't make non-static have hidden visibility at link time, i.e. be DSO-private.  This can have a huge impact on link-time optimisation and inlining.But doing so is quite orthogonal to the matter of fixing a linkage issue on Windows. By making select symbols hidden we'd be *reducing* the exposed set of functions and data symbols in a disciplined and progressive way on all platforms. Useful but different.", "msg_date": "Fri, 27 Aug 2021 17:35:08 +0800", "msg_from": "Craig Ringer <craig.ringer@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Thu, 26 Aug 2021 at 01:51, Alvaro Herrera <alvherre@alvh.no-ip.org>\nwrote:\n\n> On 2021-Aug-25, Magnus Hagander wrote:\n>\n> > The thing we need the PGDLLIMPORT definition for is to *import* them\n> > on the other end?\n>\n> Oh ... so modules that are willing to cheat can include their own\n> declarations of the variables they need, and mark them __declspec\n> (dllimport)?\n>\n>\nDamn. I was hoping nobody would notice that.\n\nI do exactly that in some extensions to work around some of this mess, but\nit is quite awkward and has its limitations.\n\nOn Thu, 26 Aug 2021 at 01:51, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:On 2021-Aug-25, Magnus Hagander wrote:\n\n> The thing we need the PGDLLIMPORT definition for is to *import* them\n> on the other end?\n\nOh ... so modules that are willing to cheat can include their own\ndeclarations of the variables they need, and mark them __declspec\n(dllimport)?\nDamn. I was hoping nobody would notice that.I do exactly that in some extensions to work around some of this mess, but it is quite awkward and has its limitations.", "msg_date": "Fri, 27 Aug 2021 17:36:14 +0800", "msg_from": "Craig Ringer <craig.ringer@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Fri, 27 Aug 2021 at 08:59, Julien Rouhaud <rjuju123@gmail.com> wrote:\n\n> On Fri, Aug 27, 2021 at 3:42 AM Magnus Hagander <magnus@hagander.net>\n> wrote:\n> >\n> > Yeah, but that does move the problem to the other side doesn't it? So\n> > if you (as a pure test of course) were to remove the variable\n> > completely from the included header and just declare it manually with\n> > PGDLLSPEC in your file, it should work?\n> >\n> > Ugly as it is, I wonder if there's a chance we could just process all\n> > the headers at install times and inject the PGDLLIMPORT. We know which\n> > symvols it is on account of what we're getting in the DEF file.\n> >\n> > Not saying that's not a very ugly solution, but it might work?\n>\n> It's apparently not enough. I tried with autovacuum_max_workers GUC,\n> and it still errors out.\n> If I add a PGDLLIMPORT, there's a link error when trying to access the\n> variable:\n> error LNK2019: unresolved external symbol __imp_autovacuum_max_workers\n> referenced in function...\n>\n> If I use PGDLLEXPORT I simply get:\n> error LNK2001: unresolved external symbol aytovacuum_max_workers\n>\n\nIt works, but you can't use PGDLLIMPORT, you have to implement the import\nyourself without the help of __declspec(dllimport) .\n\nWhere you want\n\n autovacuum_max_workers\n\nyou must instead write\n\n *((int*)__imp_autovacuum_max_workers)\n\nHere's the comment I wrote on the topic in something I was working on:\n\n/*\n * On Windows, a symbol is not accessible outside the executable or shared\n * library (PE object) that it is defined in unless explicitly exported in\n * the DLL interface.\n *\n * It must then be explicitly imported by objects that use it; Windows\ndoesn't\n * do ELF-style fixups.\n *\n * The export part is usually accomplished by a __declspec(dllexport)\n * annotation on the symbol or a .DEF file supplied as linker input.\nPostgres\n * uses the .DEF approach, auto-exporting all symbols using\n * src\\tools\\msvc\\gendef.pl . Internally this hides \"symname\" from the DLL\n * interface and instead generates an export symbol \"__imp_symname\" that is\na\n * pointer to the value of \"symname\".\n *\n * The import part is usually done with the __declspec(dllimport)\nannotation on\n * the symbol. The PGDLLIMPORT macro expands to __declspec(dllimport) when\n * postgres headers are included during extension compilation. But not all\nthe\n * symbols that pglogical needs are annotated with PGDLLIMPORT. Attempting\nto\n * access a symbol that is not so-annotated will fail at link time with an\n * error like\n *\n * error LNK2001: unresolved external symbol\ncriticalSharedRelcachesBuilt\n *\n * Because of gendefs.pl, postgres still exports the symbol even if it isn't\n * annotated PGDLLIMPORT. So we can just do the shorthand that\n * __declspec(dllimport) does for us in the preprocessor instead: replace\neach\n * symbol with its __imp_symbol indirection and dereference it.\n *\n * There's one wrinkle in this though. MSVC doesn't generate a definition\nfor a\n * global data symbol that is neither initialized nor explicitly marked\n * __declspec(dllexport). gendefs.pl will think such symbols are references\nto\n * a symbol defined in another object file and will skip them without\nemitting\n * a DATA entry for them in the DEF file, so no __imp_ stub is generated in\nthe\n * DLL interface. We can't use (*__imp_symbolname) if there's no import\nstub.\n *\n * If they're GUCs, we can round-trip them through their text values\n * to read them. Nothing should ever be assigning to GUC storage and\nthere's no\n * reason to take the address of GUC storage, so this should work fine,\nalbeit\n * slower. If we find any that aren't GUCs we're in trouble but so far there\n * haven't been any.\n *\n * See also:\n *\n * -\nhttps://docs.microsoft.com/en-us/cpp/build/importing-data-using-declspec-dllimport\n * - https://docs.microsoft.com/en-us/cpp/build/importing-using-def-files\n * -\nhttps://docs.microsoft.com/en-us/cpp/build/exporting-from-a-dll-using-def-files\n * -\nhttps://docs.microsoft.com/en-us/cpp/build/determining-which-exporting-method-to-use\n */\n\n\nThis is gruesome and I hadn't planned to mention it, but now someone\nnoticed the .DEF file exports the symbols I guess it does no harm.\n\nSo can we just fix PGDLLIMPORT now?\n\nOn Fri, 27 Aug 2021 at 08:59, Julien Rouhaud <rjuju123@gmail.com> wrote:On Fri, Aug 27, 2021 at 3:42 AM Magnus Hagander <magnus@hagander.net> wrote:\n>\n> Yeah, but that does move the problem to the other side doesn't it? So\n> if you (as a pure test of course) were to remove the variable\n> completely from the included header and just declare it manually with\n> PGDLLSPEC in your file, it should work?\n>\n> Ugly as it is, I wonder if there's a chance we could just process all\n> the headers at install times and inject the PGDLLIMPORT. We know which\n> symvols it is on account of what we're getting in the DEF file.\n>\n> Not saying that's not a very ugly solution, but it might work?\n\nIt's apparently not enough.  I tried with autovacuum_max_workers GUC,\nand it still errors out.\nIf I add a PGDLLIMPORT, there's a link error when trying to access the variable:\nerror LNK2019: unresolved external symbol __imp_autovacuum_max_workers\nreferenced in function...\n\nIf I use PGDLLEXPORT I simply get:\nerror LNK2001: unresolved external symbol aytovacuum_max_workersIt works, but you can't use PGDLLIMPORT, you have to implement the import yourself without the help of __declspec(dllimport) .Where you want    autovacuum_max_workersyou must instead write    *((int*)__imp_autovacuum_max_workers)Here's the comment I wrote on the topic in something I was working on:/* * On Windows, a symbol is not accessible outside the executable or shared * library (PE object) that it is defined in unless explicitly exported in * the DLL interface. * * It must then be explicitly imported by objects that use it; Windows doesn't * do ELF-style fixups. * * The export part is usually accomplished by a __declspec(dllexport) * annotation on the symbol or a .DEF file supplied as linker input. Postgres * uses the .DEF approach, auto-exporting all symbols using * src\\tools\\msvc\\gendef.pl . Internally this hides \"symname\" from the DLL * interface and instead generates an export symbol \"__imp_symname\" that is a * pointer to the value of \"symname\". * * The import part is usually done with the __declspec(dllimport) annotation on * the symbol. The PGDLLIMPORT macro expands to __declspec(dllimport) when * postgres headers are included during extension compilation. But not all the * symbols that pglogical needs are annotated with PGDLLIMPORT. Attempting to * access a symbol that is not so-annotated will fail at link time with an * error like * *     error LNK2001: unresolved external symbol criticalSharedRelcachesBuilt * * Because of gendefs.pl, postgres still exports the symbol even if it isn't * annotated PGDLLIMPORT. So we can just do the shorthand that * __declspec(dllimport) does for us in the preprocessor instead: replace each * symbol with its __imp_symbol indirection and dereference it. * * There's one wrinkle in this though. MSVC doesn't generate a definition for a * global data symbol that is neither initialized nor explicitly marked * __declspec(dllexport). gendefs.pl will think such symbols are references to * a symbol defined in another object file and will skip them without emitting * a DATA entry for them in the DEF file, so no __imp_ stub is generated in the * DLL interface. We can't use (*__imp_symbolname) if there's no import stub. * * If they're GUCs, we can round-trip them through their text values * to read them. Nothing should ever be assigning to GUC storage and there's no * reason to take the address of GUC storage, so this should work fine, albeit * slower. If we find any that aren't GUCs we're in trouble but so far there * haven't been any. * * See also: * * - https://docs.microsoft.com/en-us/cpp/build/importing-data-using-declspec-dllimport * - https://docs.microsoft.com/en-us/cpp/build/importing-using-def-files * - https://docs.microsoft.com/en-us/cpp/build/exporting-from-a-dll-using-def-files * - https://docs.microsoft.com/en-us/cpp/build/determining-which-exporting-method-to-use */This is gruesome and I hadn't planned to mention it, but now someone noticed the .DEF file exports the symbols I guess it does no harm.So can we just fix PGDLLIMPORT now?", "msg_date": "Fri, 27 Aug 2021 17:41:40 +0800", "msg_from": "Craig Ringer <craig.ringer@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Hi,\n\n\nOn 2021-08-23 14:53:34 +0800, Julien Rouhaud wrote:\n> So since the non currently explicitly exported GUC global variables shouldn't\n> be accessible by third-party code, I'm attaching a POC patch that does the\n> opposite of v1: enforce that restriction using a new pg_attribute_hidden()\n> macro, defined with GCC only, to start discussing that topic.\n\nThis fails on cfbot: https://cirrus-ci.com/task/6424663592009728?logs=build#L1\n\n\nI'm not feeling a lot of enthusiasm for the change. But if we were to do this,\nwe'd have to have infrastructure to detect missing hidden declarations,\notherwise it's inevitable that they don't get added.\n\nI kind of like the idea of hiding postgres symbols for other reasons than\nwin<->everything else parity. Namely that not exporting symbols can allow the\ncompiler to optimize more...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sat, 12 Feb 2022 19:59:56 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Hi,\n\nOn Sat, Feb 12, 2022 at 07:59:56PM -0800, Andres Freund wrote:\n> \n> On 2021-08-23 14:53:34 +0800, Julien Rouhaud wrote:\n> > So since the non currently explicitly exported GUC global variables shouldn't\n> > be accessible by third-party code, I'm attaching a POC patch that does the\n> > opposite of v1: enforce that restriction using a new pg_attribute_hidden()\n> > macro, defined with GCC only, to start discussing that topic.\n> \n> This fails on cfbot: https://cirrus-ci.com/task/6424663592009728?logs=build#L1\n> \n> I'm not feeling a lot of enthusiasm for the change.\n\nYes, which is also why I'm not planning on spending more effort on that (or the\nopposite) unless I get some sort of feedback, so thanks a lot for the answer\nhere.\n\nNote that if everyone is happy with the status quo please say so. I will\nhappily mark the CF entry rejected and stop all efforts to try packaging\nextensions on Windows. It will save me a lot of efforts that 99% of users\ndon't care about.\n\nIf not maybe we could improve the situation, and also learn for the max_backend\nthread.\n\nMaybe we could have an actually usable GUC API to retrieve values in their\nnative format rather than C string for instance, that we could make sure also\nworks for cases like max_backend?\n\n> But if we were to do this,\n> we'd have to have infrastructure to detect missing hidden declarations,\n> otherwise it's inevitable that they don't get added.\n\nAgreed. For now I'm using a simple loop around\n\negrep \"^\\s+&[A-Za-z_]+,$\" src/backend/utils/misc/guc.c | egrep -o \"[A-Za-z_]+\"\n\nto get all the underlying symbols, and grep that again (actually using ag,\nwhich makes it 3x faster) to detect the lack of wanted annotation. Were you\nthinking of some script like that, maybe to run before a release, or something\nmore evolved?\n\n> I kind of like the idea of hiding postgres symbols for other reasons than\n> win<->everything else parity. Namely that not exporting symbols can allow the\n> compiler to optimize more...\n\nYeah I saw that in nearby threads and I entirely agree.\n\n\n", "msg_date": "Sun, 13 Feb 2022 15:29:31 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Hi,\n\nOn 02/13/22 02:29, Julien Rouhaud wrote:\n> Maybe we could have an actually usable GUC API to retrieve values in their\n> native format rather than C string for instance, that we could make sure also\n> works for cases like max_backend?\n\nI proposed a sketch of such an API for discussion back in [0] (the second\nidea in that email, the \"what I'd really like\" one).\n\nIn that scheme, some extension code that was interested in (say,\nfor some reason) log_statement_sample_rate could say:\n\nstatic double samprate;\nstatic int gucs_changed = 0;\n\n#define SAMPRATE_CHANGED 1\n\n...\n ObserveTypedConfigValue(\"log_statement_sample_rate\",\n &samprate, &gucs_changed, SAMPRATE_CHANGED);\n...\n\nand will be subscribed to have the native-format value stored into samprate,\nand SAMPRATE_CHANGED ORed into gucs_changed, whenever the value changes.\n\nThe considerations leading me to that design were:\n\n- avoid subscribing as a 'callback' sort of listener. GUCs can get set\n (or, especially, reset) in delicate situations like error recovery\n where calling out to arbitrary extra code might best be avoided.\n\n- instead, just dump the value in a subscribed location. A copy,\n of course, so no modification there affects the real value.\n\n- but at the same time, OR a flag into a bit set, so subscribing code can\n very cheaply poll for when a value of interest (or any of a bunch of\n values of interest) has changed since last checked.\n\n- do the variable lookup by name once only, and pay no further search cost\n when the subscribing code wants the value.\n\n\nI never pictured that proposal as the last word on the question, and\ndifferent proposals could result from putting different weights on those\nobjectives, or adding other objectives, but I thought it might serve\nas a discussion-starter.\n\nRegards,\n-Chap\n\n\n[0] https://www.postgresql.org/message-id/6123C425.3080409%40anastigmatix.net\n\n\n", "msg_date": "Sun, 13 Feb 2022 12:32:20 -0500", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Chapman Flack <chap@anastigmatix.net> writes:\n> On 02/13/22 02:29, Julien Rouhaud wrote:\n>> Maybe we could have an actually usable GUC API to retrieve values in their\n>> native format rather than C string for instance, that we could make sure also\n>> works for cases like max_backend?\n\n> I proposed a sketch of such an API for discussion back in [0] (the second\n> idea in that email, the \"what I'd really like\" one).\n\n> In that scheme, some extension code that was interested in (say,\n> for some reason) log_statement_sample_rate could say:\n\n> static double samprate;\n> static int gucs_changed = 0;\n\n> #define SAMPRATE_CHANGED 1\n\n> ...\n> ObserveTypedConfigValue(\"log_statement_sample_rate\",\n> &samprate, &gucs_changed, SAMPRATE_CHANGED);\n> ...\n\n> and will be subscribed to have the native-format value stored into samprate,\n> and SAMPRATE_CHANGED ORed into gucs_changed, whenever the value changes.\n\n\nThat seems like about 10X more complexity than is warranted,\nnot only in terms of the infrastructure required, but also in\nthe intellectual complexity around \"just when could that value\nchange?\"\n\nWhy not just provide equivalents to GetConfigOption() that can\ndeliver int, float8, etc values instead of strings?\n\n(In any case we'd need to rethink the GUC \"show_hook\" APIs, which\ncurrently need only deal in string output.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 13 Feb 2022 15:16:58 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On 02/13/22 15:16, Tom Lane wrote:\n> That seems like about 10X more complexity than is warranted,\n> not only in terms of the infrastructure required, but also in\n> the intellectual complexity around \"just when could that value\n> change?\"\n> \n> Why not just provide equivalents to GetConfigOption() that can\n> deliver int, float8, etc values instead of strings?\n\nAnd repeat the bsearch to find the option every time the interested\nextension wants to check the value, even when what it learns is that\nthe value has not changed? And make it the job of every piece of\ninterested extension code to save the last-retrieved value and compare\nif it wants to detect that it's changed? When the GUC machinery already\nhas code that executes exactly when a value is being supplied for\nan option?\n\nClearly I'm not thinking here of the GUCs that are read-only views of\nvalues that are determined some other way. How many of those are there\nthat are mutable, and could have their values changed without going\nthrough the GUC mechanisms?\n\nAlso, I think there are some options that are only represented by\nan int, float8, etc., when shown, but whose native internal form\nis something else, like a struct. I was definitely contemplating\nthat you could 'subscribe' to one of those too, by passing the\naddress of an appropriate struct. But of course a GetConfigOption()\nflavor could work that way too.\n\nRegards,\n-Chap\n\n\n", "msg_date": "Sun, 13 Feb 2022 15:36:16 -0500", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Hi,\n\nOn 2022-02-13 15:36:16 -0500, Chapman Flack wrote:\n> Clearly I'm not thinking here of the GUCs that are read-only views of\n> values that are determined some other way. How many of those are there\n> that are mutable, and could have their values changed without going\n> through the GUC mechanisms?\n\nIs there any GUCs where one needs this? There are a few GUCs frequently\nchanging values, but it's stuff like transaction_read_only. Where I don't\nreally see a use for constantly checking the value.\n\n\n> Also, I think there are some options that are only represented by\n> an int, float8, etc., when shown, but whose native internal form\n> is something else, like a struct. I was definitely contemplating\n> that you could 'subscribe' to one of those too, by passing the\n> address of an appropriate struct. But of course a GetConfigOption()\n> flavor could work that way too.\n\nI have a very hard time seeing a use-case for this. Nor how it'd even work\nwith a struct - you can't just copy the struct contents, because of pointers\nto objects etc. I don't think there really are options like this anyway.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sun, 13 Feb 2022 12:48:18 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Chapman Flack <chap@anastigmatix.net> writes:\n> On 02/13/22 15:16, Tom Lane wrote:\n>> Why not just provide equivalents to GetConfigOption() that can\n>> deliver int, float8, etc values instead of strings?\n\n> And repeat the bsearch to find the option every time the interested\n> extension wants to check the value, even when what it learns is that\n> the value has not changed? And make it the job of every piece of\n> interested extension code to save the last-retrieved value and compare\n> if it wants to detect that it's changed? When the GUC machinery already\n> has code that executes exactly when a value is being supplied for\n> an option?\n\n(shrug) You could argue the performance aspect either way. If the\ncore GUC code updates a value 1000 times while the extension consults\nthe result once, you've probably lost money on the deal.\n\nAs for the bsearch, we could improve on that when and if it's shown\nto be a bottleneck --- converting to a hash table ought to pretty\nmuch fix any worries there. Or we could provide APIs that let an\nextension look up a \"struct config_generic *\" once and then fetch\ndirectly using that pointer. (But I'd prefer not to, since it'd\nconstrain the internals more than I think is wise.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 13 Feb 2022 15:48:44 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2022-02-13 15:36:16 -0500, Chapman Flack wrote:\n>> Also, I think there are some options that are only represented by\n>> an int, float8, etc., when shown, but whose native internal form\n>> is something else, like a struct. I was definitely contemplating\n>> that you could 'subscribe' to one of those too, by passing the\n>> address of an appropriate struct. But of course a GetConfigOption()\n>> flavor could work that way too.\n\n> I have a very hard time seeing a use-case for this. Nor how it'd even work\n> with a struct - you can't just copy the struct contents, because of pointers\n> to objects etc. I don't think there really are options like this anyway.\n\nThere are a couple of legacy cases like \"datestyle\" where something\nthat the user sees as one GUC translates to multiple variables under\nthe hood, so you'd have to invent a struct if you wanted to pass\nthem through a mechanism like this. I don't have a big problem\nwith leaving those out of any such solution, though. (I see that\ndatestyle's underlying variables DateStyle and DateOrder are already\nmarked PGDLLIMPORT, and that's fine with me.) A possibly more\ninteresting case is something like search_path --- but again,\nthere are already special-purpose APIs for accessing the interpreted\nvalue of that.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 13 Feb 2022 16:05:38 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On 02/13/22 15:48, Tom Lane wrote:\n> much fix any worries there. Or we could provide APIs that let an\n> extension look up a \"struct config_generic *\" once and then fetch\n> directly using that pointer. (But I'd prefer not to, since it'd\n> constrain the internals more than I think is wise.)\n\nThere is GetConfigOptionByNum already ... but I'm not sure there's\nan easy way to ask \"what's the num for option foo?\".\n\nGetNumConfigOptions exists, so there is a brute-force way.\n\nRegards,\n-Chap\n\n\n", "msg_date": "Sun, 13 Feb 2022 17:57:24 -0500", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Sun, Feb 13, 2022 at 3:17 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > ...\n> > ObserveTypedConfigValue(\"log_statement_sample_rate\",\n> > &samprate, &gucs_changed, SAMPRATE_CHANGED);\n> > ...\n>\n> > and will be subscribed to have the native-format value stored into samprate,\n> > and SAMPRATE_CHANGED ORed into gucs_changed, whenever the value changes.\n>\n>\n> That seems like about 10X more complexity than is warranted,\n> not only in terms of the infrastructure required, but also in\n> the intellectual complexity around \"just when could that value\n> change?\"\n\nI agree in the sense that I believe we should $SUBJECT rather than\nfooling around with this. It is completely understandable that\nextensions want to know the value of GUCs, and not just as strings,\nand doing $SUBJECT would be by far the easiest way of accomplishing\nthat. I'm sure Andres is right when he says that there are cases where\nnot exposing symbols could improve the generated machine code, but I'm\nalso pretty sure that we just have to live with the cost when it's\ncore GUCs that we're talking about. It's just unrealistic to suppose\nthat extensions are not going to care.\n\nBut if we're not going to do that, then I don't see why Chapman's\nproposal is overly complex. It seems completely understandable that if\n(some_guc_var != last_observed_some_guc_var) { ...adapt accordingly...\n} feels like an OK thing to do but if you have to make a function call\nevery time then it seems too expensive. Imagine a background worker\nthat has to do a bunch of extra setup every time some GUC changes, and\nevery iteration of the main loop just wants to check whether it's\nchanged, and the main loop could iterate very quickly in some cases. I\nwouldn't want to worry about the cost of a function call on every trip\nthrough the loop. Maybe it would be trivial in practice, but who\nknows?\n\nI don't particularly like Chapman's solution, but given that you've\nrepeatedly blocked every effort to just apply PGDLLIMPORT markings\nacross the board, I'm not sure what the realistic alternative is. It\ndoesn't seem fair to argue, on the one hand, that we can't just do\nwhat I believe literally every other hacker on the project wants, and\nthat on the other hand, it's also unacceptable to add complexity to\nwork around the problem you've created by blocking that proposal every\ntime it's been raised year after year. It's really pretty frustrating\nto me that we haven't just done the obvious thing here years ago. The\ntime we've spent arguing about it could have been better spent on just\nabout anything else, with absolutely zero harm to the project.\n\n--\nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 14 Feb 2022 10:29:53 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> I don't particularly like Chapman's solution, but given that you've\n> repeatedly blocked every effort to just apply PGDLLIMPORT markings\n> across the board, I'm not sure what the realistic alternative is.\n\nYou do realize that I just have one vote in these matters? If I'm\noutvoted then so be it. The impression I have though is that a\nnumber of other people don't like the extra notational cruft either.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 14 Feb 2022 10:37:52 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, Feb 14, 2022 at 10:38 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Robert Haas <robertmhaas@gmail.com> writes:\n> > I don't particularly like Chapman's solution, but given that you've\n> > repeatedly blocked every effort to just apply PGDLLIMPORT markings\n> > across the board, I'm not sure what the realistic alternative is.\n>\n> You do realize that I just have one vote in these matters? If I'm\n> outvoted then so be it. The impression I have though is that a\n> number of other people don't like the extra notational cruft either.\n\nHmm, I guess I'd need to know who those people are in order to be able\nto review their comments. I don't *like* the extra notational cruft,\nbut applying it inconsistently isn't better than being consistent. As\nI see it, we have four choices: (1) apply PGDLLIMPORT markings\nrelatively broadly so that people can get extensions to work on\nWindows, (2) continue to apply them inconsistently, thus slightly\nreducing notational clutter at the cost of breaking lots of extensions\non Windows, (3) put some complex system in place like what Chapman\nproposes and get all extension authors to adopt it, and (4) remove the\nWindows port. To the best of my current knowledge, everyone other than\nyou prefers (1), you prefer (2) or (4), and (3) is an attempt at\ncompromise that is nobody's first choice.\n\nIf that is correct, then I think we should do (1). If it's incorrect\nthen I think we should do our best to find a choice other than (2)\nthat does attract a consensus. The current situation, which is (2),\nmust be the worst of all possible options because it manages to bother\nthe people who dislike the clutter AND ALSO bother the people who want\nto have their extensions work on Windows. Any other choice has a\nchance of reaching a state where only one of those groups of people is\nannoyed.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 14 Feb 2022 11:43:08 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On 02/14/22 11:43, Robert Haas wrote:\n> On Mon, Feb 14, 2022 at 10:38 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Robert Haas <robertmhaas@gmail.com> writes:\n>>> I don't particularly like Chapman's solution,\n> ... and (3) is an attempt at compromise that is nobody's first choice.\n\nOk, I guess that's )sniffle( a pretty fair way of putting it.\n\n> ... (3) put some complex system in place like what Chapman\n> proposes and get all extension authors to adopt it,\n\nBy the same token, I don't think it would entail anything like a big\nflag day for extension authors. Provided no one proposes immediately\nto /remove/ PGDLLIMPORT from things that now have it, the effect would\nbe more that the next time an extension author comes hat-in-hand\nasking for a new PGDLLIMPORT because a thing won't build on Windows,\nthe answer can be \"here, we have this API you can use for that now.\"\n\nMy reading of past discussions on the list suggest that stronger\nencapsulation and API delineation have advocates in some quarters,\nso I tried to accommodate that in what I proposed. It does, for example,\navoid exposing the 'real' value of a GUC to writing by a buggy\nor compromised extension.\n\nI'll be first to agree what I proposed isn't beautiful, but it might be\nthat a round or two of improvement by somebody smarter than me could lead\nto something possibly preferable to PGDLLIMPORT-everywhere /when measured\nagainst certain objectives/, like encapsulation.\n\nSo maybe this is in part a discussion about what the weights should be\non those various objectives.\n\nRegards,\n-Chap\n\n\n", "msg_date": "Mon, 14 Feb 2022 12:25:36 -0500", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> Hmm, I guess I'd need to know who those people are in order to be able\n> to review their comments. I don't *like* the extra notational cruft,\n> but applying it inconsistently isn't better than being consistent. As\n> I see it, we have four choices: (1) apply PGDLLIMPORT markings\n> relatively broadly so that people can get extensions to work on\n> Windows, (2) continue to apply them inconsistently, thus slightly\n> reducing notational clutter at the cost of breaking lots of extensions\n> on Windows, (3) put some complex system in place like what Chapman\n> proposes and get all extension authors to adopt it, and (4) remove the\n> Windows port. To the best of my current knowledge, everyone other than\n> you prefers (1), you prefer (2) or (4), and (3) is an attempt at\n> compromise that is nobody's first choice.\n\nI think you are attributing straw-man positions to me. What I'd actually\n*like* is some solution that has the effect of (1) without having to mark\nup our code with a bunch of Microsoft-isms. However I don't know how to\ndo that, and I do agree that (2), (3), and (4) are not better than (1).\n\nThere are some technical issues though:\n\n* AFAICS, the patch of record doesn't actually do (1), it does something\nelse that adds yet more new notation. The cfbot says it fails, too.\n\n* If we institute a policy that all GUCs should be PGDLLIMPORT'd,\nhow will we enforce that new patches follow that? I don't want to be\nendlessly going back and adding forgotten PGDLLIMPORT markers.\n\n* There's a moderately sizable subset of GUCs where the underlying\nvariable is not visible at all because it's static in guc.c.\nTypically this is because that variable is only used for display\nand there's an assign hook that stores the real data somewhere else.\nI suppose what we want in such cases is for the \"somewhere else\"\nto be PGDLLIMPORT'd, but in a lot of cases those variables are also\nstatic in some other module. Does this proposal include exporting\nvariables that currently aren't visible to extensions at all?\nI'm a little resistant to that. I can buy making sure that Windows\nhas a level playing field, but that's as far as I want to go.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 14 Feb 2022 12:33:46 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, Feb 14, 2022 at 12:25 PM Chapman Flack <chap@anastigmatix.net> wrote:\n> On 02/14/22 11:43, Robert Haas wrote:\n> > On Mon, Feb 14, 2022 at 10:38 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >> Robert Haas <robertmhaas@gmail.com> writes:\n> >>> I don't particularly like Chapman's solution,\n> > ... and (3) is an attempt at compromise that is nobody's first choice.\n>\n> Ok, I guess that's )sniffle( a pretty fair way of putting it.\n\nI mean I like it better than Tom does ... I just think it's a\ncomplicated work around for a problem we don't really need to have.\n\n> My reading of past discussions on the list suggest that stronger\n> encapsulation and API delineation have advocates in some quarters,\n> so I tried to accommodate that in what I proposed. It does, for example,\n> avoid exposing the 'real' value of a GUC to writing by a buggy\n> or compromised extension.\n>\n> I'll be first to agree what I proposed isn't beautiful, but it might be\n> that a round or two of improvement by somebody smarter than me could lead\n> to something possibly preferable to PGDLLIMPORT-everywhere /when measured\n> against certain objectives/, like encapsulation.\n>\n> So maybe this is in part a discussion about what the weights should be\n> on those various objectives.\n\nKeep in mind that there's nothing being set in stone here. Applying\nPGDLLIMPORT to all GUCs across the board does not foreclose putting\nsome other system that restricts symbol visibility in the future. But\nin the present, there is clearly no approach to the symbol visibility\nproblem that is fully baked or enjoys consensus. Yet, there is clearly\nconsensus that not being able to access GUCs in Windows extensions is\na problem. There must be like six different threads with people\ncomplaining about that, and in every case the suggested solution is to\njust add PGDLLIMPORT for crying out loud.\n\nIf in the future there is a consensus to restrict symbol visibility in\norder to achieve some agreed-upon amount of encapsulation, then we can\ndo that then. Extension authors may not like it much, but every\nserious extension author understands that the PostgreSQL code base\nneeds to keep moving forward, and that this will sometimes require\nthem to adjust for new major versions. This would be a bigger\nadjustment than many, but I have confidence that if the benefits are\nworthwhile, people will cope with it and adjust their extensions to\nadhere to whatever new rules we put in place.\n\nBut between now and then, refusing to apply PGDLLIMPORT to a basically\nrandom subset of GUCs is just annoying people without any compensating\nbenefit.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 14 Feb 2022 12:36:18 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, Feb 14, 2022 at 12:34 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> I think you are attributing straw-man positions to me. What I'd actually\n> *like* is some solution that has the effect of (1) without having to mark\n> up our code with a bunch of Microsoft-isms. However I don't know how to\n> do that, and I do agree that (2), (3), and (4) are not better than (1).\n\nOK, that sounds like we might be making some progress toward a useful agreement.\n\n> There are some technical issues though:\n>\n> * AFAICS, the patch of record doesn't actually do (1), it does something\n> else that adds yet more new notation. The cfbot says it fails, too.\n\nThat sounds like a problem. Should be fixable.\n\n> * If we institute a policy that all GUCs should be PGDLLIMPORT'd,\n> how will we enforce that new patches follow that? I don't want to be\n> endlessly going back and adding forgotten PGDLLIMPORT markers.\n\nIt seems to me that it would be no different from bumping catversion\nor updating nodefuncs.c: yes, it will get forgotten sometimes, but\nhopefully people will mostly get used to it just like they do with\ndozens of other PG-specific coding rules. I don't see that it's likely\nto generate more than a handful of commits per year, so it doesn't\nreally seem worth worrying about to me, but YMMV. Maybe it's possible\nto write a perl script to verify it, although it seems like it might\nbe complicated to code that up.\n\n> * There's a moderately sizable subset of GUCs where the underlying\n> variable is not visible at all because it's static in guc.c.\n> Typically this is because that variable is only used for display\n> and there's an assign hook that stores the real data somewhere else.\n> I suppose what we want in such cases is for the \"somewhere else\"\n> to be PGDLLIMPORT'd, but in a lot of cases those variables are also\n> static in some other module. Does this proposal include exporting\n> variables that currently aren't visible to extensions at all?\n> I'm a little resistant to that. I can buy making sure that Windows\n> has a level playing field, but that's as far as I want to go.\n\nI can live with that. If someone complains about those variables being\nstatic-to-file instead of globally visible, we can address that\ncomplaint on its merits when it is presented.\n\nAn alternative rule which would dodge that particular issue would be\nto just slap PGDLLIMPORT on every global variable in every header\nfile. That would arguably be a simpler rule, though it means even more\nPGDLLIMPORT declarations floating around.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 14 Feb 2022 12:45:08 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> An alternative rule which would dodge that particular issue would be\n> to just slap PGDLLIMPORT on every global variable in every header\n> file. That would arguably be a simpler rule, though it means even more\n> PGDLLIMPORT declarations floating around.\n\nYeah, if the objective is \"level playing field for Windows\",\nthen it's hard to avoid the conclusion that we should just do that.\nAgain, I've never had an objection to that as the end result ---\nI just wish that we could get the toolchain to do it for us.\nBut if we can't, we can't.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 14 Feb 2022 12:54:47 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, Feb 14, 2022 at 12:55 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Robert Haas <robertmhaas@gmail.com> writes:\n> > An alternative rule which would dodge that particular issue would be\n> > to just slap PGDLLIMPORT on every global variable in every header\n> > file. That would arguably be a simpler rule, though it means even more\n> > PGDLLIMPORT declarations floating around.\n>\n> Yeah, if the objective is \"level playing field for Windows\",\n> then it's hard to avoid the conclusion that we should just do that.\n> Again, I've never had an objection to that as the end result ---\n> I just wish that we could get the toolchain to do it for us.\n> But if we can't, we can't.\n\n100% agreed.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 14 Feb 2022 13:12:49 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Hi,\n\nOn 2022-02-14 12:45:08 -0500, Robert Haas wrote:\n> On Mon, Feb 14, 2022 at 12:34 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > * If we institute a policy that all GUCs should be PGDLLIMPORT'd,\n> > how will we enforce that new patches follow that? I don't want to be\n> > endlessly going back and adding forgotten PGDLLIMPORT markers.\n> \n> It seems to me that it would be no different from bumping catversion\n> or updating nodefuncs.c: yes, it will get forgotten sometimes, but\n> hopefully people will mostly get used to it just like they do with\n> dozens of other PG-specific coding rules. I don't see that it's likely\n> to generate more than a handful of commits per year, so it doesn't\n> really seem worth worrying about to me, but YMMV. Maybe it's possible\n> to write a perl script to verify it, although it seems like it might\n> be complicated to code that up.\n\nI think it'd be better if we had scripts ensuring this stays sane. Several of\nyour examples do have that. Whereas I don't see what would cause us to missing\nPGDLLIMPORTs for GUCs, given it's a windows only issue and that you need an\nextension using the GUC with omitted PGDLLIMPORT.\n\n\n> An alternative rule which would dodge that particular issue would be\n> to just slap PGDLLIMPORT on every global variable in every header\n> file. That would arguably be a simpler rule, though it means even more\n> PGDLLIMPORT declarations floating around.\n\nThat would have the advantage of being comparatively easy to check in an\nautomated way. Might even be cheap enough to just make it part of the build.\n\nBut it seems like it'd be a fair amount of work and cause a lot of patch\nrebasing pain? If we end up going that way, we should schedule this to happen\njust after the feature freeze, I think.\n\nIf we consider doing this for all extern variables, we should think about\ndoing this for headers *and* functions. That'd allow us to get rid of the\nfairly complicated logic to generate the .def file for the postgres binary on\nwindows (src/tools/gendef.pl). And maybe also the related thing on AIX\n(src/backend/port/aix/mkldexport.sh)\n\nI'm kind of partial to the \"add explicit visibility information to everything\"\napproach because the windows export file generation is a decent chunk of the\nmeson patchset. And what's missing to make it work on AIX...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 14 Feb 2022 17:53:09 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, Feb 14, 2022 at 8:53 PM Andres Freund <andres@anarazel.de> wrote:\n> > An alternative rule which would dodge that particular issue would be\n> > to just slap PGDLLIMPORT on every global variable in every header\n> > file. That would arguably be a simpler rule, though it means even more\n> > PGDLLIMPORT declarations floating around.\n>\n> That would have the advantage of being comparatively easy to check in an\n> automated way. Might even be cheap enough to just make it part of the build.\n\nI wasn't able to quickly write something that was smart enough to use\nas part of the build, but I wrote something dumb that I think works\nwell enough to use with a little bit of human intelligence alongside.\nSee attached.\n\n> But it seems like it'd be a fair amount of work and cause a lot of patch\n> rebasing pain? If we end up going that way, we should schedule this to happen\n> just after the feature freeze, I think.\n\nWe could do that. I'd sort of rather get it done. We still have two\nweeks before the last CommitFest officially starts, and it's not as if\nthere won't be tons of uncommitted patches floating around after that.\n\n> If we consider doing this for all extern variables, we should think about\n> doing this for headers *and* functions. That'd allow us to get rid of the\n> fairly complicated logic to generate the .def file for the postgres binary on\n> windows (src/tools/gendef.pl). And maybe also the related thing on AIX\n> (src/backend/port/aix/mkldexport.sh)\n\nI don't know what you mean by this.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com", "msg_date": "Tue, 15 Feb 2022 08:58:05 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Hi,\n\nOn 2022-02-15 08:58:05 -0500, Robert Haas wrote:\n> On Mon, Feb 14, 2022 at 8:53 PM Andres Freund <andres@anarazel.de> wrote:\n> > > An alternative rule which would dodge that particular issue would be\n> > > to just slap PGDLLIMPORT on every global variable in every header\n> > > file. That would arguably be a simpler rule, though it means even more\n> > > PGDLLIMPORT declarations floating around.\n> >\n> > That would have the advantage of being comparatively easy to check in an\n> > automated way. Might even be cheap enough to just make it part of the build.\n> \n> I wasn't able to quickly write something that was smart enough to use\n> as part of the build, but I wrote something dumb that I think works\n> well enough to use with a little bit of human intelligence alongside.\n> See attached.\n\nCool.\n\n\n> > But it seems like it'd be a fair amount of work and cause a lot of patch\n> > rebasing pain? If we end up going that way, we should schedule this to happen\n> > just after the feature freeze, I think.\n> \n> We could do that. I'd sort of rather get it done. We still have two\n> weeks before the last CommitFest officially starts, and it's not as if\n> there won't be tons of uncommitted patches floating around after that.\n\nBreaking close to every patch 6-7 weeks before freeze doesn't seem\ngreat. Particularly because this is a mostly automatically generated patch, so\nI don't really see a forcing function to do this now, rather than at a more\nopportune moment.\n\nThe more I think about it the more I'm convinced that if we want to do this,\nwe should do it for variables and functions.\n\n\n> > If we consider doing this for all extern variables, we should think about\n> > doing this for headers *and* functions. That'd allow us to get rid of the\n> > fairly complicated logic to generate the .def file for the postgres binary on\n> > windows (src/tools/gendef.pl). And maybe also the related thing on AIX\n> > (src/backend/port/aix/mkldexport.sh)\n> \n> I don't know what you mean by this.\n\nWe only need gendef.pl because we don't mark functions with visibility\ninformation. If we attach PGDLLIMPORT to functions and variables we can a fair\nbit of complexity. And I think not just for windows, but also AIX (there's a\nwhole section in src/backend/Makefile about AIX oddity), but I'm not sure\nabout it.\n\n\n\n> diff --git a/src/include/common/relpath.h b/src/include/common/relpath.h\n> index a4b5dc853b..13849a3790 100644\n> --- a/src/include/common/relpath.h\n> +++ b/src/include/common/relpath.h\n> @@ -56,7 +56,7 @@ typedef enum ForkNumber\n> \n> #define FORKNAMECHARS\t4\t\t/* max chars for a fork name */\n> \n> -extern const char *const forkNames[];\n> +extern PGDLLIMPORT const char *const forkNames[];\n> \n> extern ForkNumber forkname_to_number(const char *forkName);\n> extern int\tforkname_chars(const char *str, ForkNumber *fork);\n\nI think we might need a new form of PGDLLIMPORT to mark these correctly - I\ndon't think they should be marked PGDLLIMPORT in frontend environment.\n\n\n> diff --git a/src/include/fe_utils/print.h b/src/include/fe_utils/print.h\n> index 836b4e29a8..5caf9e2d08 100644\n> --- a/src/include/fe_utils/print.h\n> +++ b/src/include/fe_utils/print.h\n> @@ -177,10 +177,10 @@ typedef struct printQueryOpt\n> } printQueryOpt;\n> \n> \n> -extern volatile sig_atomic_t cancel_pressed;\n> +extern PGDLLIMPORT volatile sig_atomic_t cancel_pressed;\n> \n> -extern const printTextFormat pg_asciiformat;\n> -extern const printTextFormat pg_asciiformat_old;\n> +extern PGDLLIMPORT const printTextFormat pg_asciiformat;\n> +extern PGDLLIMPORT const printTextFormat pg_asciiformat_old;\n> extern printTextFormat pg_utf8format;\t/* ideally would be const, but... */\n\nAre these right? I don't think we should make frontend stuff exported without\na very clear reason.\n\n\n> extern void jit_reset_after_error(void);\n> diff --git a/src/include/jit/llvmjit.h b/src/include/jit/llvmjit.h\n> index 66143afccc..4541f9a2c4 100644\n> --- a/src/include/jit/llvmjit.h\n> +++ b/src/include/jit/llvmjit.h\n> @@ -56,30 +56,30 @@ typedef struct LLVMJitContext\n> } LLVMJitContext;\n> \n> /* llvm module containing information about types */\n> -extern LLVMModuleRef llvm_types_module;\n> +extern PGDLLIMPORT LLVMModuleRef llvm_types_module;\n\nThese are wrong I think, this is a shared library.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 15 Feb 2022 08:06:58 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Hi,\n\nOn Mon, Feb 14, 2022 at 12:45:08PM -0500, Robert Haas wrote:\n> On Mon, Feb 14, 2022 at 12:34 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> > * There's a moderately sizable subset of GUCs where the underlying\n> > variable is not visible at all because it's static in guc.c.\n> > Typically this is because that variable is only used for display\n> > and there's an assign hook that stores the real data somewhere else.\n> > I suppose what we want in such cases is for the \"somewhere else\"\n> > to be PGDLLIMPORT'd, but in a lot of cases those variables are also\n> > static in some other module. Does this proposal include exporting\n> > variables that currently aren't visible to extensions at all?\n> > I'm a little resistant to that. I can buy making sure that Windows\n> > has a level playing field, but that's as far as I want to go.\n> \n> I can live with that. If someone complains about those variables being\n> static-to-file instead of globally visible, we can address that\n> complaint on its merits when it is presented.\n\nSame here, if any third-party project had any use of such variable, they would\nhave sent some patch for that already so I don't see any reason to change it\nnow.\n\n\n", "msg_date": "Wed, 16 Feb 2022 01:10:50 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Wed, Feb 16, 2022 at 01:10:50AM +0800, Julien Rouhaud wrote:\n> Hi,\n> \n> On Mon, Feb 14, 2022 at 12:45:08PM -0500, Robert Haas wrote:\n> > On Mon, Feb 14, 2022 at 12:34 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > \n> > > * There's a moderately sizable subset of GUCs where the underlying\n> > > variable is not visible at all because it's static in guc.c.\n> > > Typically this is because that variable is only used for display\n> > > and there's an assign hook that stores the real data somewhere else.\n> > > I suppose what we want in such cases is for the \"somewhere else\"\n> > > to be PGDLLIMPORT'd, but in a lot of cases those variables are also\n> > > static in some other module. Does this proposal include exporting\n> > > variables that currently aren't visible to extensions at all?\n> > > I'm a little resistant to that. I can buy making sure that Windows\n> > > has a level playing field, but that's as far as I want to go.\n> > \n> > I can live with that. If someone complains about those variables being\n> > static-to-file instead of globally visible, we can address that\n> > complaint on its merits when it is presented.\n> \n> Same here, if any third-party project had any use of such variable, they would\n> have sent some patch for that already so I don't see any reason to change it\n> now.\n\nAgreed. I think the big goal here is to make Windows have the same\nGUC variable visibility as Unix --- when we change things in a way that\nbreaks extensions, we hear about Unix breakage quickly and adjust for\nit. It is Windows being different and only getting the problem reports\nlater that is the real problem.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n If only the physical world exists, free will is an illusion.\n\n\n\n", "msg_date": "Tue, 15 Feb 2022 12:17:48 -0500", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Hi,\n\nSorry for taking so much time to answer here. I definitely wanted to work on\nthat but I was under the impression that although we now had an agreement to\napply PGDLLIMPORT globally a patch itself wasn't really rushed, so I spent the\nlast two days trying to setup a new Windows environment as my previous one\nisn't working anymore. That's taking much longer than I planned.\n\nOn Tue, Feb 15, 2022 at 08:06:58AM -0800, Andres Freund wrote:\n> Hi,\n> \n> On 2022-02-15 08:58:05 -0500, Robert Haas wrote:\n> > On Mon, Feb 14, 2022 at 8:53 PM Andres Freund <andres@anarazel.de> wrote:\n> > > > An alternative rule which would dodge that particular issue would be\n> > > > to just slap PGDLLIMPORT on every global variable in every header\n> > > > file. That would arguably be a simpler rule, though it means even more\n> > > > PGDLLIMPORT declarations floating around.\n> > >\n> > > That would have the advantage of being comparatively easy to check in an\n> > > automated way. Might even be cheap enough to just make it part of the build.\n> > \n> > I wasn't able to quickly write something that was smart enough to use\n> > as part of the build, but I wrote something dumb that I think works\n> > well enough to use with a little bit of human intelligence alongside.\n> > See attached.\n> \n> Cool.\n\n+1\n\n> > > But it seems like it'd be a fair amount of work and cause a lot of patch\n> > > rebasing pain? If we end up going that way, we should schedule this to happen\n> > > just after the feature freeze, I think.\n> > \n> > We could do that. I'd sort of rather get it done. We still have two\n> > weeks before the last CommitFest officially starts, and it's not as if\n> > there won't be tons of uncommitted patches floating around after that.\n> \n> Breaking close to every patch 6-7 weeks before freeze doesn't seem\n> great. Particularly because this is a mostly automatically generated patch, so\n> I don't really see a forcing function to do this now, rather than at a more\n> opportune moment.\n\nAgreed, especially if we can do some cleanup in gendef.pl.\n\n> The more I think about it the more I'm convinced that if we want to do this,\n> we should do it for variables and functions.\n> \n> \n> > > If we consider doing this for all extern variables, we should think about\n> > > doing this for headers *and* functions. That'd allow us to get rid of the\n> > > fairly complicated logic to generate the .def file for the postgres binary on\n> > > windows (src/tools/gendef.pl). And maybe also the related thing on AIX\n> > > (src/backend/port/aix/mkldexport.sh)\n> > \n> > I don't know what you mean by this.\n> \n> We only need gendef.pl because we don't mark functions with visibility\n> information. If we attach PGDLLIMPORT to functions and variables we can a fair\n> bit of complexity. And I think not just for windows, but also AIX (there's a\n> whole section in src/backend/Makefile about AIX oddity), but I'm not sure\n> about it.\n\nI will try to have a look at it once my build environment is ready.\n\n\n", "msg_date": "Wed, 16 Feb 2022 01:19:56 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Tue, Feb 15, 2022 at 11:07 PM Andres Freund <andres@anarazel.de> wrote:\n\n> > diff --git a/src/include/common/relpath.h b/src/include/common/relpath.h\n> > index a4b5dc853b..13849a3790 100644\n> > --- a/src/include/common/relpath.h\n> > +++ b/src/include/common/relpath.h\n> > @@ -56,7 +56,7 @@ typedef enum ForkNumber\n> >\n> > #define FORKNAMECHARS 4 /* max chars for a fork name */\n> >\n> > -extern const char *const forkNames[];\n> > +extern PGDLLIMPORT const char *const forkNames[];\n> >\n> > extern ForkNumber forkname_to_number(const char *forkName);\n> > extern int forkname_chars(const char *str, ForkNumber *fork);\n>\n> I think we might need a new form of PGDLLIMPORT to mark these correctly - I\n> don't think they should be marked PGDLLIMPORT in frontend environment.\n\nThat has been taken care of already, IIUC:\n\ncommit e04a8059a74c125a8af94acdcb7b15b92188470a\nAuthor: Tom Lane <tgl@sss.pgh.pa.us>\nDate: Mon Nov 29 11:00:00 2021 -0500\n\n Simplify declaring variables exported from libpgcommon and libpgport.\n\n This reverts commits c2d1eea9e and 11b500072, as well as similar hacks\n elsewhere, in favor of setting up the PGDLLIMPORT macro so that it can\n just be used unconditionally. That can work because in frontend code,\n we need no marking in either the defining or consuming files for a\n variable exported from these libraries; and frontend code has no need\n to access variables exported from the core backend, either.\n\n-- \nJohn Naylor\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 16 Feb 2022 09:20:11 +0700", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Hi,\n\nOn 2022-02-15 08:06:58 -0800, Andres Freund wrote:\n> The more I think about it the more I'm convinced that if we want to do this,\n> we should do it for variables and functions.\n\nBtw, if we were to do this, we should just use -fvisibility=hidden everywhere\nand would see the same set of failures on unixoid systems as on windows. Of\ncourse only in in-core extensions, but it'd still be better than nothing.\n\nI proposed using -fvisibility=hidden in extensions:\nhttps://postgr.es/m/20211101020311.av6hphdl6xbjbuif@alap3.anarazel.de\n\nMostly because using explicit symbol exports makes it a lot easier to build\nextensions libraries on windows (with meson, but also everything built outside\nof postgres with msvc). But also because it makes function calls *inside* an\nextension have noticeably lower overhead. And it makes the set of symbols\nexported smaller.\n\n\nOne problem I encountered was that it's actually kind of hard to set build\nflags only for extension libraries:\nhttps://postgr.es/m/20220111025328.iq5g6uck53j5qtin%40alap3.anarazel.de\n\nBut if we added explicit exports to everything we export, we'd not need to\nrestrict the use of -fvisibility=hidden to extension libraries anymore. Would\nget decent error messages on all platforms.\n\n\nSubsequently we could yield a bit of performance from critical paths by\nmarking selected symbols as *not* exported. That'd make them a tad cheaper to\ncall and allow the optimizer more leeway.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 18 Feb 2022 16:02:18 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Fri, Feb 18, 2022 at 7:02 PM Andres Freund <andres@anarazel.de> wrote:\n> On 2022-02-15 08:06:58 -0800, Andres Freund wrote:\n> > The more I think about it the more I'm convinced that if we want to do this,\n> > we should do it for variables and functions.\n>\n> Btw, if we were to do this, we should just use -fvisibility=hidden everywhere\n> and would see the same set of failures on unixoid systems as on windows. Of\n> course only in in-core extensions, but it'd still be better than nothing.\n\nLet's be less ambitious for this release, and just get the variables\nmarked with PGDLLIMPORT. We seem to have consensus to create parity\nbetween Windows and non-Windows builds, which means precisely applying\nPGDLLIMPORT to variables marked in header files, and nothing more. The\nmerits of -fvisibility=hidden or PGDLLIMPORT on functions are a\nseparate question that can be debated on its own merits, but I don't\nwant that larger discussion to bog down this effort. Here are updated\npatches for that.\n\n@RMT: Andres proposed upthread that we should plan to do this just\nafter feature freeze. Accordingly I propose to commit at least 0002\nand perhaps 0001 if people want it just after feature freeze. I\ntherefore ask that the RMT either (a) regard this change as not being\na feature (and thus not subject to the freeze) or (b) give it a 1-day\nextension. The reason for committing it just after freeze is to\nminimize the number of conflicts that it creates for other patches.\nThe reason why that's probably an OK thing to do is that applying\nPGDLLIMPORT markings is low-risk.\n\nThanks,\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com", "msg_date": "Wed, 30 Mar 2022 14:37:21 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "\nOn 3/30/22 14:37, Robert Haas wrote:\n> On Fri, Feb 18, 2022 at 7:02 PM Andres Freund <andres@anarazel.de> wrote:\n>> On 2022-02-15 08:06:58 -0800, Andres Freund wrote:\n>>> The more I think about it the more I'm convinced that if we want to do this,\n>>> we should do it for variables and functions.\n>> Btw, if we were to do this, we should just use -fvisibility=hidden everywhere\n>> and would see the same set of failures on unixoid systems as on windows. Of\n>> course only in in-core extensions, but it'd still be better than nothing.\n> Let's be less ambitious for this release, and just get the variables\n> marked with PGDLLIMPORT. We seem to have consensus to create parity\n> between Windows and non-Windows builds, which means precisely applying\n> PGDLLIMPORT to variables marked in header files, and nothing more. The\n> merits of -fvisibility=hidden or PGDLLIMPORT on functions are a\n> separate question that can be debated on its own merits, but I don't\n> want that larger discussion to bog down this effort. Here are updated\n> patches for that.\n>\n> @RMT: Andres proposed upthread that we should plan to do this just\n> after feature freeze. Accordingly I propose to commit at least 0002\n> and perhaps 0001 if people want it just after feature freeze. I\n> therefore ask that the RMT either (a) regard this change as not being\n> a feature (and thus not subject to the freeze) or (b) give it a 1-day\n> extension. The reason for committing it just after freeze is to\n> minimize the number of conflicts that it creates for other patches.\n> The reason why that's probably an OK thing to do is that applying\n> PGDLLIMPORT markings is low-risk.\n>\n> Thanks,\n>\n\n\nWFM. I think Tom also has an item he wants to do right at the end of\nfeature freeze.\n\n\nThe script looks fine, needs a copyright notice and a comment at the top\ndescribing what it does. It seems like something we might need to do\nfrom time to time, as it will be easy to forget to mark variables and we\nshould periodically run this as a check.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n", "msg_date": "Tue, 5 Apr 2022 09:28:40 -0400", "msg_from": "Andrew Dunstan <andrew@dunslane.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Andrew Dunstan <andrew@dunslane.net> writes:\n> On 3/30/22 14:37, Robert Haas wrote:\n>> @RMT: Andres proposed upthread that we should plan to do this just\n>> after feature freeze. Accordingly I propose to commit at least 0002\n>> and perhaps 0001 if people want it just after feature freeze. I\n>> therefore ask that the RMT either (a) regard this change as not being\n>> a feature (and thus not subject to the freeze) or (b) give it a 1-day\n>> extension. The reason for committing it just after freeze is to\n>> minimize the number of conflicts that it creates for other patches.\n>> The reason why that's probably an OK thing to do is that applying\n>> PGDLLIMPORT markings is low-risk.\n\n> WFM. I think Tom also has an item he wants to do right at the end of\n> feature freeze.\n\nYeah, the frontend error message rework in [1]. That has exactly\nthe same constraint that it's likely to break other open patches,\nso it'd be better to do it after the CF cutoff. I think that doing\nthat concurrently with Robert's thing shouldn't be too risky, because\nit only affects frontend code while his patch should touch only backend.\n\n\t\t\tregards, tom lane\n\n[1] https://commitfest.postgresql.org/37/3574/\n\n\n", "msg_date": "Tue, 05 Apr 2022 10:06:54 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Tue, Apr 5, 2022 at 10:07 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Yeah, the frontend error message rework in [1]. That has exactly\n> the same constraint that it's likely to break other open patches,\n> so it'd be better to do it after the CF cutoff. I think that doing\n> that concurrently with Robert's thing shouldn't be too risky, because\n> it only affects frontend code while his patch should touch only backend.\n\nSo when *exactly* do we want to land these patches? None of the\ncalendar programs I use support \"anywhere on earth\" as a time zone,\nbut I think that feature freeze is 8am on Friday on the East coast of\nthe United States. If I commit the PGDLLIMPORT change within a few\nhours after that time, is that good? Should I try to do it earlier,\nbefore we technically hit 8am? Should I do it the night before, last\nthing before I go to bed on Thursday? Do you care whether your commit\nor mine goes in first?\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 5 Apr 2022 11:05:46 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Tue, Apr 5, 2022 at 10:06 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> On Tue, Apr 5, 2022 at 10:07 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > Yeah, the frontend error message rework in [1]. That has exactly\n> > the same constraint that it's likely to break other open patches,\n> > so it'd be better to do it after the CF cutoff. I think that doing\n> > that concurrently with Robert's thing shouldn't be too risky, because\n> > it only affects frontend code while his patch should touch only backend.\n>\n> So when *exactly* do we want to land these patches? None of the\n> calendar programs I use support \"anywhere on earth\" as a time zone,\n> but I think that feature freeze is 8am on Friday on the East coast of\n> the United States.\n\nI understand it to be noon UTC on Friday.\n\n> If I commit the PGDLLIMPORT change within a few\n> hours after that time, is that good? Should I try to do it earlier,\n> before we technically hit 8am? Should I do it the night before, last\n> thing before I go to bed on Thursday? Do you care whether your commit\n> or mine goes in first?\n\nFor these two patches, I'd say a day or two after feature freeze is a\nreasonable goal.\n\n--\nJohn Naylor\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 6 Apr 2022 00:57:29 +0700", "msg_from": "John Naylor <john.naylor@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> Do you care whether your commit\n> or mine goes in first?\n\nI do not. If they're not independent, at least one of us has messed up.\n\nI have family commitments on Saturday, so if I don't get mine in\non Friday it'll likely not happen before Sunday.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 05 Apr 2022 15:19:10 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Wed, Apr 06, 2022 at 12:57:29AM +0700, John Naylor wrote:\n> For these two patches, I'd say a day or two after feature freeze is a\n> reasonable goal.\n\nYeah. For patches as invasive as the PGDLLIMPORT business and the\nfrontend error refactoring, I am also fine to have two exceptions with\nthe freeze deadline.\n--\nMichael", "msg_date": "Thu, 7 Apr 2022 08:56:19 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Wed, Apr 6, 2022 at 7:56 PM Michael Paquier <michael@paquier.xyz> wrote:\n> On Wed, Apr 06, 2022 at 12:57:29AM +0700, John Naylor wrote:\n> > For these two patches, I'd say a day or two after feature freeze is a\n> > reasonable goal.\n>\n> Yeah. For patches as invasive as the PGDLLIMPORT business and the\n> frontend error refactoring, I am also fine to have two exceptions with\n> the freeze deadline.\n\nDone now.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 8 Apr 2022 08:42:38 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Fri, Apr 8, 2022 at 2:42 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Wed, Apr 6, 2022 at 7:56 PM Michael Paquier <michael@paquier.xyz>\n> wrote:\n> > On Wed, Apr 06, 2022 at 12:57:29AM +0700, John Naylor wrote:\n> > > For these two patches, I'd say a day or two after feature freeze is a\n> > > reasonable goal.\n> >\n> > Yeah. For patches as invasive as the PGDLLIMPORT business and the\n> > frontend error refactoring, I am also fine to have two exceptions with\n> > the freeze deadline.\n>\n> Done now.\n>\n\n\\o/\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, Apr 8, 2022 at 2:42 PM Robert Haas <robertmhaas@gmail.com> wrote:On Wed, Apr 6, 2022 at 7:56 PM Michael Paquier <michael@paquier.xyz> wrote:\n> On Wed, Apr 06, 2022 at 12:57:29AM +0700, John Naylor wrote:\n> > For these two patches, I'd say a day or two after feature freeze is a\n> > reasonable goal.\n>\n> Yeah.  For patches as invasive as the PGDLLIMPORT business and the\n> frontend error refactoring, I am also fine to have two exceptions with\n> the freeze deadline.\n\nDone now.\\o/ --  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Fri, 8 Apr 2022 15:04:18 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Fri, Apr 08, 2022 at 03:04:18PM +0200, Magnus Hagander wrote:\n> On Fri, Apr 8, 2022 at 2:42 PM Robert Haas <robertmhaas@gmail.com> wrote:\n> \n> > On Wed, Apr 6, 2022 at 7:56 PM Michael Paquier <michael@paquier.xyz>\n> > wrote:\n> > > On Wed, Apr 06, 2022 at 12:57:29AM +0700, John Naylor wrote:\n> > > > For these two patches, I'd say a day or two after feature freeze is a\n> > > > reasonable goal.\n> > >\n> > > Yeah. For patches as invasive as the PGDLLIMPORT business and the\n> > > frontend error refactoring, I am also fine to have two exceptions with\n> > > the freeze deadline.\n> >\n> > Done now.\n> >\n> \n> \\o/\n\nWoohoo! Thanks a lot!\n\n\n", "msg_date": "Fri, 8 Apr 2022 23:05:15 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Hi,\n\nOn 2022-04-08 08:42:38 -0400, Robert Haas wrote:\n> On Wed, Apr 6, 2022 at 7:56 PM Michael Paquier <michael@paquier.xyz> wrote:\n> > On Wed, Apr 06, 2022 at 12:57:29AM +0700, John Naylor wrote:\n> > > For these two patches, I'd say a day or two after feature freeze is a\n> > > reasonable goal.\n> >\n> > Yeah. For patches as invasive as the PGDLLIMPORT business and the\n> > frontend error refactoring, I am also fine to have two exceptions with\n> > the freeze deadline.\n> \n> Done now.\n\nJust noticed that\nextern sigset_t UnBlockSig,\n \t\t\tBlockSig,\n \t\t\tStartupBlockSig;\nare unadorned.\n\n\nThere's also a number of variables that are only declared in .c files that\n!windows can still access. Some likely aren't worth caring about, but some\nothers are underlying GUCs, so we probably do? E.g.\nCommitDelay\nCommitSiblings\ndefault_tablespace\nignore_checksum_failure\nignore_invalid_pages\nLog_disconnections\nssl_renegotiation_limit\ntemp_tablespaces\nUnix_socket_group\nUnix_socket_permissions\nwal_level_options\n\nLikely don't care:\ndynamic_shared_memory_options\ngistBufferingOptValues\nrecovery_target_action_options\nssl_protocol_versions_info\n\nAlso noticed that the bbsink_ops variables are const, instead of static const,\nwas that intentional?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 6 May 2022 16:49:24 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Fri, May 06, 2022 at 04:49:24PM -0700, Andres Freund wrote:\n> Just noticed that\n> extern sigset_t UnBlockSig,\n> \t\t\tBlockSig,\n> \t\t\tStartupBlockSig;\n> are unadorned.\n\nmark_pgdllimport.pl is not able to capture this part of the change\nbecause of this logic, where we assume that the header line has to\nfinish with a semicolon:\n# Variable declarations should end in a semicolon. If we see an\n# opening parenthesis, it's probably a function declaration.\n$needs_pgdllimport = 0 if $stripped_line !~ /;$/ ||\n $stripped_line =~ /\\(/;\n\nIt is quite common to define one variable per line, so I would not put\nthe blame on the script and just update pqsignal.h. And it is common\nto finish lines with a comma for function declarations..\n\n> There's also a number of variables that are only declared in .c files that\n> !windows can still access. Some likely aren't worth caring about, but some\n> others are underlying GUCs, so we probably do? E.g.\n> CommitDelay\n> CommitSiblings\n> default_tablespace\n> ignore_checksum_failure\n> ignore_invalid_pages\n> Log_disconnections\n> ssl_renegotiation_limit\n> temp_tablespaces\n> wal_level_options\n\nThese are indeed declared in .c files. So you mean that we'd better\ndeclare them in headers and mark them as PGDLLIMPORT? I am not sure\nif that's worth the addition, nobody has asked for these to be\navailable yet, AFAIK.\n\n> Unix_socket_group\n> Unix_socket_permissions\n\nAlready marked with PGDLLIMPORT.\n\n> Also noticed that the bbsink_ops variables are const, instead of static const,\n> was that intentional?\n\nYep, that looks like an error.\n\nWhile on it, I think that it would be a good idea to document in the\nscript that we need pass down a list of header files as arguments to\nrewrite them.\n--\nMichael", "msg_date": "Mon, 9 May 2022 16:15:35 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, May 9, 2022 at 3:15 AM Michael Paquier <michael@paquier.xyz> wrote:\n> On Fri, May 06, 2022 at 04:49:24PM -0700, Andres Freund wrote:\n> > Just noticed that\n> > extern sigset_t UnBlockSig,\n> > BlockSig,\n> > StartupBlockSig;\n> > are unadorned.\n>\n> mark_pgdllimport.pl is not able to capture this part of the change\n> because of this logic, where we assume that the header line has to\n> finish with a semicolon:\n> # Variable declarations should end in a semicolon. If we see an\n> # opening parenthesis, it's probably a function declaration.\n> $needs_pgdllimport = 0 if $stripped_line !~ /;$/ ||\n> $stripped_line =~ /\\(/;\n>\n> It is quite common to define one variable per line, so I would not put\n> the blame on the script and just update pqsignal.h. And it is common\n> to finish lines with a comma for function declarations..\n\nRight. I didn't try to equip the script with a real C parser. Just\nenough to catch our typical style - which those declarations aren't.\n\n> > There's also a number of variables that are only declared in .c files that\n> > !windows can still access. Some likely aren't worth caring about, but some\n> > others are underlying GUCs, so we probably do? E.g.\n> > CommitDelay\n> > CommitSiblings\n> > default_tablespace\n> > ignore_checksum_failure\n> > ignore_invalid_pages\n> > Log_disconnections\n> > ssl_renegotiation_limit\n> > temp_tablespaces\n> > wal_level_options\n>\n> These are indeed declared in .c files. So you mean that we'd better\n> declare them in headers and mark them as PGDLLIMPORT? I am not sure\n> if that's worth the addition, nobody has asked for these to be\n> available yet, AFAIK.\n\nCompletely agree. The agreed-upon charter was to adjust the header\nfiles, not move any declarations into header files. I'm not against\ndoing that; I think it's good for extensions to have access to GUC\nvalues. But it wasn't the mission.\n\n> > Also noticed that the bbsink_ops variables are const, instead of static const,\n> > was that intentional?\n>\n> Yep, that looks like an error.\n>\n> While on it, I think that it would be a good idea to document in the\n> script that we need pass down a list of header files as arguments to\n> rewrite them.\n\nEither of you please feel free to change these things, at least as far\nas I'm concerned.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 9 May 2022 09:23:47 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Mon, May 09, 2022 at 09:23:47AM -0400, Robert Haas wrote:\n> Either of you please feel free to change these things, at least as far\n> as I'm concerned.\n\nWell, what about the attached then? While looking at all the headers\nin the tree, I have noticed that __pg_log_level is not marked, but\nwe'd better paint a PGDLLIMPORT also for it? This is getting used by\npgbench for some unlikely() business, as one example.\n--\nMichael", "msg_date": "Tue, 10 May 2022 16:09:47 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Tue, May 10, 2022 at 04:09:47PM +0900, Michael Paquier wrote:\n> Well, what about the attached then? While looking at all the headers\n> in the tree, I have noticed that __pg_log_level is not marked, but\n> we'd better paint a PGDLLIMPORT also for it? This is getting used by\n> pgbench for some unlikely() business, as one example.\n\nAfter an extra look, PGDLLIMPORT missing from __pg_log_level looks\nlike an imbroglio between 8ec5694, that has added the marking, and\n9a374b77 that has removed it the same day. All that has been fixed in\n5edeb57.\n--\nMichael", "msg_date": "Thu, 12 May 2022 15:15:10 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Hi,\n\nOn 2022-05-12 15:15:10 +0900, Michael Paquier wrote:\n> On Tue, May 10, 2022 at 04:09:47PM +0900, Michael Paquier wrote:\n> > Well, what about the attached then? While looking at all the headers\n> > in the tree, I have noticed that __pg_log_level is not marked, but\n> > we'd better paint a PGDLLIMPORT also for it? This is getting used by\n> > pgbench for some unlikely() business, as one example.\n> \n> After an extra look, PGDLLIMPORT missing from __pg_log_level looks\n> like an imbroglio between 8ec5694, that has added the marking, and\n> 9a374b77 that has removed it the same day. All that has been fixed in\n> 5edeb57.\n\nIt seems pretty nonsensical to add PGDLLIMPORT to frontend only headers /\nvariables. What is that supposed to mean?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 12 May 2022 08:37:37 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2022-05-12 15:15:10 +0900, Michael Paquier wrote:\n>> After an extra look, PGDLLIMPORT missing from __pg_log_level looks\n>> like an imbroglio between 8ec5694, that has added the marking, and\n>> 9a374b77 that has removed it the same day. All that has been fixed in\n>> 5edeb57.\n\n> It seems pretty nonsensical to add PGDLLIMPORT to frontend only headers /\n> variables. What is that supposed to mean?\n\nYeah, that's why I removed it in 9a374b77.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 12 May 2022 11:59:49 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" }, { "msg_contents": "On Thu, May 12, 2022 at 11:59:49AM -0400, Tom Lane wrote:\n>> It seems pretty nonsensical to add PGDLLIMPORT to frontend only headers /\n>> variables. What is that supposed to mean?\n> \n> Yeah, that's why I removed it in 9a374b77.\n\nPerhaps we should try to remove it from the header itself in the long\nrun, even if that's used in a couple of macros? pgbench relies on it\nto avoid building a debug string for a meta-command, and logging.h has\nit in those compat macros.. I won't fight on that, though.\n\nAnyway, I'll go remove the marking. My apologies for the noise.\n--\nMichael", "msg_date": "Fri, 13 May 2022 09:05:44 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Mark all GUC variable as PGDLLIMPORT" } ]
[ { "msg_contents": "Hi,\n\nAfter [1], seawasp blew up[2]. I tested the following fix on LLVM 13\nand 14 (main branch ~2 days ago). Better ideas welcome.\n\n- if (F.getAttributes().hasFnAttribute(llvm::Attribute::NoInline))\n+#if LLVM_VERSION_MAJOR < 14\n+#define hasFnAttr hasFnAttribute\n+#endif\n+\n+ if (F.getAttributes().hasFnAttr(llvm::Attribute::NoInline))\n\n[1] https://github.com/llvm/llvm-project/commit/92ce6db9ee7666a347fccf0f72ba3225b199d6d1\n[2] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=seawasp&dt=2021-08-21%2023%3A17%3A30\n\n\n", "msg_date": "Mon, 23 Aug 2021 00:54:35 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Spelling change in LLVM 14 API" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n> After [1], seawasp blew up[2]. I tested the following fix on LLVM 13\n> and 14 (main branch ~2 days ago). Better ideas welcome.\n\n> - if (F.getAttributes().hasFnAttribute(llvm::Attribute::NoInline))\n> +#if LLVM_VERSION_MAJOR < 14\n> +#define hasFnAttr hasFnAttribute\n> +#endif\n> +\n> + if (F.getAttributes().hasFnAttr(llvm::Attribute::NoInline))\n\nSeems like either we should push back on pointless renaming, or else\nthat we're not really supposed to be accessing this non-stable API.\nI have no idea which of those situations applies ... but if the LLVM\nguys are randomly renaming methods that *are* supposed to be\nuser-visible, they need re-education.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 22 Aug 2021 09:22:43 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Spelling change in LLVM 14 API" }, { "msg_contents": "On 2021-Aug-22, Tom Lane wrote:\n\n> Thomas Munro <thomas.munro@gmail.com> writes:\n> > After [1], seawasp blew up[2]. I tested the following fix on LLVM 13\n> > and 14 (main branch ~2 days ago). Better ideas welcome.\n> \n> > - if (F.getAttributes().hasFnAttribute(llvm::Attribute::NoInline))\n> > +#if LLVM_VERSION_MAJOR < 14\n> > +#define hasFnAttr hasFnAttribute\n> > +#endif\n> > +\n> > + if (F.getAttributes().hasFnAttr(llvm::Attribute::NoInline))\n> \n> Seems like either we should push back on pointless renaming, or else\n> that we're not really supposed to be accessing this non-stable API.\n> I have no idea which of those situations applies ... but if the LLVM\n> guys are randomly renaming methods that *are* supposed to be\n> user-visible, they need re-education.\n\nDid anything happen? Seawasp is still red ...\n\n-- \nÁlvaro Herrera\n\n\n", "msg_date": "Sun, 29 Aug 2021 11:40:31 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Spelling change in LLVM 14 API" }, { "msg_contents": "Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> On 2021-Aug-22, Tom Lane wrote:\n>> Thomas Munro <thomas.munro@gmail.com> writes:\n>>> After [1], seawasp blew up[2]. I tested the following fix on LLVM 13\n>>> and 14 (main branch ~2 days ago). Better ideas welcome.\n>>> \n>>> - if (F.getAttributes().hasFnAttribute(llvm::Attribute::NoInline))\n>>> +#if LLVM_VERSION_MAJOR < 14\n>>> +#define hasFnAttr hasFnAttribute\n>>> +#endif\n>>> +\n>>> + if (F.getAttributes().hasFnAttr(llvm::Attribute::NoInline))\n\n>> Seems like either we should push back on pointless renaming, or else\n>> that we're not really supposed to be accessing this non-stable API.\n>> I have no idea which of those situations applies ... but if the LLVM\n>> guys are randomly renaming methods that *are* supposed to be\n>> user-visible, they need re-education.\n\n> Did anything happen? Seawasp is still red ...\n\nI stand by my opinion that Thomas' patch is a kluge rather than something\nwe should accept as a long-term answer. However, in the interests of\nkeeping the buildfarm green, maybe we should commit it until we have a\nbetter solution. It looks like seawasp is only building HEAD, so I think\nwe could commit this in HEAD only.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 29 Aug 2021 12:11:09 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Spelling change in LLVM 14 API" }, { "msg_contents": "On 2021-Aug-29, Tom Lane wrote:\n\n> I stand by my opinion that Thomas' patch is a kluge rather than something\n> we should accept as a long-term answer. However, in the interests of\n> keeping the buildfarm green, maybe we should commit it until we have a\n> better solution. It looks like seawasp is only building HEAD, so I think\n> we could commit this in HEAD only.\n\nWell, I definitely agree with your opinion, but perhaps we should\nconsider what to do in case LLVM developers decide not to care and keep\nthe rename. I'm not sure that polluting the tree with kludges for\ncross-LLVM-version compatibility is the best way to handle this kind of\nthing. Maybe it'd be better to try and centralize them in a single file\nperhaps. For example, pglogical has files for each PG version it\nsupports so that the main source code only has to use one wording of\neach call:\n\nhttps://github.com/2ndQuadrant/pglogical/blob/REL2_x_STABLE/compat14/pglogical_compat.h\nhttps://github.com/2ndQuadrant/pglogical/blob/REL2_x_STABLE/compat96/pglogical_compat.c\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"La rebeldía es la virtud original del hombre\" (Arthur Schopenhauer)\n\n\n", "msg_date": "Sun, 29 Aug 2021 12:47:38 -0400", "msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Spelling change in LLVM 14 API" }, { "msg_contents": "Hi,\n\nOn 2021-08-22 09:22:43 -0400, Tom Lane wrote:\n> Seems like either we should push back on pointless renaming, or else\n> that we're not really supposed to be accessing this non-stable API.\n\nUnfortunately LLVM only considers the C API (and even there only subsets) as\nstable. Most of our code uses the stable C API, but there are parts where that\nwasn't / isn't sufficient.\n\nThe weirdest part about this change [1] is that it's doing such a halfway\njob. There's plenty other variants of the hasFnAttribute() spelling around,\ne.g. in Function.h ([2]). I kinda get wanting to clean up that half the\nfunctions are named like hasFnAttr() and the other like hasFnAttribute(), but\nright now it seems to make things worse rather than better.\n\nRight now the easiest change would be to just use the\nFunction::hasFnAttribute() helper function. But I'm a bit loathe to do so\nbecause in a way one would hope that that gets changed too :(.\n\nThe next best thing seems to be to use the slightly longer form spelling, like\nthis:\n\ndiff --git i/src/backend/jit/llvm/llvmjit_inline.cpp w/src/backend/jit/llvm/llvmjit_inline.cpp\nindex 6f03595db5a..eb350003935 100644\n--- i/src/backend/jit/llvm/llvmjit_inline.cpp\n+++ w/src/backend/jit/llvm/llvmjit_inline.cpp\n@@ -594,7 +594,7 @@ function_inlinable(llvm::Function &F,\n \tif (F.materialize())\n \t\telog(FATAL, \"failed to materialize metadata\");\n \n-\tif (F.getAttributes().hasFnAttribute(llvm::Attribute::NoInline))\n+\tif (F.getAttributes().hasAttribute(llvm::Attribute::FunctionIndex, llvm::Attribute::NoInline))\n \t{\n \t\tilog(DEBUG1, \"ineligibile to import %s due to noinline\",\n \t\t\t F.getName().data());\n\nwhich seems not likely to fall under the same \"cleanup\" spree.\n\n\nOn 2021-08-29 12:47:38 -0400, Alvaro Herrera wrote:\n> On 2021-Aug-29, Tom Lane wrote:\n> > I stand by my opinion that Thomas' patch is a kluge rather than something\n> > we should accept as a long-term answer. However, in the interests of\n> > keeping the buildfarm green, maybe we should commit it until we have a\n> > better solution. It looks like seawasp is only building HEAD, so I think\n> > we could commit this in HEAD only.\n> \n> Well, I definitely agree with your opinion, but perhaps we should\n> consider what to do in case LLVM developers decide not to care and keep\n> the rename.\n\nYea :(.\n\nI just pinged them, but I don't have much hope that this will be backed out at\nthis point. There's probably more llvm users that already adapted their code\nthan \"us\".\n\n\n> I'm not sure that polluting the tree with kludges for\n> cross-LLVM-version compatibility is the best way to handle this kind of\n> thing. Maybe it'd be better to try and centralize them in a single file\n> perhaps.\n\nI think that makes sense for things that are in more than one place, but if\nthere's just a single case of the ifdef it doesn't seem that obvious to me. In\nparticular because there's a C / C++ boundary involved here...\n\nGreetings,\n\nAndres Freund\n\n\n[1] https://github.com/llvm/llvm-project/commit/92ce6db9ee7666a347fccf0f72ba3225b199d6d1\n[2] https://github.com/llvm/llvm-project/blob/96d329455501dd9f7b38c6f4c5d54c7e13247dd1/llvm/include/llvm/IR/Function.h#L390\n\n\n", "msg_date": "Sun, 29 Aug 2021 10:40:59 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Spelling change in LLVM 14 API" }, { "msg_contents": "On Mon, Aug 30, 2021 at 5:41 AM Andres Freund <andres@anarazel.de> wrote:\n> - if (F.getAttributes().hasFnAttribute(llvm::Attribute::NoInline))\n> + if (F.getAttributes().hasAttribute(llvm::Attribute::FunctionIndex, llvm::Attribute::NoInline))\n\nYeah, that's already stopped working since you wrote it a few weeks\nago... There's also been a second breakage site in our code due to\nLLVM commit 85b732b5. New fix attached. Tested on LLVM 7, 9, 13, 14\n(= LLVM main branch commit 945df8bc4cf3 built 2021-09-15).\n\nEven though the macro approach is ugly, we're already handling every\nother API change that way, and at least it's at least very clear which\nlines to delete in a few years when older LLVMs fall off the conveyor\nbelt of time. Admittedly renaming an identifiers is a new kludge, but\nI didn't want to duplicate the whole if block or confuse pgindent.", "msg_date": "Fri, 24 Sep 2021 12:52:09 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Spelling change in LLVM 14 API" }, { "msg_contents": "On Fri, Sep 24, 2021 at 12:52 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> Yeah, that's already stopped working since you wrote it a few weeks\n> ago... There's also been a second breakage site in our code due to\n> LLVM commit 85b732b5. New fix attached. Tested on LLVM 7, 9, 13, 14\n> (= LLVM main branch commit 945df8bc4cf3 built 2021-09-15).\n\nAnd pushed. Probably won't be the last change and seawasp only tests\nmaster, so no back-patch for now.\n\n\n", "msg_date": "Mon, 27 Sep 2021 10:54:27 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Spelling change in LLVM 14 API" }, { "msg_contents": "On Mon, Sep 27, 2021 at 10:54 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> And pushed. Probably won't be the last change and seawasp only tests\n> master, so no back-patch for now.\n\nAccording to my crystal ball, seawasp will shortly break again[1][2]\nand the attached patch will fix it.\n\n[1] https://github.com/llvm/llvm-project/commit/f6fa95b77f33c3690e4201e505cb8dce1433abd9\n[2] https://github.com/llvm/llvm-project/commit/e463b69736da8b0a950ecd937cf990401bdfcdeb", "msg_date": "Tue, 26 Oct 2021 13:39:53 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Spelling change in LLVM 14 API" }, { "msg_contents": "Hi,\n\nOn 2021-10-26 13:39:53 +1300, Thomas Munro wrote:\n> On Mon, Sep 27, 2021 at 10:54 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> > And pushed. Probably won't be the last change and seawasp only tests\n> > master, so no back-patch for now.\n> \n> According to my crystal ball, seawasp will shortly break again[1][2]\n> and the attached patch will fix it.\n\nThat feels lot more convincing though. Based on past experience it's not hard\nto believe that the compile-time impact of the include the use of std::string\nforces into a lot of places is pretty significant...\n\nCould we make old case a wrapper around the new case that just passes on the\nerror as a const char *? That should be more maintainable long-term, because\nthere's only one copy of the body?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 25 Oct 2021 17:51:57 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Spelling change in LLVM 14 API" }, { "msg_contents": "On Tue, Oct 26, 2021 at 1:52 PM Andres Freund <andres@anarazel.de> wrote:\n> On 2021-10-26 13:39:53 +1300, Thomas Munro wrote:\n> > According to my crystal ball, seawasp will shortly break again[1][2]\n> > and the attached patch will fix it.\n>\n> That feels lot more convincing though. Based on past experience it's not hard\n> to believe that the compile-time impact of the include the use of std::string\n> forces into a lot of places is pretty significant...\n>\n> Could we make old case a wrapper around the new case that just passes on the\n> error as a const char *? That should be more maintainable long-term, because\n> there's only one copy of the body?\n\nHere's one like that. The previous message \"Track LLVM 14 API\nchanges\" didn't seem too scalable so I added date and commit ID.", "msg_date": "Tue, 26 Oct 2021 14:21:40 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Spelling change in LLVM 14 API" }, { "msg_contents": "On Tue, Oct 26, 2021 at 2:21 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> Here's one like that. The previous message \"Track LLVM 14 API\n> changes\" didn't seem too scalable so I added date and commit ID.\n\nseawasp finally caught up with these LLVM changes and turned red. I\nretested the patch against this week's LLVM locally. New version also\nadds #include <new>, for the definition of std::new_handler, which g++\nis now complaining about in llvmjit_error.cpp.\n\nSince then, the LLVM 14 headers have started spewing deprecation\nnotices about LLVMBuildStructGEP, LLVMBuildLoad, LLVMBuildCall. The\nwarnings say things like \"Use LLVMBuildStructGEP2 instead to support\nopaque pointers\", and the -2 variants need a new argument that takes\nan extra LLVMTypeRef argument, but I didn't look further...", "msg_date": "Mon, 31 Jan 2022 18:34:16 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Spelling change in LLVM 14 API" } ]
[ { "msg_contents": "Hi, all\n\nRecently, I got a problem that the startup process of standby is stuck and keeps in a waiting state. The backtrace of startup process shows that it is waiting for a backend process which conflicts with recovery processing to exit, the guc parameters max_standby_streaming_delay and max_standby_archive_delay are both set as 30 seconds, but it doesn't work. The backend process keeps alive, and the backtrace of this backend process show that it is waiting for the socket to be writeable in secure_write(). After further reading the code, I found that ProcessClientWriteInterrupt() in secure_write() only process interrupts when ProcDiePending is true, otherwise do nothing. However, snapshot conflicts with recovery will only set QueryCancelPending as true, so the response to the signal will de delayed indefinitely if the corresponding client is stuck, thus blocking the recovery process.\n\nI want to know why the interrupt is only handled when ProcDiePending is true, I think query which is supposed to be canceled also should respond to the signal.\n\nI also want to share a patch with you, I add a guc parameter max_standby_client_write_delay, if a query is supposed to be canceled, and the time delayed by a client exceeds max_standby_client_write_delay, then set ProcDiePending as true to avoid being delayed indefinitely, what do you think of it, hope to get your reply.\n\nThanks & Best Regard", "msg_date": "Mon, 23 Aug 2021 01:08:32 +0800", "msg_from": "\"=?UTF-8?B?6JSh5qKm5aifKOeOiuS6jik=?=\" <mengjuan.cmj@alibaba-inc.com>", "msg_from_op": true, "msg_subject": "\n =?UTF-8?B?UXVlcmllcyB0aGF0IHNob3VsZCBiZSBjYW5jZWxlZCB3aWxsIGdldCBzdHVjayBvbiBzZWN1?=\n =?UTF-8?B?cmVfd3JpdGUgZnVuY3Rpb24=?=" } ]
[ { "msg_contents": "Hackers,\n\nPlease find attached an improvement to the error messages given for invalid backreference usage:\n\n select 'xyz' ~ '(.)(.)\\3';\n ERROR: invalid regular expression: invalid backreference number\n select 'xyz' ~ '(.)(.)(?=\\2)';\n-ERROR: invalid regular expression: invalid backreference number\n+ERROR: invalid regular expression: backreference in lookaround assertion\n\nThe first regexp is invalid because only two capture groups exist, so \\3 doesn't refer to anything. The second regexp is rejected because the regular expression system does not support backreferences within lookaround assertions. (See the docs, section 9.7.3.6. Limits And Compatibility.) It is flat wrong to say the backreference number is invalid. There is a perfectly valid capture that \\2 refers to. \n\nThe patch defines a new error code REG_ENOBREF in regex/regex.h right next to REG_ESUBREG from which it is split out, rather than at the end of the list. Is there a project preference to add it at the end? Certainly, that would give a shorter git diff.\n\nAre there dependencies on the current error messages which prevent such changes?\n\n\n\n \n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Sun, 22 Aug 2021 17:26:40 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Improved regular expression error message for backrefs" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> The patch defines a new error code REG_ENOBREF in regex/regex.h right next to REG_ESUBREG from which it is split out, rather than at the end of the list. Is there a project preference to add it at the end? Certainly, that would give a shorter git diff.\n> Are there dependencies on the current error messages which prevent such changes?\n\nYeah: the POSIX standard says what the error codes from regcomp() are.\n\nPOSIX defines\n\n\tREG_ESUBREG\n\t\tNumber in \\digit invalid or in error.\n\nwhich does seem to cover this case, so what I'd argue is that we should\nimprove the \"invalid backreference number\" text rather than invent\na nonstandard error code. Maybe about like \"backreference number does\nnot exist or cannot be referenced from here\"?\n\n(Admittedly, there's not a huge reason why src/backend/regex/ needs to\nstay compliant with the POSIX API today. But I still have ambitions to\nsplit that out as a free-standing library someday, as Henry Spencer had\noriginally planned to do. So I'd rather stick to the API spec.)\n\nIt might be worth checking what text is attributed to this error code\nby PCRE and other implementations of the POSIX spec.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 22 Aug 2021 22:47:25 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Improved regular expression error message for backrefs" }, { "msg_contents": "\n\n> On Aug 22, 2021, at 7:47 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Yeah: the POSIX standard says what the error codes from regcomp() are.\n\nI'm not sure how to interpret them. The language \"The implementation may define additional macros or constants using names beginning with REG_\" at the bottom of the docs might imply that one can add to the list.\n\n> POSIX defines\n> \n> \tREG_ESUBREG\n> \t\tNumber in \\digit invalid or in error.\n> \n> which does seem to cover this case,\n\nHmm. The number is neither invalid nor in error. The only thing arguing in favor of using this code is that the error message contains the word \"backreference\":\n\n\t\"REG_ESUBREG\", \"invalid backreference number\"\n\nwhich gives the reader a clue that the problem has something to do with a backreference in the pattern. But the POSIX wording \"Number in \\digit invalid or in error.\" doesn't even have that advantage. We seem to be using the wrong return code. I would think a more generic \n\n\tREG_BADPAT\n\t\tInvalid regular expression.\n\nwould be the correct code, though arguably far less informative.\n\n> so what I'd argue is that we should\n> improve the \"invalid backreference number\" text rather than invent\n> a nonstandard error code. Maybe about like \"backreference number does\n> not exist or cannot be referenced from here\"?\n\nAssuming we leave the error codes alone, how about, \"backreference number invalid or cannot be referenced from here\"?\n\n> (Admittedly, there's not a huge reason why src/backend/regex/ needs to\n> stay compliant with the POSIX API today. But I still have ambitions to\n> split that out as a free-standing library someday, as Henry Spencer had\n> originally planned to do. So I'd rather stick to the API spec.)\n\nThat's fine. Something else might kill that ambition, but this quibble over error messages isn't nearly important enough to do so.\n\n> It might be worth checking what text is attributed to this error code\n> by PCRE and other implementations of the POSIX spec.\n\nReading the docs at pcre.org, it appears that capture groups are allowed in look-around assertions. Our engine doesn't do that, instead treating all groups within assertions as non-capturing. I don't see anything about whether backreferences are allowed within pcre assertions, but I know that perl itself does allow them. So maybe the error text used by other implementations is irrelevant?\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Sun, 22 Aug 2021 20:37:12 -0700", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": true, "msg_subject": "Re: Improved regular expression error message for backrefs" } ]