threads
listlengths 1
2.99k
|
|---|
[
{
"msg_contents": "This array of tranche names is looking pretty ugly these days, and it'll\nget worse as we add more members to it. I propose to use C99 designated\ninitializers, like we've done for other arrays. Patch attached.\n\nThe way I've coded in this patch, it means the array will now have 52\nNULL pointers at the beginning. I don't think this is a big deal and\nmakes the code prettier. I see two alternatives:\n\n1. Avoid all those NULLs by making each definition uglier (subtract\nNUM_INDIVIDUAL_LWLOCKS from each array index) _and_ the usage of the\narray by subtracting the same amount. This saves 208 bytes at the\nexpense of making the code worse.\n\n2. More invasively, rework generate-lwlocknames.pl so that both lwlocks\nand these builtin tranche names appear in a single array. (We could do\nso by #include'ing lwlocknames.c at the top of the array).\n\n\nNow, having written this proposal, I'm leaning towards idea 2 myself,\nbut since the patch here is less invasive, it seems worth having as\nevidence.\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n\"People get annoyed when you try to debug them.\" (Larry Wall)",
"msg_date": "Tue, 23 Jan 2024 11:25:25 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "make BuiltinTrancheNames less ugly"
},
{
"msg_contents": "On 23/01/2024 12:25, Alvaro Herrera wrote:\n> This array of tranche names is looking pretty ugly these days, and it'll\n> get worse as we add more members to it. I propose to use C99 designated\n> initializers, like we've done for other arrays. Patch attached.\n> \n> The way I've coded in this patch, it means the array will now have 52\n> NULL pointers at the beginning. I don't think this is a big deal and\n> makes the code prettier. I see two alternatives:\n> \n> 1. Avoid all those NULLs by making each definition uglier (subtract\n> NUM_INDIVIDUAL_LWLOCKS from each array index) _and_ the usage of the\n> array by subtracting the same amount. This saves 208 bytes at the\n> expense of making the code worse.\n> \n> 2. More invasively, rework generate-lwlocknames.pl so that both lwlocks\n> and these builtin tranche names appear in a single array. (We could do\n> so by #include'ing lwlocknames.c at the top of the array).\n> \n> \n> Now, having written this proposal, I'm leaning towards idea 2 myself,\n> but since the patch here is less invasive, it seems worth having as\n> evidence.\n\nIdea 2 seems pretty straightforward, +1 for that.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Tue, 23 Jan 2024 12:33:50 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: make BuiltinTrancheNames less ugly"
},
{
"msg_contents": "On 2024-Jan-23, Heikki Linnakangas wrote:\n\n> On 23/01/2024 12:25, Alvaro Herrera wrote:\n\n> > 2. More invasively, rework generate-lwlocknames.pl so that both lwlocks\n> > and these builtin tranche names appear in a single array. (We could do\n> > so by #include'ing lwlocknames.c at the top of the array).\n\n> Idea 2 seems pretty straightforward, +1 for that.\n\nThis is what I came up with. For the compilation framework (both\nMakefile and meson) I mostly just copied what we do in src/backend/node,\nwhich seems to have passed CI just fine, but maybe there are better ways\nto achieve it.\n\n... oh, actually FreeBSD failed with this strange problem while linking:\n[11:39:43.550] ld: error: undefined symbol: __dtraceenabled_postgresql___lwlock__wait__start\n[11:39:43.551] >>> referenced by lwlock.c:1277 (../src/backend/storage/lmgr/lwlock.c:1277)\n[11:39:43.551] >>> lwlock.a.p/lwlock.c.o:(LWLockAcquire) in archive src/backend/storage/lmgr/lwlock.a\n[11:39:43.551] >>> referenced by lwlock.c:1442 (../src/backend/storage/lmgr/lwlock.c:1442)\n[11:39:43.551] >>> lwlock.a.p/lwlock.c.o:(LWLockAcquireOrWait) in archive src/backend/storage/lmgr/lwlock.a\n[11:39:43.551] >>> referenced by lwlock.c:1660 (../src/backend/storage/lmgr/lwlock.c:1660)\n[11:39:43.551] >>> lwlock.a.p/lwlock.c.o:(LWLockWaitForVar) in archive src/backend/storage/lmgr/lwlock.a\n[11:39:43.551] \n [ further similar lines ]\nhttps://cirrus-ci.com/task/5055489315176448?logs=build#L1091\n\nI have no idea what this means or how is it related to what I'm doing.\n\n\nIMO it would be less ugly to have the origin file lwlocknames.txt be not\na text file but a .h with a macro that can be defined by interested\nparties so that they can extract what they want from the file, like\nPG_CMDTAG or PG_KEYWORD. Using Perl for this seems dirty ...\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n\"In Europe they call me Niklaus Wirth; in the US they call me Nickel's worth.\n That's because in Europe they call me by name, and in the US by value!\"\n\n\n",
"msg_date": "Tue, 23 Jan 2024 12:47:42 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "Re: make BuiltinTrancheNames less ugly"
},
{
"msg_contents": "On 2024-Jan-23, Alvaro Herrera wrote:\n\n> ... oh, actually FreeBSD failed with this strange problem while linking:\n> [11:39:43.550] ld: error: undefined symbol: __dtraceenabled_postgresql___lwlock__wait__start\n> [11:39:43.551] >>> referenced by lwlock.c:1277 (../src/backend/storage/lmgr/lwlock.c:1277)\n> [11:39:43.551] >>> lwlock.a.p/lwlock.c.o:(LWLockAcquire) in archive src/backend/storage/lmgr/lwlock.a\n> [11:39:43.551] >>> referenced by lwlock.c:1442 (../src/backend/storage/lmgr/lwlock.c:1442)\n> [11:39:43.551] >>> lwlock.a.p/lwlock.c.o:(LWLockAcquireOrWait) in archive src/backend/storage/lmgr/lwlock.a\n> [11:39:43.551] >>> referenced by lwlock.c:1660 (../src/backend/storage/lmgr/lwlock.c:1660)\n> [11:39:43.551] >>> lwlock.a.p/lwlock.c.o:(LWLockWaitForVar) in archive src/backend/storage/lmgr/lwlock.a\n> [11:39:43.551] \n\nSo what's going on here is that lwlock.c is being compiled to a separate\narchive (lwlock.a), and when linking it wants to see the dtrace symbols\n(__dtraceenabled_postgresql___lwlock__wait__start et al) but it looks\nlike they're not defined.\n\nI installed systemtap on my machine and reconfigured meson with it so\nthat it uses dtrace, and it compiles successfully. One interesting\npoint: on my ninja log, I see dtrace being invoked, which I do not in\nthe FreeBSD log.\n\nI continue to not understand what is going on.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"El sabio habla porque tiene algo que decir;\nel tonto, porque tiene que decir algo\" (Platon).\n\n\n",
"msg_date": "Tue, 23 Jan 2024 13:39:58 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "Re: make BuiltinTrancheNames less ugly"
},
{
"msg_contents": "On 2024-Jan-23, Alvaro Herrera wrote:\n\n> This is what I came up with.\n\nHm, I forgot the attachment, thanks Heikki for the reminder.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"Las mujeres son como hondas: mientras más resistencia tienen,\n más lejos puedes llegar con ellas\" (Jonas Nightingale, Leap of Faith)",
"msg_date": "Tue, 23 Jan 2024 14:05:13 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "Re: make BuiltinTrancheNames less ugly"
},
{
"msg_contents": "On 2024-Jan-23, Alvaro Herrera wrote:\n\n> ... oh, actually FreeBSD failed with this strange problem while linking:\n\nI figured this out. For dtrace support, we need to run dtrace on all\nthe objects produced by the compilation step, but because I took\nlwlock.o out of the objects used to produce the backend into its own\n\"library\", it needs to be included explicitly. (I think this is not a\nproblem for things like nodes/copyfuncs.c only because those files don't\nhave any use of TRACE macros).\n\nSo here's v3, which now passes fully in CI.\n\nI'm a total newbie to Meson, so it's likely that there are better ways\nto implement this. I'll leave this here for a little bit in case\nanybody wants to comment.\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/\n\"El sudor es la mejor cura para un pensamiento enfermo\" (Bardia)",
"msg_date": "Tue, 23 Jan 2024 15:42:39 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "Re: make BuiltinTrancheNames less ugly"
},
{
"msg_contents": "On 2024-Jan-23, Alvaro Herrera wrote:\n\n> I'm a total newbie to Meson, so it's likely that there are better ways\n> to implement this. I'll leave this here for a little bit in case\n> anybody wants to comment.\n\nOK, I pushed the array definition, and here's the other bits as a\nfollowup patch. I'll add it to the next commitfest, though I hope to\nget it committed before then, either in this form or whatever different\nMeson trickery is recommended.\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n\"Every machine is a smoke machine if you operate it wrong enough.\"\nhttps://twitter.com/libseybieda/status/1541673325781196801",
"msg_date": "Wed, 24 Jan 2024 15:09:49 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "Re: make BuiltinTrancheNames less ugly"
},
{
"msg_contents": "On Wed Jan 24, 2024 at 8:09 AM CST, Alvaro Herrera wrote:\n> From 3d24b89855888a6650ec1aafb3579d810bfec5ac Mon Sep 17 00:00:00 2001\n> From: Alvaro Herrera <alvherre@alvh.no-ip.org>\n> Date: Tue, 23 Jan 2024 10:36:14 +0100\n> Subject: [PATCH] Remove IndividualLWLockNames\n>\n> We can just merge the lwlock names into the BuiltinTrancheNames array.\n> This requires that Meson compiles the file with -I. in CPPFLAGS, which\n> in turn requires some additional contortions for DTrace support in\n> FreeBSD.\n> ---\n> src/backend/meson.build | 4 +++-\n> src/backend/storage/lmgr/Makefile | 3 ++-\n> src/backend/storage/lmgr/generate-lwlocknames.pl | 10 ++--------\n> src/backend/storage/lmgr/lwlock.c | 13 ++++---------\n> src/backend/storage/lmgr/meson.build | 12 ++++++++++--\n> 5 files changed, 21 insertions(+), 21 deletions(-)\n>\n> diff --git a/src/backend/meson.build b/src/backend/meson.build\n> index 8767aaba67..57a52c37e0 100644\n> --- a/src/backend/meson.build\n> +++ b/src/backend/meson.build\n> @@ -127,7 +127,9 @@ backend_objs = [postgres_lib.extract_all_objects(recursive: false)]\n> if dtrace.found() and host_system != 'darwin'\n> backend_input += custom_target(\n> 'probes.o',\n> - input: ['utils/probes.d', postgres_lib.extract_objects(backend_sources, timezone_sources)],\n> + input: ['utils/probes.d',\n> + postgres_lib.extract_objects(backend_sources, timezone_sources),\n> + lwlock_lib.extract_objects(lwlock_source)],\n> output: 'probes.o',\n> command: [dtrace, '-C', '-G', '-o', '@OUTPUT@', '-s', '@INPUT@'],\n> install: false,\n> diff --git a/src/backend/storage/lmgr/Makefile b/src/backend/storage/lmgr/Makefile\n> index 504480e847..81da6ee13a 100644\n> --- a/src/backend/storage/lmgr/Makefile\n> +++ b/src/backend/storage/lmgr/Makefile\n> @@ -12,13 +12,14 @@ subdir = src/backend/storage/lmgr\n> top_builddir = ../../../..\n> include $(top_builddir)/src/Makefile.global\n> \n> +override CPPFLAGS := -I. $(CPPFLAGS)\n> +\n> OBJS = \\\n> \tcondition_variable.o \\\n> \tdeadlock.o \\\n> \tlmgr.o \\\n> \tlock.o \\\n> \tlwlock.o \\\n> -\tlwlocknames.o \\\n> \tpredicate.o \\\n> \tproc.o \\\n> \ts_lock.o \\\n> diff --git a/src/backend/storage/lmgr/generate-lwlocknames.pl b/src/backend/storage/lmgr/generate-lwlocknames.pl\n> index 7b93ecf6c1..a679a4ff54 100644\n> --- a/src/backend/storage/lmgr/generate-lwlocknames.pl\n> +++ b/src/backend/storage/lmgr/generate-lwlocknames.pl\n> @@ -10,7 +10,6 @@ use Getopt::Long;\n> my $output_path = '.';\n> \n> my $lastlockidx = -1;\n> -my $continue = \"\\n\";\n> \n> GetOptions('outdir:s' => \\$output_path);\n> \n> @@ -29,8 +28,6 @@ print $h $autogen;\n> print $h \"/* there is deliberately not an #ifndef LWLOCKNAMES_H here */\\n\\n\";\n> print $c $autogen, \"\\n\";\n> \n> -print $c \"const char *const IndividualLWLockNames[] = {\";\n> -\n> #\n> # First, record the predefined LWLocks listed in wait_event_names.txt. We'll\n> # cross-check those with the ones in lwlocknames.txt.\n> @@ -97,12 +94,10 @@ while (<$lwlocknames>)\n> \twhile ($lastlockidx < $lockidx - 1)\n> \t{\n> \t\t++$lastlockidx;\n> -\t\tprintf $c \"%s\t\\\"<unassigned:%d>\\\"\", $continue, $lastlockidx;\n> -\t\t$continue = \",\\n\";\n> +\t\tprintf $c \"[%s] = \\\"<unassigned:%d>\\\",\\n\", $lastlockidx, $lastlockidx;\n> \t}\n> -\tprintf $c \"%s\t\\\"%s\\\"\", $continue, $trimmedlockname;\n> +\tprintf $c \"[%s] = \\\"%s\\\",\\n\", $lockidx, $trimmedlockname;\n> \t$lastlockidx = $lockidx;\n> -\t$continue = \",\\n\";\n> \n> \tprint $h \"#define $lockname (&MainLWLockArray[$lockidx].lock)\\n\";\n> }\n> @@ -112,7 +107,6 @@ die\n> . \"lwlocknames.txt\"\n> if $i < scalar @wait_event_lwlocks;\n> \n> -printf $c \"\\n};\\n\";\n> print $h \"\\n\";\n> printf $h \"#define NUM_INDIVIDUAL_LWLOCKS\t\t%s\\n\", $lastlockidx + 1;\n> \n> diff --git a/src/backend/storage/lmgr/lwlock.c b/src/backend/storage/lmgr/lwlock.c\n> index 98fa6035cc..8aad9c6690 100644\n> --- a/src/backend/storage/lmgr/lwlock.c\n> +++ b/src/backend/storage/lmgr/lwlock.c\n> @@ -115,8 +115,8 @@ StaticAssertDecl(LW_VAL_EXCLUSIVE > (uint32) MAX_BACKENDS,\n> * There are three sorts of LWLock \"tranches\":\n> *\n> * 1. The individually-named locks defined in lwlocknames.h each have their\n> - * own tranche. The names of these tranches appear in IndividualLWLockNames[]\n> - * in lwlocknames.c.\n> + * own tranche. The names of these tranches come from lwlocknames.c into\n> + * BuiltinTranchNames[] below.\n> *\n> * 2. There are some predefined tranches for built-in groups of locks.\n> * These are listed in enum BuiltinTrancheIds in lwlock.h, and their names\n> @@ -129,9 +129,8 @@ StaticAssertDecl(LW_VAL_EXCLUSIVE > (uint32) MAX_BACKENDS,\n> * All these names are user-visible as wait event names, so choose with care\n> * ... and do not forget to update the documentation's list of wait events.\n> */\n> -extern const char *const IndividualLWLockNames[];\t/* in lwlocknames.c */\n> -\n> static const char *const BuiltinTrancheNames[] = {\n> +#include \"lwlocknames.c\"\n> \t[LWTRANCHE_XACT_BUFFER] = \"XactBuffer\",\n> \t[LWTRANCHE_COMMITTS_BUFFER] = \"CommitTsBuffer\",\n> \t[LWTRANCHE_SUBTRANS_BUFFER] = \"SubtransBuffer\",\n> @@ -738,11 +737,7 @@ LWLockReportWaitEnd(void)\n> static const char *\n> GetLWTrancheName(uint16 trancheId)\n> {\n> -\t/* Individual LWLock? */\n> -\tif (trancheId < NUM_INDIVIDUAL_LWLOCKS)\n> -\t\treturn IndividualLWLockNames[trancheId];\n> -\n> -\t/* Built-in tranche? */\n> +\t/* Individual LWLock or built-in tranche? */\n> \tif (trancheId < LWTRANCHE_FIRST_USER_DEFINED)\n> \t\treturn BuiltinTrancheNames[trancheId];\n> \n> diff --git a/src/backend/storage/lmgr/meson.build b/src/backend/storage/lmgr/meson.build\n> index da32198f78..a12064ae8a 100644\n> --- a/src/backend/storage/lmgr/meson.build\n> +++ b/src/backend/storage/lmgr/meson.build\n> @@ -5,11 +5,19 @@ backend_sources += files(\n> 'deadlock.c',\n> 'lmgr.c',\n> 'lock.c',\n> - 'lwlock.c',\n> 'predicate.c',\n> 'proc.c',\n> 's_lock.c',\n> 'spin.c',\n> )\n> \n> -generated_backend_sources += lwlocknames[1]\n> +# this includes a .c file generated. Is there a better way?\n> +lwlock_source = files('lwlock.c')\n\nI don't understand this comment. Could you explain it a bit more?\n\n> +\n> +lwlock_lib = static_library('lwlock',\n> + lwlock_source,\n> + dependencies: [backend_code],\n> + include_directories: include_directories('../../../include/storage'),\n> + kwargs: internal_lib_args,\n> + )\n\nMove the paren to the beginning of the line.\n\n> +backend_link_with += lwlock_lib\n\nEarlier in the thread you had said this:\n\n> IMO it would be less ugly to have the origin file lwlocknames.txt be\n> not a text file but a .h with a macro that can be defined by\n> interested parties so that they can extract what they want from the\n> file, like PG_CMDTAG or PG_KEYWORD. Using Perl for this seems dirty...\n\nI really like this idea, and would definitely be more inclined to see \na solution like this.\n\n-- \nTristan Partin\nNeon (https://neon.tech)\n\n\n",
"msg_date": "Mon, 12 Feb 2024 11:01:51 -0600",
"msg_from": "\"Tristan Partin\" <tristan@neon.tech>",
"msg_from_op": false,
"msg_subject": "Re: make BuiltinTrancheNames less ugly"
},
{
"msg_contents": "On 12/02/2024 19:01, Tristan Partin wrote:\n> On Wed Jan 24, 2024 at 8:09 AM CST, Alvaro Herrera wrote:\n>> IMO it would be less ugly to have the origin file lwlocknames.txt be\n>> not a text file but a .h with a macro that can be defined by\n>> interested parties so that they can extract what they want from the\n>> file, like PG_CMDTAG or PG_KEYWORD. Using Perl for this seems dirty...\n> \n> I really like this idea, and would definitely be more inclined to see\n> a solution like this.\n\n+1 to that idea from me too. Seems pretty straightforward.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Fri, 23 Feb 2024 11:31:12 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: make BuiltinTrancheNames less ugly"
},
{
"msg_contents": "On 2024-Feb-23, Heikki Linnakangas wrote:\n\n> On 12/02/2024 19:01, Tristan Partin wrote:\n> > On Wed Jan 24, 2024 at 8:09 AM CST, Alvaro Herrera wrote:\n> > > IMO it would be less ugly to have the origin file lwlocknames.txt be\n> > > not a text file but a .h with a macro that can be defined by\n> > > interested parties so that they can extract what they want from the\n> > > file, like PG_CMDTAG or PG_KEYWORD. Using Perl for this seems dirty...\n> > \n> > I really like this idea, and would definitely be more inclined to see\n> > a solution like this.\n> \n> +1 to that idea from me too. Seems pretty straightforward.\n\nOK, here's a patch that does it. I have not touched Meson yet.\n\nI'm pretty disappointed of not being able to remove\ngenerate-lwlocknames.pl (it now generates the .h, no longer the .c\nfile), but I can't find a way to do the equivalent #defines in CPP ...\nit'd require invoking the C preprocessor twice. Maybe an intermediate\n.h file would solve the problem, but I have no idea how would that work\nwith Meson. I guess I'll do it in Make and let somebody suggest a Meson\nway.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"El hombre nunca sabe de lo que es capaz hasta que lo intenta\" (C. Dickens)",
"msg_date": "Fri, 1 Mar 2024 15:00:49 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "Re: make BuiltinTrancheNames less ugly"
},
{
"msg_contents": "On Fri Mar 1, 2024 at 8:00 AM CST, Alvaro Herrera wrote:\n> On 2024-Feb-23, Heikki Linnakangas wrote:\n>\n> > On 12/02/2024 19:01, Tristan Partin wrote:\n> > > On Wed Jan 24, 2024 at 8:09 AM CST, Alvaro Herrera wrote:\n> > > > IMO it would be less ugly to have the origin file lwlocknames.txt be\n> > > > not a text file but a .h with a macro that can be defined by\n> > > > interested parties so that they can extract what they want from the\n> > > > file, like PG_CMDTAG or PG_KEYWORD. Using Perl for this seems dirty...\n> > > \n> > > I really like this idea, and would definitely be more inclined to see\n> > > a solution like this.\n> > \n> > +1 to that idea from me too. Seems pretty straightforward.\n>\n> OK, here's a patch that does it. I have not touched Meson yet.\n>\n> I'm pretty disappointed of not being able to remove\n> generate-lwlocknames.pl (it now generates the .h, no longer the .c\n> file), but I can't find a way to do the equivalent #defines in CPP ...\n> it'd require invoking the C preprocessor twice. Maybe an intermediate\n> .h file would solve the problem, but I have no idea how would that work\n> with Meson. I guess I'll do it in Make and let somebody suggest a Meson\n> way.\n\nI can help you with Meson if you get the Make implementation done.\n\n-- \nTristan Partin\nNeon (https://neon.tech)\n\n\n",
"msg_date": "Fri, 01 Mar 2024 10:42:19 -0600",
"msg_from": "\"Tristan Partin\" <tristan@neon.tech>",
"msg_from_op": false,
"msg_subject": "Re: make BuiltinTrancheNames less ugly"
},
{
"msg_contents": "On 2024-Mar-01, Tristan Partin wrote:\n\n> On Fri Mar 1, 2024 at 8:00 AM CST, Alvaro Herrera wrote:\n\n> > I'm pretty disappointed of not being able to remove\n> > generate-lwlocknames.pl (it now generates the .h, no longer the .c\n> > file), but I can't find a way to do the equivalent #defines in CPP ...\n> > it'd require invoking the C preprocessor twice. Maybe an intermediate\n> > .h file would solve the problem, but I have no idea how would that work\n> > with Meson. I guess I'll do it in Make and let somebody suggest a Meson\n> > way.\n> \n> I can help you with Meson if you get the Make implementation done.\n\nActually I realized that we need to keep the Perl script anyway because\nwe want to be able to cross-check the wait_event_names.txt files to\nensure we generate the correct documentation. Since it was simple\nenough, I added the Meson support already.\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — 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)",
"msg_date": "Mon, 11 Mar 2024 13:01:52 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "Re: make BuiltinTrancheNames less ugly"
}
] |
[
{
"msg_contents": "These checks are not effective for what they are trying to prevent. \nA recent commit[0] in libcurl when used on macOS has been tripping the \npthread_is_threaded_np() check in postmaster.c for \nshared_preload_libraries entries which use libcurl (like Neon). Under \nthe hood, libcurl calls SCDynamicStoreCopyProxies[1], which apparently \ncauses the check to fail.\n\nAttached is a patch to remove the check, and a minimal reproducer \n(curlexe.zip) for others to run on macOS.\n\nHere are some logs:\n\nPostgres working as expected:\n> $ LC_ALL=\"C\" /opt/homebrew/opt/postgresql@16/bin/postgres -D /opt/homebrew/var/postgresql@16\n> 2024-01-22 23:18:51.203 GMT [50388] LOG: starting PostgreSQL 16.1 (Homebrew) on aarch64-apple-darwin23.2.0, compiled by Apple clang version 15.0.0 (clang-1500.1.0.2.5), 64-bit\n> 2024-01-22 23:18:51.204 GMT [50388] LOG: listening on IPv6 address \"::1\", port 5432\n> 2024-01-22 23:18:51.204 GMT [50388] LOG: listening on IPv4 address \"127.0.0.1\", port 5432\n> 2024-01-22 23:18:51.205 GMT [50388] LOG: listening on Unix socket \"/tmp/.s.PGSQL.5432\"\n> 2024-01-22 23:18:51.207 GMT [50391] LOG: database system was shut down at 2023-12-21 23:12:10 GMT\n> 2024-01-22 23:18:51.211 GMT [50388] LOG: database system is ready to accept connections\n> ^C2024-01-22 23:18:53.797 GMT [50388] LOG: received fast shutdown request\n> 2024-01-22 23:18:53.798 GMT [50388] LOG: aborting any active transactions\n> 2024-01-22 23:18:53.800 GMT [50388] LOG: background worker \"logical replication launcher\" (PID 50394) exited with exit code 1\n> 2024-01-22 23:18:53.801 GMT [50389] LOG: shutting down\n> 2024-01-22 23:18:53.801 GMT [50389] LOG: checkpoint starting: shutdown immediate\n> 2024-01-22 23:18:53.805 GMT [50389] LOG: checkpoint complete: wrote 3 buffers (0.0%); 0 WAL file(s) added, 0 removed, 0 recycled; write=0.002 s, sync=0.001 s, total=0.005 s; sync files=2, longest=0.001 s, average=0.001 s; distance=0 kB, estimate=0 kB; lsn=0/4BE77E0, redo lsn=0/4BE77E0\n> 2024-01-22 23:18:53.809 GMT [50388] LOG: database system is shut down\n\nPostgres not working with attached extension preloaded:\n> $ echo shared_preload_libraries=curlexe >> /opt/homebrew/var/postgresql@16/postgresql.conf\n> $ LC_ALL=\"C\" /opt/homebrew/opt/postgresql@16/bin/postgres -D /opt/homebrew/var/postgresql@16\n> 2024-01-22 23:19:01.108 GMT [50395] LOG: starting PostgreSQL 16.1 (Homebrew) on aarch64-apple-darwin23.2.0, compiled by Apple clang version 15.0.0 (clang-1500.1.0.2.5), 64-bit\n> 2024-01-22 23:19:01.110 GMT [50395] LOG: listening on IPv6 address \"::1\", port 5432\n> 2024-01-22 23:19:01.110 GMT [50395] LOG: listening on IPv4 address \"127.0.0.1\", port 5432\n> 2024-01-22 23:19:01.111 GMT [50395] LOG: listening on Unix socket \"/tmp/.s.PGSQL.5432\"\n> 2024-01-22 23:19:01.113 GMT [50395] FATAL: postmaster became multithreaded during startup\n> 2024-01-22 23:19:01.113 GMT [50395] HINT: Set the LC_ALL environment variable to a valid locale.\n> 2024-01-22 23:19:01.114 GMT [50395] LOG: database system is shut down\n\nSame as previous, but without IPv6 support in libcurl:\n> $ DYLD_LIBRARY_PATH=/opt/homebrew/opt/curl-without-ipv6/lib LC_ALL=\"C\" /opt/homebrew/opt/postgresql@16/bin/postgres -D /opt/homebrew/var/postgresql@16\n> 2024-01-22 23:23:17.151 GMT [50546] LOG: starting PostgreSQL 16.1 (Homebrew) on aarch64-apple-darwin23.2.0, compiled by Apple clang version 15.0.0 (clang-1500.1.0.2.5), 64-bit\n> 2024-01-22 23:23:17.152 GMT [50546] LOG: listening on IPv6 address \"::1\", port 5432\n> 2024-01-22 23:23:17.152 GMT [50546] LOG: listening on IPv4 address \"127.0.0.1\", port 5432\n> 2024-01-22 23:23:17.152 GMT [50546] LOG: listening on Unix socket \"/tmp/.s.PGSQL.5432\"\n> 2024-01-22 23:23:17.155 GMT [50549] LOG: database system was shut down at 2024-01-22 23:23:10 GMT\n> 2024-01-22 23:23:17.158 GMT [50546] LOG: database system is ready to accept connections\n> ^C2024-01-22 23:23:26.997 GMT [50546] LOG: received fast shutdown request\n> 2024-01-22 23:23:26.998 GMT [50546] LOG: aborting any active transactions\n> 2024-01-22 23:23:27.000 GMT [50546] LOG: background worker \"logical replication launcher\" (PID 50552) exited with exit code 1\n> 2024-01-22 23:23:27.000 GMT [50547] LOG: shutting down\n> 2024-01-22 23:23:27.001 GMT [50547] LOG: checkpoint starting: shutdown immediate\n> 2024-01-22 23:23:27.002 GMT [50547] LOG: checkpoint complete: wrote 3 buffers (0.0%); 0 WAL file(s) added, 0 removed, 0 recycled; write=0.001 s, sync=0.001 s, total=0.003 s; sync files=2, longest=0.001 s, average=0.001 s; distance=0 kB, estimate=0 kB; lsn=0/4BE78D0, redo lsn=0/4BE78D0\n> 2024-01-22 23:23:27.005 GMT [50546] LOG: database system is shut down\n\n[0]: https://github.com/curl/curl/commit/8b7cbe9decc205b08ec8258eb184c89a33e3084b\n[1]: https://developer.apple.com/documentation/systemconfiguration/1517088-scdynamicstorecopyproxies\n\n-- \nTristan Partin\nNeon (https://neon.tech)",
"msg_date": "Tue, 23 Jan 2024 13:20:15 -0600",
"msg_from": "\"Tristan Partin\" <tristan@neon.tech>",
"msg_from_op": true,
"msg_subject": "Remove pthread_is_threaded_np() checks in postmaster"
},
{
"msg_contents": "Hi,\nOn 2024-01-23 13:20:15 -0600, Tristan Partin wrote:\n> These checks are not effective for what they are trying to prevent. A recent\n> commit[0] in libcurl when used on macOS has been tripping the\n> pthread_is_threaded_np() check in postmaster.c for shared_preload_libraries\n> entries which use libcurl (like Neon). Under the hood, libcurl calls\n> SCDynamicStoreCopyProxies[1], which apparently causes the check to fail.\n\nMaybe I'm missing something, but isn't that indicating the exact opposite,\nnamely that the check is precisely doing what it's intended?\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Tue, 23 Jan 2024 11:47:08 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: Remove pthread_is_threaded_np() checks in postmaster"
},
{
"msg_contents": "On Tue Jan 23, 2024 at 1:47 PM CST, Andres Freund wrote:\n> Hi,\n> On 2024-01-23 13:20:15 -0600, Tristan Partin wrote:\n> > These checks are not effective for what they are trying to prevent. A recent\n> > commit[0] in libcurl when used on macOS has been tripping the\n> > pthread_is_threaded_np() check in postmaster.c for shared_preload_libraries\n> > entries which use libcurl (like Neon). Under the hood, libcurl calls\n> > SCDynamicStoreCopyProxies[1], which apparently causes the check to fail.\n>\n> Maybe I'm missing something, but isn't that indicating the exact opposite,\n> namely that the check is precisely doing what it's intended?\n\nThe logic in the original commit seems sound:\n\n> On Darwin, detect and report a multithreaded postmaster.\n>\n> Darwin --enable-nls builds use a substitute setlocale() that may start a\n> thread. Buildfarm member orangutan experienced BackendList corruption\n> on account of different postmaster threads executing signal handlers\n> simultaneously. Furthermore, a multithreaded postmaster risks undefined\n> behavior from sigprocmask() and fork(). Emit LOG messages about the\n> problem and its workaround. Back-patch to 9.0 (all supported versions).\n\nSome reading from signal(7):\n\n> A process-directed signal may be delivered to any one of the threads \n> that does not currently have the signal blocked. If more than one of \n> the threads has the signal unblocked, then the kernel chooses an \n> arbitrary thread to which to deliver the signal.\n\nSo it sounds like the commit is trying to protect from the last \nsentence.\n\nAnd then forks only copy from their parent thread...\n\nPlease ignore this thread. I need to think of a better solution to this \nproblem.\n\n-- \nTristan Partin\nNeon (https://neon.tech)\n\n\n",
"msg_date": "Tue, 23 Jan 2024 14:10:48 -0600",
"msg_from": "\"Tristan Partin\" <tristan@neon.tech>",
"msg_from_op": true,
"msg_subject": "Re: Remove pthread_is_threaded_np() checks in postmaster"
},
{
"msg_contents": "On Tue Jan 23, 2024 at 2:10 PM CST, Tristan Partin wrote:\n> On Tue Jan 23, 2024 at 1:47 PM CST, Andres Freund wrote:\n> > Hi,\n> > On 2024-01-23 13:20:15 -0600, Tristan Partin wrote:\n> > > These checks are not effective for what they are trying to prevent. A recent\n> > > commit[0] in libcurl when used on macOS has been tripping the\n> > > pthread_is_threaded_np() check in postmaster.c for shared_preload_libraries\n> > > entries which use libcurl (like Neon). Under the hood, libcurl calls\n> > > SCDynamicStoreCopyProxies[1], which apparently causes the check to fail.\n> >\n> > Maybe I'm missing something, but isn't that indicating the exact opposite,\n> > namely that the check is precisely doing what it's intended?\n>\n> The logic in the original commit seems sound:\n>\n> > On Darwin, detect and report a multithreaded postmaster.\n> >\n> > Darwin --enable-nls builds use a substitute setlocale() that may start a\n> > thread. Buildfarm member orangutan experienced BackendList corruption\n> > on account of different postmaster threads executing signal handlers\n> > simultaneously. Furthermore, a multithreaded postmaster risks undefined\n> > behavior from sigprocmask() and fork(). Emit LOG messages about the\n> > problem and its workaround. Back-patch to 9.0 (all supported versions).\n>\n> Some reading from signal(7):\n>\n> > A process-directed signal may be delivered to any one of the threads \n> > that does not currently have the signal blocked. If more than one of \n> > the threads has the signal unblocked, then the kernel chooses an \n> > arbitrary thread to which to deliver the signal.\n>\n> So it sounds like the commit is trying to protect from the last \n> sentence.\n>\n> And then forks only copy from their parent thread...\n\nWhat is keeping us from using pthread_sigmask(3) instead of \nsigprocmask(2)? If an extension can guarantee that threads that get \nlaunched by it don't interact with anything Postgres-related, would that \nbe enough to protect from any fork(2) related issues? In the OP example, \nis there any harm in the thread that libcurl inadvertantly launches from \na Postgres perspective?\n\n-- \nTristan Partin\nNeon (https://neon.tech)\n\n\n",
"msg_date": "Tue, 23 Jan 2024 15:50:11 -0600",
"msg_from": "\"Tristan Partin\" <tristan@neon.tech>",
"msg_from_op": true,
"msg_subject": "Re: Remove pthread_is_threaded_np() checks in postmaster"
},
{
"msg_contents": "Hi,\n\nOn 2024-01-23 15:50:11 -0600, Tristan Partin wrote:\n> What is keeping us from using pthread_sigmask(3) instead of sigprocmask(2)?\n\nWe would need to make sure to compile with threading support everywhere. One\nissue is that on some platforms things get slower once you actually start\nusing pthreads.\n\n\n> If an extension can guarantee that threads that get launched by it don't\n> interact with anything Postgres-related, would that be enough to protect\n> from any fork(2) related issues?\n\nA fork() while threads are running is undefined behavior IIRC, and undefined\nbehavior isn't limited to a single thread. You'd definitely need to use\npthread_sigprocmask etc to address that aspect alone.\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Tue, 23 Jan 2024 14:23:47 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: Remove pthread_is_threaded_np() checks in postmaster"
},
{
"msg_contents": "On Tue Jan 23, 2024 at 4:23 PM CST, Andres Freund wrote:\n> Hi,\n>\n> On 2024-01-23 15:50:11 -0600, Tristan Partin wrote:\n> > What is keeping us from using pthread_sigmask(3) instead of sigprocmask(2)?\n>\n> We would need to make sure to compile with threading support everywhere. One\n> issue is that on some platforms things get slower once you actually start\n> using pthreads.\n\nWhat are examples of these reduced performance platforms?\n\n From reading the meson.build files, it seems like building with \nthreading enabled is the future, so should we just rip the band-aid off \nfor 17?\n\n> > If an extension can guarantee that threads that get launched by it don't\n> > interact with anything Postgres-related, would that be enough to protect\n> > from any fork(2) related issues?\n>\n> A fork() while threads are running is undefined behavior IIRC, and undefined\n> behavior isn't limited to a single thread. You'd definitely need to use\n> pthread_sigprocmask etc to address that aspect alone.\n\nIf you can find a resource that explains the UB, I would be very \ninterested to read that. I found a SO[0] answer that made it seem like \nthis actually wasn't the case.\n\n[0]: https://stackoverflow.com/a/42679479/7572728\n\n-- \nTristan Partin\nNeon (https://neon.tech)\n\n\n",
"msg_date": "Tue, 23 Jan 2024 17:26:19 -0600",
"msg_from": "\"Tristan Partin\" <tristan@neon.tech>",
"msg_from_op": true,
"msg_subject": "Re: Remove pthread_is_threaded_np() checks in postmaster"
},
{
"msg_contents": "Hi,\n\nOn 2024-01-23 17:26:19 -0600, Tristan Partin wrote:\n> On Tue Jan 23, 2024 at 4:23 PM CST, Andres Freund wrote:\n> > Hi,\n> > \n> > On 2024-01-23 15:50:11 -0600, Tristan Partin wrote:\n> > > What is keeping us from using pthread_sigmask(3) instead of sigprocmask(2)?\n> > \n> > We would need to make sure to compile with threading support everywhere. One\n> > issue is that on some platforms things get slower once you actually start\n> > using pthreads.\n> \n> What are examples of these reduced performance platforms?\n\nWith some libc, including IIRC glibc, FILE* style io starts to use locking,\nfor example. Which we likely shouldn't use as heavily as we do, but we\ncurrently do use it for things like COPY.\n\n\n> From reading the meson.build files, it seems like building with threading\n> enabled is the future, so should we just rip the band-aid off for 17?\n\nBuilding with -pthreads and using threads are separate things...\n\n\n> > > If an extension can guarantee that threads that get launched by it don't\n> > > interact with anything Postgres-related, would that be enough to protect\n> > > from any fork(2) related issues?\n> > \n> > A fork() while threads are running is undefined behavior IIRC, and undefined\n> > behavior isn't limited to a single thread. You'd definitely need to use\n> > pthread_sigprocmask etc to address that aspect alone.\n> \n> If you can find a resource that explains the UB, I would be very interested\n> to read that. I found a SO[0] answer that made it seem like this actually\n> wasn't the case.\n\nI think there are safe ways to do it, but I don't think we currently reliably\ndo so. It certainly wouldn't be well defined to have a thread created in\npostmaster, before backends are forked off (\"the child process may only\nexecute async-signal-safe operations until such time as one of the exec\nfunctions is called\").\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Tue, 23 Jan 2024 16:39:38 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: Remove pthread_is_threaded_np() checks in postmaster"
},
{
"msg_contents": "On Wed, Jan 24, 2024 at 1:39 PM Andres Freund <andres@anarazel.de> wrote:\n> On 2024-01-23 17:26:19 -0600, Tristan Partin wrote:\n> > On Tue Jan 23, 2024 at 4:23 PM CST, Andres Freund wrote:\n> > > A fork() while threads are running is undefined behavior IIRC, and undefined\n> > > behavior isn't limited to a single thread. You'd definitely need to use\n> > > pthread_sigprocmask etc to address that aspect alone.\n> >\n> > If you can find a resource that explains the UB, I would be very interested\n> > to read that. I found a SO[0] answer that made it seem like this actually\n> > wasn't the case.\n>\n> I think there are safe ways to do it, but I don't think we currently reliably\n> do so. It certainly wouldn't be well defined to have a thread created in\n> postmaster, before backends are forked off (\"the child process may only\n> execute async-signal-safe operations until such time as one of the exec\n> functions is called\").\n\nRight, the classic example is that if you fork() while some other\nthread is in malloc() or fwrite() or whatever libc or other unknown\ncode it might hold a mutex that will never be released in the child.\n\nAs for what exactly might be happening in this case, I tried calling\nSCDynamicStoreCopyProxies() and saw a new thread sitting in\n__workq_kernreturn, which smells like libdispatch AKA GCD, Apple's\nthread pool job dispatch thing. I tried to step my way through and\nfollow along on Apple's github and saw plenty of uses of libdispatch\nin CoreFoundation code, but not the culprit, and then I hit libxpc,\nwhich is closed source so I lost interest. Boo. Then I found this\narticle that says some interesting stuff about all that:\n\nhttps://www.evanjones.ca/fork-is-dangerous.html\n\nThat code has changed a bit since then but still tries to detect unsafe forks.\n\nhttps://github.com/apple-oss-distributions/libdispatch/blob/main/src/init.c\n\nThese days, I don't think the original corruption complaint that led\nto that am-I-multihreaded check being added to PostgreSQL could happen\nanyway, because the postmaster would now process its state machine\nserially in the main thread's work loop even if a random unexpected\nthread happened to run the handler. But obviously that doesn't help\nus with these other complications so that observation isn't very\ninteresting.\n\nAs for sigprocmask() vs pthread_sigmask(), the sources of\nunspecifiedness I am aware of are: (1) Unix vendors disagreeing on\nwhether the former affected only the calling thread or the whole\nprocess before threads were standardised, and we can see that they\nstill differ today (eg Darwin/XNU loops over all threads setting them,\nwhile many other systems do exactly the same as pthread_sigmask()),\nand (2) libcs sometimes use or defer some signals for their own\nprivate purposes, so sometimes pthread_sigmask() has a wrapper doing\nsome footwork in userspace rather than just invoking the system call,\nbut I dunno. In one of the threads about avoiding bad behaviour\naround system(), I think there might have been some ideas about\ngetting rid of the need to block signals at all, which I think must be\ntheoretically possible if the handlers are smart enough to avoid\nmisbehaving in child processes, and maybe we use moar latches.\n\n\n",
"msg_date": "Thu, 25 Jan 2024 18:44:01 +1300",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Remove pthread_is_threaded_np() checks in postmaster"
}
] |
[
{
"msg_contents": "I just discovered that doing \"make -C src/backend/storage/lmgr check\" no\nlonger works, because commit 92daeca45df6 (\"Add wait event for\npg_usleep() in perform_spin_delay()\") added a requirement for\nmy_wait_event_info to be present at link time:\n\n$ LC_ALL=C make -C src/backend/storage/lmgr/ s_lock_test\nmake: Entering directory '/home/alvherre/Code/pgsql-build/master/src/backend/storage/lmgr'\ngcc -I. -I../../../../src/include -I/pgsql/source/master/src/include -D_GNU_SOURCE -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wimplicit-fallthrough=3 -Wcast-function-type -Wshadow=compatible-local -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -Wno-format-truncation -Wno-stringop-truncation -g -O2 -DS_LOCK_TEST=1 /pgsql/source/master/src/backend/storage/lmgr/s_lock.c \\\n\t -L ../../../../src/common -lpgcommon \\\n\t-L ../../../../src/port -lpgport -lm -o s_lock_test\n/usr/bin/ld: /run/user/1000/alvherre-tmp/ccMaAvVj.o: warning: relocation against `my_wait_event_info' in read-only section `.text'\n/usr/bin/ld: /run/user/1000/alvherre-tmp/ccMaAvVj.o: in function `pgstat_report_wait_start':\n/pgsql/source/master/src/include/utils/wait_event.h:94: undefined reference to `my_wait_event_info'\n/usr/bin/ld: /run/user/1000/alvherre-tmp/ccMaAvVj.o: in function `pgstat_report_wait_end':\n/pgsql/source/master/src/include/utils/wait_event.h:107: undefined reference to `my_wait_event_info'\n/usr/bin/ld: warning: creating DT_TEXTREL in a PIE\ncollect2: error: ld returned 1 exit status\nmake: *** [Makefile:35: s_lock_test] Error 1\nmake: Leaving directory '/home/alvherre/Code/pgsql-build/master/src/backend/storage/lmgr'\n\n\nThis is after I added -lm, to fix these other problems:\n\n/home/alvherre/Code/pgsql-build/master/src/common/../../../../../../../pgsql/source/master/src/common/pg_prng.c:269: undefined reference to `log'\n/usr/bin/ld: /home/alvherre/Code/pgsql-build/master/src/common/../../../../../../../pgsql/source/master/src/common/pg_prng.c:269: undefined reference to `sin'\n/usr/bin/ld: /home/alvherre/Code/pgsql-build/master/src/common/../../../../../../../pgsql/source/master/src/common/pg_prng.c:269: undefined reference to `sqrt'\n\n\nOn my machine, it's enough to patch s_lock_test.c to have a local definition\nfor the missing symbol. Since the file already has a test mode, it\nturns out to be quite simple -- attached.\n\n\nI do wonder if we want to keep this around, given that it's been more\nthan one year broken and nobody seems to have noticed, and the Meson\nbuild does not support the test as a target.\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/\n Are you not unsure you want to delete Firefox?\n [Not unsure] [Not not unsure] [Cancel]\n http://smylers.hates-software.com/2008/01/03/566e45b2.html",
"msg_date": "Wed, 24 Jan 2024 12:14:17 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "s_lock_test no longer works"
},
{
"msg_contents": "Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> I do wonder if we want to keep this around, given that it's been more\n> than one year broken and nobody seems to have noticed, and the Meson\n> build does not support the test as a target.\n\nThe last time it was broken, it took us multiple years to notice, too.\nI'm not sure that that's a reason to remove the test scaffolding,\nthough. You'd probably only really use it to smoke-test some new\nspinlock assembly code, and how often does anyone do that anymore?\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Wed, 24 Jan 2024 11:44:54 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: s_lock_test no longer works"
},
{
"msg_contents": "Hi,\n\nOn 2024-01-24 12:14:17 +0100, Alvaro Herrera wrote:\n> I do wonder if we want to keep this around, given that it's been more\n> than one year broken and nobody seems to have noticed, and the Meson\n> build does not support the test as a target.\n\nPerhaps we should just make the test built and run by default instead? OTOH,\nregress.c:test_spinlock() actually covers about as much as the standalone\ntest...\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Wed, 24 Jan 2024 11:46:49 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: s_lock_test no longer works"
},
{
"msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2024-01-24 12:14:17 +0100, Alvaro Herrera wrote:\n>> I do wonder if we want to keep this around, given that it's been more\n>> than one year broken and nobody seems to have noticed, and the Meson\n>> build does not support the test as a target.\n\n> Perhaps we should just make the test built and run by default instead? OTOH,\n> regress.c:test_spinlock() actually covers about as much as the standalone\n> test...\n\nIf your spinlocks aren't working, it's unlikely you'll get as far as\nbeing able to run test_spinlock(). I think the standalone test does\nhave some value; it's just that it's not needed very often these days.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Wed, 24 Jan 2024 15:05:12 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: s_lock_test no longer works"
},
{
"msg_contents": "Hi,\n\nOn 2024-01-24 15:05:12 -0500, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > On 2024-01-24 12:14:17 +0100, Alvaro Herrera wrote:\n> >> I do wonder if we want to keep this around, given that it's been more\n> >> than one year broken and nobody seems to have noticed, and the Meson\n> >> build does not support the test as a target.\n> \n> > Perhaps we should just make the test built and run by default instead? OTOH,\n> > regress.c:test_spinlock() actually covers about as much as the standalone\n> > test...\n> \n> If your spinlocks aren't working, it's unlikely you'll get as far as\n> being able to run test_spinlock(). I think the standalone test does\n> have some value; it's just that it's not needed very often these days.\n\nAs long as the uncontended case works, you can get surprisingly far... But\nstill, fair enough. If so, I think we should just rig things so the standalone\ntest gets built and run by default. It's not like that'd be a measurably\nexpensive thing to do.\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Wed, 24 Jan 2024 12:43:01 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: s_lock_test no longer works"
}
] |
[
{
"msg_contents": "Hi,\n\nBecause of commit 1bdd54e662, the code of HandleWalWriterInterrupts()\nbecame the same as HandleMainLoopInterrupts(). So I'd like to propose to\nremove HandleWalWriterInterrupts() and make walwriter use\nHandleMainLoopInterrupts() instead for improved code simplicity. Thought?\n\nPatch attached.\n\nRegards,\n\n-- \nFujii Masao",
"msg_date": "Wed, 24 Jan 2024 21:20:17 +0900",
"msg_from": "Fujii Masao <masao.fujii@gmail.com>",
"msg_from_op": true,
"msg_subject": "Remove redundant HandleWalWriterInterrupts()"
},
{
"msg_contents": "On Wed, Jan 24, 2024 at 5:50 PM Fujii Masao <masao.fujii@gmail.com> wrote:\n>\n> Hi,\n>\n> Because of commit 1bdd54e662, the code of HandleWalWriterInterrupts()\n> became the same as HandleMainLoopInterrupts(). So I'd like to propose to\n> remove HandleWalWriterInterrupts() and make walwriter use\n> HandleMainLoopInterrupts() instead for improved code simplicity. Thought?\n>\n> Patch attached.\n\nNice catch. Indeed they both are the same after commit 1bdd54e662. The\npatch LGTM.\n\n-- \nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Wed, 24 Jan 2024 19:30:17 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Remove redundant HandleWalWriterInterrupts()"
},
{
"msg_contents": "On Wed, Jan 24, 2024 at 07:30:17PM +0530, Bharath Rupireddy wrote:\n> On Wed, Jan 24, 2024 at 5:50 PM Fujii Masao <masao.fujii@gmail.com> wrote:\n>> Because of commit 1bdd54e662, the code of HandleWalWriterInterrupts()\n>> became the same as HandleMainLoopInterrupts(). So I'd like to propose to\n>> remove HandleWalWriterInterrupts() and make walwriter use\n>> HandleMainLoopInterrupts() instead for improved code simplicity. Thought?\n>>\n>> Patch attached.\n> \n> Nice catch. Indeed they both are the same after commit 1bdd54e662. The\n> patch LGTM.\n\nLGTM, too.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Wed, 24 Jan 2024 13:40:19 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Remove redundant HandleWalWriterInterrupts()"
},
{
"msg_contents": "On Thu, Jan 25, 2024 at 4:40 AM Nathan Bossart <nathandbossart@gmail.com> wrote:\n>\n> On Wed, Jan 24, 2024 at 07:30:17PM +0530, Bharath Rupireddy wrote:\n> > On Wed, Jan 24, 2024 at 5:50 PM Fujii Masao <masao.fujii@gmail.com> wrote:\n> >> Because of commit 1bdd54e662, the code of HandleWalWriterInterrupts()\n> >> became the same as HandleMainLoopInterrupts(). So I'd like to propose to\n> >> remove HandleWalWriterInterrupts() and make walwriter use\n> >> HandleMainLoopInterrupts() instead for improved code simplicity. Thought?\n> >>\n> >> Patch attached.\n> >\n> > Nice catch. Indeed they both are the same after commit 1bdd54e662. The\n> > patch LGTM.\n>\n> LGTM, too.\n\nThank you both for reviewing! I've pushed the patch.\n\nRegards,\n\n-- \nFujii Masao\n\n\n",
"msg_date": "Thu, 25 Jan 2024 12:57:06 +0900",
"msg_from": "Fujii Masao <masao.fujii@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Remove redundant HandleWalWriterInterrupts()"
}
] |
[
{
"msg_contents": "Greetings -hackers and -mentors,\n\nGoogle Summer of Code is back for 2024! Please review this\nannouncement blog post:\nhttps://opensource.googleblog.com/2023/11/google-summer-of-code-2024-celebrating-20th-year.html\n\nAnd please make yourself familiar with the GSoC 2024 timeline:\nhttps://developers.google.com/open-source/gsoc/timeline\n\nNow is the time to work on getting together a set of projects we'd\nlike to have GSoC students work on over the summer. Like last year, we\nmust have a good set of projects for students to choose from before\nthe deadline for mentoring organizations.\n\nThe deadline for Mentoring organizations to apply is February 6.\nThe list of accepted organizations will be published on February 21.\n\nUnsurprisingly, we'll need to have an Ideas page again, so I've gone\nahead and created one (copying last year's):\nhttps://wiki.postgresql.org/wiki/GSoC_2024\n\nGoogle discusses what makes a good \"Ideas\" list here:\nhttps://google.github.io/gsocguides/mentor/defining-a-project-ideas-list.html\n\nAll the entries are marked with '2023' to indicate they were pulled\nfrom last year. If the project from last year is still relevant,\nplease update it to '2024'. Make sure to revise all the information\n(in particular, list yourself as a mentor and remove the other\nmentors, as appropriate). Please also update the project's scope to be\nreasonable for the time students are asked.\n\nHaving at least two mentors per project is an excellent idea to\ndecrease the load. Please consider listing yourself as a co-mentor for\nprojects with only one mentor listed. The program's goals are not\nlimited solely to code writing. One of the goals is to inspire new\ndevelopers to begin participating in open-source communities and to\nhelp open-source projects identify and bring in new developers.\n\nNew entries are welcome and encouraged; note them as '2024' when you add them.\n\nProjects from last year that were worked on but had significant\nfollow-on work to be completed are also welcome - update the\ndescription appropriately and mark it as being for '2024'.\n\nWhen we get closer to submitting our application, I'll clean out the\n'2023' entries that have yet to receive any updates. Also, if any\nprojects are no longer appropriate (maybe they were completed, for\nexample, and no longer need work), please feel free to remove them. We\nmay have missed some updates where a GSoC project was achieved\nindependently of GSoC.\n\nAs a reminder, each idea on the page should be in the format that the\nother entries are in and should include:\n 1 Project Description\n 2 Skills needed\n 3 Difficulty Level\n 4 Project Size\n 5 Potential Mentors\n 6 Expected Outcomes\n 7 References\n\nAs with last year, please consider PostgreSQL to be an \"Umbrella\"\nproject, and anything that would be regarded as a \"PostgreSQL Family\"\nper the News/Announce policy [1] is likely to be acceptable as a\nPostgreSQL GSoC project.\n\nIn other words, if you're a contributor or developer on WAL-G, barman,\npgBackRest, pgwatch, pgagroal, pgexporter, pgmoneta, pgpool,\npgbouncer, the PostgreSQL website (pgweb), the PgEU/PgUS website code\n(pgeu-system), pgAdmin4, DBeaver, HeidiSQL, pldebugger, pspg, the PG\nRPMs (pgrpms), the JDBC driver, the ODBC driver, or any of the many\nother PG Family projects, please feel free to add a project for\nconsideration!\n\nLet's have another great year of GSoC with PostgreSQL!\nPGForce be with you!\n\nBest regards,\nPavlo Golub,\non behalf of PostgreSQL GSoC Admins\n\n[1]: https://www.postgresql.org/about/policies/news-and-events/\n\n\n",
"msg_date": "Wed, 24 Jan 2024 13:24:47 +0100",
"msg_from": "Pavlo Golub <pavlo.golub@gmail.com>",
"msg_from_op": true,
"msg_subject": "GSoC 2024"
}
] |
[
{
"msg_contents": "Hi,\n\nIt would be viable and appropriate to implement a unified function that provides important information about the current connection?\n\nJust an example: \"Current Connection Informations\".\n\nI implemented it in PL/pgSQL to demonstrate the idea, see on GitHub:\nhttps://github.com/maiquelgrassi/DBA-toolkit/blob/main/cluster/dba_whoami_function.sql\n\nRegards,\nMaiquel.\n\n\n\n\n\n\n\n\n\nHi,\n \nIt would be viable and appropriate to implement a unified function that provides important information about the current connection?\n\nJust an example: \"Current Connection Informations\".\n \nI implemented it in PL/pgSQL to demonstrate the idea, see on GitHub:\nhttps://github.com/maiquelgrassi/DBA-toolkit/blob/main/cluster/dba_whoami_function.sql\n\nRegards,\nMaiquel.",
"msg_date": "Wed, 24 Jan 2024 22:05:29 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "Current Connection Information"
},
{
"msg_contents": "Hi,\n\n> It would be viable and appropriate to implement a unified function that provides important information about the current connection?\n>\n> Just an example: \"Current Connection Informations\".\n>\n> I implemented it in PL/pgSQL to demonstrate the idea, see on GitHub:\n> https://github.com/maiquelgrassi/DBA-toolkit/blob/main/cluster/dba_whoami_function.sql\n\nI believe one would typically do something like this:\n\n```\nselect * from pg_stat_activity where pid = pg_backend_pid();\n```\n\nOn top of that psql can be configured to display useful information, e.g.:\n\n```\n$ cat ~/.psqlrc\n\\timing on\nselect (case when pg_is_in_recovery() then 'replica' else 'master'\nend) as master_or_replica\n\\gset\n\\set PROMPT1 '%p (%:master_or_replica:) =# '\n```\n\nPersonally I somewhat doubt that there is a one-size-fits-all\nequivalent of `whoami` for Postgres. E.g. one person would like to see\na list of extensions available in the current database while for\nanother this is redundant information.\n\nEven if we do this I don't think this should be a PL/pgSQL function\nbut rather a \\whoami command for psql. This solution however will\nleave users of DataGrip and similar products unhappy.\n\n-- \nBest regards,\nAleksander Alekseev\n\n\n",
"msg_date": "Thu, 25 Jan 2024 14:51:07 +0300",
"msg_from": "Aleksander Alekseev <aleksander@timescale.com>",
"msg_from_op": false,
"msg_subject": "Re: Current Connection Information"
},
{
"msg_contents": "Hi Maiquel,\n\nI assume you wanted to reply to the mailing list and add me to cc:\n(aka \"Reply to All\") but sent the e-mail off-list by mistake, so\nquoting it here:\n\n> Hi Aleksander,\n>\n> Why do you think DataGrip users would be unhappy?\n>\n> I liked your suggestion of creating something like \\whoami for psql. Wouldn't it be worth trying that?\n>\n> The output doesn't necessarily need to include all the fields I added in my PL/pgSQL function; it can be reduced or have other fields added.\n>\n>\n> What do you think?\n\nAnswering the questions:\n\n> Why do you think DataGrip users would be unhappy?\n\nI must admit I'm not well familiar with such products. My humble\nunderstanding is that in most cases they use JDBC, libpq or other\ndrivers and thus can't benefit from something implemented in psql.\n\n> I liked your suggestion of creating something like \\whoami for psql. Wouldn't it be worth trying that?\n\nIMO it's worth trying submitting the patch, if your time permits it of course.\n\n-- \nBest regards,\nAleksander Alekseev\n\n\n",
"msg_date": "Fri, 26 Jan 2024 11:27:26 +0300",
"msg_from": "Aleksander Alekseev <aleksander@timescale.com>",
"msg_from_op": false,
"msg_subject": "Re: Current Connection Information"
},
{
"msg_contents": "Hi Aleksander,\n\n>>I assume you wanted to reply to the mailing list and add me to cc:\n>>(aka \"Reply to All\") but sent the e-mail off-list by mistake, so\n>>quoting it here:\n\nYes, tks for that.\n\n>>IMO it's worth trying submitting the patch, if your time permits it of course.\n\nI've been spending a little time thinking about this.\n\nRegards,\nMaiquel.\n\n\n\n\n\n\n\nHi Aleksander,\n\n>>I assume you wanted to reply to the mailing list and add me to cc:\n>>(aka \"Reply to All\") but sent the e-mail off-list by mistake, so\n>>quoting it here:\n\nYes, tks for that.\n\n\n>>IMO it's worth trying submitting the patch, if your time permits\n it of course.\n\n\nI've been spending a little time thinking about this.\n\nRegards,\nMaiquel.",
"msg_date": "Fri, 26 Jan 2024 14:41:46 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Current Connection Information"
}
] |
[
{
"msg_contents": "Hi,\n\nAttached is a patch set which combines the freeze and prune records\nfor vacuum -- eliminating the overhead of a separate freeze WAL record\nfor every block frozen by vacuum. The contents of the freeze record\nare added to the PRUNE record.\n\nIn cases where vacuum does freeze and prune, combining the WAL records\ncan reduce WAL bytes substantially and, as a consequence, reduce WAL\nsync and write time.\n\nFor example:\n\npsql -c \"CREATE TABLE foo(id INT, a INT, b INT, c INT, d INT, e INT, f\nINT, g INT, h TEXT) WITH (autovacuum_enabled=false);\"\n\nfor x in $(seq 1 16);\ndo\n psql -c \"INSERT INTO foo SELECT i, i, i, i, i, i, i, i, repeat('b',\n30) FROM generate_series(1,2000000)i;\"\ndone\n\npsql -c \"UPDATE foo SET a = 2 WHERE id % 7 = 0;\"\npsql -c \"VACUUM (FREEZE) foo;\"\n\nGenerates 30% fewer WAL records and 12% fewer WAL bytes -- which,\ndepending on what else is happening on the system, can lead to vacuum\nspending substantially less time on WAL writing and syncing (often 15%\nless time on WAL writes and 10% less time on syncing WAL in my\ntesting).\n\nThough heap_page_prune() is also used by on-access pruning, on-access\npruning does not pass in the parameter used for freezing, so it should\nincur limited additional overhead. The primary additional overhead\nwould be checking tuples' xmins against the GlobalVisState to\ndetermine if the page would be all_visible and identify the visibility\ncutoff xid. This is required to determine whether or not to\nopportunistically freeze. We could condition this on the caller being\nvacuum if needed.\n\nThough, in the future, we may want to consider opportunistic/eager\nfreezing on access. This could allow us to, for example, freeze\nbulk-loaded read-only data before it goes cold and avoid expensive\nwraparound vacuuming.\n\nThere are other steps that we can take to decrease vacuum WAL volume\neven further. Many of those are natural follow-ons to combining the\nprune and freeze record. For example, I intend to propose combining\nthe visibility map update record into the Prune/Freeze and Vacuum\nrecords -- eliminating an extra visibility map update record. This\nwould mean a single WAL record emitted per block for vacuum's first\npass.\n\nOn master, for my example above, of the roughly 1 million WAL records\nemitted by vacuum, about 1/3 of them are prune records, 1/3 are freeze\nrecords, and 1/3 are visibility map update records. So we will achieve\nanother substantial reduction in the number of WAL records and bytes\nof WAL record overhead by eliminating a separate record for updating\nthe VM.\n\nThe attached patch set is broken up into many separate commits for\nease of review. Each patch does a single thing which can be explained\nplainly in the commit message. Every commit passes tests and works on\nits own.\n\n0001 - 0003 cover checking tuples' xmins against the GlobalVisState in\nheap_page_prune().\n\n0004 - 0007 executes freezing in heap_page_prune() (for vacuum only).\n\n0008 translates the eager/opportunistic freeze heuristic into one that\nwill work without relying on having a separate prune record. Elsewhere\nin [1] we are discussing how to improve this heuristic.\n\n0009 - 0012 merges the freeze record into the prune record.\n\n0013 - 0015 removes the loop through the page in lazy_scan_prune() by\ndoing the accounting it did in heap_page_prune(). A nice bonus of this\npatch set is that we can eliminate one of vacuum's loops through the\npage.\n\n- Melanie\n\n[1] https://www.postgresql.org/message-id/CAAKRu_ZTDm1d9M%2BENf6oXhW9nRT3J76vOL1ianiCW4%2B4M6hMoA%40mail.gmail.com",
"msg_date": "Wed, 24 Jan 2024 17:49:35 -0500",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 25/01/2024 00:49, Melanie Plageman wrote:\n> Generates 30% fewer WAL records and 12% fewer WAL bytes -- which,\n> depending on what else is happening on the system, can lead to vacuum\n> spending substantially less time on WAL writing and syncing (often 15%\n> less time on WAL writes and 10% less time on syncing WAL in my\n> testing).\n\nNice!\n\n> The attached patch set is broken up into many separate commits for\n> ease of review. Each patch does a single thing which can be explained\n> plainly in the commit message. Every commit passes tests and works on\n> its own.\n\nAbout this very first change:\n\n> --- a/src/backend/access/heap/vacuumlazy.c\n> +++ b/src/backend/access/heap/vacuumlazy.c\n> @@ -1526,8 +1526,7 @@ lazy_scan_prune(LVRelState *vacrel,\n> \t\t\t\t\t * that everyone sees it as committed?\n> \t\t\t\t\t */\n> \t\t\t\t\txmin = HeapTupleHeaderGetXmin(htup);\n> -\t\t\t\t\tif (!TransactionIdPrecedes(xmin,\n> -\t\t\t\t\t\t\t\t\t\t\t vacrel->cutoffs.OldestXmin))\n> +\t\t\t\t\tif (!GlobalVisTestIsRemovableXid(vacrel->vistest, xmin))\n> \t\t\t\t\t{\n> \t\t\t\t\t\tall_visible = false;\n> \t\t\t\t\t\tbreak;\n\nDoes GlobalVisTestIsRemovableXid() handle FrozenTransactionId correctly?\n\nI read through all the patches in order, and aside from the above they \nall look correct to me. Some comments on the set as whole:\n\nI don't think we need XLOG_HEAP2_FREEZE_PAGE as a separate record type \nanymore. By removing that, you also get rid of the freeze-only codepath \nnear the end of heap_page_prune(), and the \nheap_freeze_execute_prepared() function.\n\nThe XLOG_HEAP2_FREEZE_PAGE record is a little smaller than \nXLOG_HEAP2_PRUNE. But we could optimize the XLOG_HEAP2_PRUNE format for \nthe case that there's no pruning, just freezing. The record format \n(xl_heap_prune) looks pretty complex as it is, I think it could be made \nboth more compact and more clear with some refactoring.\n\nFreezeMultiXactId still takes a separate 'cutoffs' arg, but it could use \npagefrz->cutoffs now.\n\nHeapPageFreeze has two \"trackers\", for the \"freeze\" and \"no freeze\" \ncases. heap_page_prune() needs to track both, until it decides whether \nto freeze or not. But it doesn't make much sense that the caller \n(lazy_scan_prune()) has to initialize both, and has to choose which of \nthe values to use after the call depending on whether heap_page_prune() \nfroze or not. The two trackers should be just heap_page_prune()'s \ninternal business.\n\nHeapPageFreeze is a bit confusing in general, as it's both an input and \nan output to heap_page_prune(). Not sure what exactly to do there, but I \nfeel that we should make heap_page_prune()'s interface more clear. \nPerhaps move the output fields to PruneResult.\n\nLet's rename heap_page_prune() to heap_page_prune_and_freeze(), as \nfreezing is now an integral part of the function. And mention it in the \nfunction comment, too.\n\nIn heap_prune_chain:\n\n> * Tuple visibility information is provided in presult->htsv.\n\nNot this patch's fault directly, but it's not immediate clear what \"is \nprovided\" means here. Does the caller provide it, or does the function \nset it, ie. is it an input or output argument? Looking at the code, it's \nan input, but now it looks a bit weird that an input argument is called \n'presult'.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n",
"msg_date": "Wed, 6 Mar 2024 14:59:31 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "Thanks so much for the review!\n\nOn Wed, Mar 6, 2024 at 7:59 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> On 25/01/2024 00:49, Melanie Plageman wrote:\n>\n> > The attached patch set is broken up into many separate commits for\n> > ease of review. Each patch does a single thing which can be explained\n> > plainly in the commit message. Every commit passes tests and works on\n> > its own.\n>\n> About this very first change:\n>\n> > --- a/src/backend/access/heap/vacuumlazy.c\n> > +++ b/src/backend/access/heap/vacuumlazy.c\n> > @@ -1526,8 +1526,7 @@ lazy_scan_prune(LVRelState *vacrel,\n> > * that everyone sees it as committed?\n> > */\n> > xmin = HeapTupleHeaderGetXmin(htup);\n> > - if (!TransactionIdPrecedes(xmin,\n> > - vacrel->cutoffs.OldestXmin))\n> > + if (!GlobalVisTestIsRemovableXid(vacrel->vistest, xmin))\n> > {\n> > all_visible = false;\n> > break;\n>\n> Does GlobalVisTestIsRemovableXid() handle FrozenTransactionId correctly?\n\nOkay, so I thought a lot about this, and I don't understand how\nGlobalVisTestIsRemovableXid() would not handle FrozenTransactionId\ncorrectly.\n\nvacrel->cutoffs.OldestXmin is computed initially from\nGetOldestNonRemovableTransactionId() which uses ComputeXidHorizons().\nGlobalVisState is updated by ComputeXidHorizons() (when it is\nupdated).\n\nI do see that the comment above GlobalVisTestIsRemovableXid() says\n\n * It is crucial that this only gets called for xids from a source that\n * protects against xid wraparounds (e.g. from a table and thus protected by\n * relfrozenxid).\n\nand then in\n\n * Convert 32 bit argument to FullTransactionId. We can do so safely\n * because we know the xid has to, at the very least, be between\n * [oldestXid, nextXid), i.e. within 2 billion of xid.\n\nI'm not sure what oldestXid is here.\nIt's true that I don't see GlobalVisTestIsRemovableXid() being called\nanywhere else with an xmin as an input. I think that hints that it is\nnot safe with FrozenTransactionId. But I don't see what could go\nwrong.\n\nMaybe it has something to do with converting it to a FullTransactionId?\n\n FullTransactionIdFromU64(U64FromFullTransactionId(rel) + (int32)\n(xid - rel_xid));\n\nSorry, I couldn't quite figure it out :(\n\n> I read through all the patches in order, and aside from the above they\n> all look correct to me. Some comments on the set as whole:\n>\n> I don't think we need XLOG_HEAP2_FREEZE_PAGE as a separate record type\n> anymore. By removing that, you also get rid of the freeze-only codepath\n> near the end of heap_page_prune(), and the\n> heap_freeze_execute_prepared() function.\n\nThat makes sense to me.\n\n> The XLOG_HEAP2_FREEZE_PAGE record is a little smaller than\n> XLOG_HEAP2_PRUNE. But we could optimize the XLOG_HEAP2_PRUNE format for\n> the case that there's no pruning, just freezing. The record format\n> (xl_heap_prune) looks pretty complex as it is, I think it could be made\n> both more compact and more clear with some refactoring.\n\nI'm happy to change up xl_heap_prune format. In its current form,\naccording to pahole, it has no holes and just 3 bytes of padding at\nthe end.\n\nOne way we could make it smaller is by moving the isCatalogRel member\nto directly after snapshotConflictHorizon and then adding a flags\nfield and defining flags to indicate whether or not other members\nexist at all. We could set bits for HAS_FREEZE_PLANS, HAS_REDIRECTED,\nHAS_UNUSED, HAS_DEAD. Then I would remove the non-optional uint16\nnredirected, nunused, nplans, ndead and just put the number of\nredirected/unused/etc at the beginning of the arrays containing the\noffsets. Then I could write various macros for accessing them. That\nwould make it smaller, but it definitely wouldn't make it less complex\n(IMO).\n\n> FreezeMultiXactId still takes a separate 'cutoffs' arg, but it could use\n> pagefrz->cutoffs now.\n\nYep, I forgot to add a commit to do this. Thanks!\n\n> HeapPageFreeze has two \"trackers\", for the \"freeze\" and \"no freeze\"\n> cases. heap_page_prune() needs to track both, until it decides whether\n> to freeze or not. But it doesn't make much sense that the caller\n> (lazy_scan_prune()) has to initialize both, and has to choose which of\n> the values to use after the call depending on whether heap_page_prune()\n> froze or not. The two trackers should be just heap_page_prune()'s\n> internal business.\n>\n> HeapPageFreeze is a bit confusing in general, as it's both an input and\n> an output to heap_page_prune(). Not sure what exactly to do there, but I\n> feel that we should make heap_page_prune()'s interface more clear.\n> Perhaps move the output fields to PruneResult.\n\nGreat point. Perhaps I just add NewRelfrozenXid and NewRelminMxid to\nPruneResult (and call it PruneFreezeResult) and then make\nVacuumCutoffs an optional argument to heap_page_prune() (used by\nvacuum and not on-access pruning). Then I eliminate HeapPageFreeze as\na parameter altogether.\n\n> Let's rename heap_page_prune() to heap_page_prune_and_freeze(), as\n> freezing is now an integral part of the function. And mention it in the\n> function comment, too.\n\nAgreed. Will do in the next version. I want to get some consensus on\nwhat to do with xl_heap_prune before going on my rebase journey with\nthese 15 patches.\n\n> In heap_prune_chain:\n>\n> > * Tuple visibility information is provided in presult->htsv.\n>\n> Not this patch's fault directly, but it's not immediate clear what \"is\n> provided\" means here. Does the caller provide it, or does the function\n> set it, ie. is it an input or output argument? Looking at the code, it's\n> an input, but now it looks a bit weird that an input argument is called\n> 'presult'.\n\nSo, htsv is a member of PruneResult on master because\nheap_page_prune() populates PruneResult->htsv for use in\nlazy_scan_prune(). heap_prune_chain() doesn't have access to\nPruneResult on master. Once I move PruneResult to being populated both\nby heap_page_prune() and heap_prune_chain(), it gets more confusing.\nhtsv is always populated in heap_page_prune(), but it is not until\nlater patches in the set that I stop accessing it in\nlazy_scan_prune(). Once I do so, I move htsv from PruneResult into\nPruneState -- which fixes the heap_prune_chain() confusion.\n\nSo, only intermediate commits in the set have PruneResult->htsv used\nin heap_prune_chain(). The end state is that heap_prune_chain()\naccesses PruneState->htsv. However, I can document how it is used more\nclearly in the function comment in the intermediate commits. Or, I can\nsimply leave htsv as a separate input argument to heap_prune_chain()\nin the intermediate commits.\n\n- Melanie\n\n\n",
"msg_date": "Sat, 9 Mar 2024 15:41:49 -0500",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 09/03/2024 22:41, Melanie Plageman wrote:\n> On Wed, Mar 6, 2024 at 7:59 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>> Does GlobalVisTestIsRemovableXid() handle FrozenTransactionId correctly?\n> \n> Okay, so I thought a lot about this, and I don't understand how\n> GlobalVisTestIsRemovableXid() would not handle FrozenTransactionId\n> correctly.\n> \n> vacrel->cutoffs.OldestXmin is computed initially from\n> GetOldestNonRemovableTransactionId() which uses ComputeXidHorizons().\n> GlobalVisState is updated by ComputeXidHorizons() (when it is\n> updated).\n> \n> I do see that the comment above GlobalVisTestIsRemovableXid() says\n> \n> * It is crucial that this only gets called for xids from a source that\n> * protects against xid wraparounds (e.g. from a table and thus protected by\n> * relfrozenxid).\n> \n> and then in\n> \n> * Convert 32 bit argument to FullTransactionId. We can do so safely\n> * because we know the xid has to, at the very least, be between\n> * [oldestXid, nextXid), i.e. within 2 billion of xid.\n> \n> I'm not sure what oldestXid is here.\n> It's true that I don't see GlobalVisTestIsRemovableXid() being called\n> anywhere else with an xmin as an input. I think that hints that it is\n> not safe with FrozenTransactionId. But I don't see what could go\n> wrong.\n> \n> Maybe it has something to do with converting it to a FullTransactionId?\n> \n> FullTransactionIdFromU64(U64FromFullTransactionId(rel) + (int32)\n> (xid - rel_xid));\n> \n> Sorry, I couldn't quite figure it out :(\n\nI just tested it. No, GlobalVisTestIsRemovableXid does not work for \nFrozenTransactionId. I just tested it with state->definitely_needed == \n{0, 4000000000} and xid == FrozenTransactionid, and it incorrectly \nreturned 'false'. It treats FrozenTransactionId as if was a regular xid '2'.\n\n>> The XLOG_HEAP2_FREEZE_PAGE record is a little smaller than\n>> XLOG_HEAP2_PRUNE. But we could optimize the XLOG_HEAP2_PRUNE format for\n>> the case that there's no pruning, just freezing. The record format\n>> (xl_heap_prune) looks pretty complex as it is, I think it could be made\n>> both more compact and more clear with some refactoring.\n> \n> I'm happy to change up xl_heap_prune format. In its current form,\n> according to pahole, it has no holes and just 3 bytes of padding at\n> the end.\n> \n> One way we could make it smaller is by moving the isCatalogRel member\n> to directly after snapshotConflictHorizon and then adding a flags\n> field and defining flags to indicate whether or not other members\n> exist at all. We could set bits for HAS_FREEZE_PLANS, HAS_REDIRECTED,\n> HAS_UNUSED, HAS_DEAD. Then I would remove the non-optional uint16\n> nredirected, nunused, nplans, ndead and just put the number of\n> redirected/unused/etc at the beginning of the arrays containing the\n> offsets.\n\nSounds good.\n\n> Then I could write various macros for accessing them. That\n> would make it smaller, but it definitely wouldn't make it less complex\n> (IMO).\n\nI don't know, it might turn out not that complex. If you define the \nformats of each of those \"sub-record types\" as explicit structs, per \nattached sketch, you won't need so many macros. Some care is still \nneeded with alignment though.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)",
"msg_date": "Tue, 12 Mar 2024 00:38:45 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Mon, Mar 11, 2024 at 6:38 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> On 09/03/2024 22:41, Melanie Plageman wrote:\n> > On Wed, Mar 6, 2024 at 7:59 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> >> Does GlobalVisTestIsRemovableXid() handle FrozenTransactionId correctly?\n> >\n> > Okay, so I thought a lot about this, and I don't understand how\n> > GlobalVisTestIsRemovableXid() would not handle FrozenTransactionId\n> > correctly.\n> >\n> > vacrel->cutoffs.OldestXmin is computed initially from\n> > GetOldestNonRemovableTransactionId() which uses ComputeXidHorizons().\n> > GlobalVisState is updated by ComputeXidHorizons() (when it is\n> > updated).\n> >\n> > I do see that the comment above GlobalVisTestIsRemovableXid() says\n> >\n> > * It is crucial that this only gets called for xids from a source that\n> > * protects against xid wraparounds (e.g. from a table and thus protected by\n> > * relfrozenxid).\n> >\n> > and then in\n> >\n> > * Convert 32 bit argument to FullTransactionId. We can do so safely\n> > * because we know the xid has to, at the very least, be between\n> > * [oldestXid, nextXid), i.e. within 2 billion of xid.\n> >\n> > I'm not sure what oldestXid is here.\n> > It's true that I don't see GlobalVisTestIsRemovableXid() being called\n> > anywhere else with an xmin as an input. I think that hints that it is\n> > not safe with FrozenTransactionId. But I don't see what could go\n> > wrong.\n> >\n> > Maybe it has something to do with converting it to a FullTransactionId?\n> >\n> > FullTransactionIdFromU64(U64FromFullTransactionId(rel) + (int32)\n> > (xid - rel_xid));\n> >\n> > Sorry, I couldn't quite figure it out :(\n>\n> I just tested it. No, GlobalVisTestIsRemovableXid does not work for\n> FrozenTransactionId. I just tested it with state->definitely_needed ==\n> {0, 4000000000} and xid == FrozenTransactionid, and it incorrectly\n> returned 'false'. It treats FrozenTransactionId as if was a regular xid '2'.\n\nI see. Looking at the original code:\n if (!TransactionIdPrecedes(xmin,\n vacrel->cutoffs.OldestXmin))\n\nAnd the source code for TransactionIdPrecedes:\n\n\tif (!TransactionIdIsNormal(id1) || !TransactionIdIsNormal(id2))\n\t\treturn (id1 < id2);\n\n\tdiff = (int32) (id1 - id2);\n\treturn (diff < 0);\n\nIn your example, It seems like you mean GlobalVisState->maybe_needed is\n0 and GlobalVisState->definitely_needed = 4000000000. In this example,\nif vacrel->cutoffs.OldestXmin was 0, we would get a wrong answer also.\n\nBut, I do see that the comparison done by TransactionIdPrecedes() is is\nquite different than that done by FullTransactionIdPrecedes() because of\nthe modulo 2**32 arithmetic.\n\nSolving the handling of FrozenTransactionId specifically by\nGlobalVisTestIsRemovableXid() seems like it would be done easily in our\ncase by wrapping it in a function which checks if\nTransactionIdIsNormal() and returns true if it is not normal. But, I'm\nnot sure if I am missing the larger problem.\n\n> >> The XLOG_HEAP2_FREEZE_PAGE record is a little smaller than\n> >> XLOG_HEAP2_PRUNE. But we could optimize the XLOG_HEAP2_PRUNE format for\n> >> the case that there's no pruning, just freezing. The record format\n> >> (xl_heap_prune) looks pretty complex as it is, I think it could be made\n> >> both more compact and more clear with some refactoring.\n> >\n> > I'm happy to change up xl_heap_prune format. In its current form,\n> > according to pahole, it has no holes and just 3 bytes of padding at\n> > the end.\n> >\n> > One way we could make it smaller is by moving the isCatalogRel member\n> > to directly after snapshotConflictHorizon and then adding a flags\n> > field and defining flags to indicate whether or not other members\n> > exist at all. We could set bits for HAS_FREEZE_PLANS, HAS_REDIRECTED,\n> > HAS_UNUSED, HAS_DEAD. Then I would remove the non-optional uint16\n> > nredirected, nunused, nplans, ndead and just put the number of\n> > redirected/unused/etc at the beginning of the arrays containing the\n> > offsets.\n>\n> Sounds good.\n>\n> > Then I could write various macros for accessing them. That\n> > would make it smaller, but it definitely wouldn't make it less complex\n> > (IMO).\n>\n> I don't know, it might turn out not that complex. If you define the\n> formats of each of those \"sub-record types\" as explicit structs, per\n> attached sketch, you won't need so many macros. Some care is still\n> needed with alignment though.\n\nIn the attached v2, I've done as you suggested and made all members\nexcept flags and snapshotConflictHorizon optional in the xl_heap_prune\nstruct and obsoleted the xl_heap_freeze struct. I've kept the actual\nxl_heap_freeze_page struct and heap_xlog_freeze_page() function so that\nwe can replay previously made XLOG_HEAP2_FREEZE_PAGE records.\n\nBecause we may set line pointers unused during vacuum's first pass, I\ncouldn't use the presence of nowunused without redirected or dead items\nto indicate that this was a record emitted by vacuum's second pass. As\nsuch, I haven't obsoleted the xl_heap_vacuum struct. I was thinking I\ncould add a flag that indicates the record was emitted by vacuum's\nsecond pass? We would want to distinguish this so that we could set the\nitems unused without calling heap_page_prune_execute() -- because that\ncalls PageRepairFragmentation() which requires a full cleanup lock.\n\nI introduced a few sub-record types similar to what you suggested --\nthey help a bit with alignment, so I think they are worth keeping. There\nare comments around them, but perhaps a larger diagram of the layout of\na the new XLOG_HEAP2_PRUNE record would be helpful.\n\nThere is a bit of duplicated code between heap_xlog_prune() and\nheap2_desc() since they both need to deserialize the record. Before the\ncode to do this was small and it didn't matter, but it might be worth\nrefactoring it that way now.\n\nNote that I've made all of the changes related to obsoleting the\nXLOG_HEAP2_FREEZE_PAGE record in separate commits on top of the rest of\nthe set for ease of review. However, I've rebased the other review\nfeedback into the relevant commits.\n\nOn Wed, Mar 6, 2024 at 7:59 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> I don't think we need XLOG_HEAP2_FREEZE_PAGE as a separate record type\n> anymore. By removing that, you also get rid of the freeze-only codepath\n> near the end of heap_page_prune(), and the\n> heap_freeze_execute_prepared() function.\n>\n> The XLOG_HEAP2_FREEZE_PAGE record is a little smaller than\n> XLOG_HEAP2_PRUNE. But we could optimize the XLOG_HEAP2_PRUNE format for\n> the case that there's no pruning, just freezing. The record format\n> (xl_heap_prune) looks pretty complex as it is, I think it could be made\n> both more compact and more clear with some refactoring.\n\nOn the point of removing the freeze-only code path from\nheap_page_prune() (now heap_page_prune_and_freeze()): while doing this,\nI realized that heap_pre_freeze_checks() was not being called in the\ncase that we decide to freeze because we emitted an FPI while setting\nthe hint bit. I've fixed that, however, I've done so by moving\nheap_pre_freeze_checks() into the critical section. I think that is not\nokay? I could move it earlier and not do call it when the hint bit FPI\nleads us to freeze tuples. But, I think that would lead to us doing a\nlot less validation of tuples being frozen when checksums are enabled.\nOr, I could make two critical sections?\n\n> FreezeMultiXactId still takes a separate 'cutoffs' arg, but it could use\n> pagefrz->cutoffs now.\n\nFixed this.\n\n> HeapPageFreeze has two \"trackers\", for the \"freeze\" and \"no freeze\"\n> cases. heap_page_prune() needs to track both, until it decides whether\n> to freeze or not. But it doesn't make much sense that the caller\n> (lazy_scan_prune()) has to initialize both, and has to choose which of\n> the values to use after the call depending on whether heap_page_prune()\n> froze or not. The two trackers should be just heap_page_prune()'s\n> internal business.\n\nI've added new_relminmxid and new_relfrozenxid to PruneFreezeResult and\nset them appropriately in heap_page_prune_and_freeze().\n\nIt's a bit sad because if it wasn't for vacrel->skippedallvis,\nvacrel->NewRelfrozenXid and vacrel->NewRelminMxid would be\nvacrel->cutoffs.OldestXmin and vacrel->cutoffs.OldestMxact respectively\nand we could avoid having lazy_scan_prune() initializing the\nHeapPageFreeze altogether and just pass VacuumCutoffs (and\nheap_page_prune_opt() could pass NULL) to heap_page_prune_and_freeze().\n\nI think it is probably worse to add both of them as additional optional\narguments, so I've just left lazy_scan_prune() with the job of\ninitializing them.\n\nIn heap_page_prune_and_freeze(), I initialize new_relminmxid and\nnew_relfrozenxid to InvalidMultiXactId and InvalidTransactionId\nrespectively because on-access pruning doesn't have a value to set them\nto. But I wasn't sure if this was okay -- since I don't see validation\nthat TransactionIdIsValid() in vac_update_relstats(). It will work now\n-- just worried about future issues. I could add an assert there?\n\n> HeapPageFreeze is a bit confusing in general, as it's both an input and\n> an output to heap_page_prune(). Not sure what exactly to do there, but I\n> feel that we should make heap_page_prune()'s interface more clear.\n> Perhaps move the output fields to PruneResult.\n\nHeapPageFrz is now only an input argument to\nheap_page_prune_and_freeze() as of the commit in which\nheap_page_prune_and_freeze() becomes responsible for executing freezing.\nIt is still an in/out param to earlier commits because we still need\ninfo from it to execute freezing in lazy_scan_prune().\n\n> Let's rename heap_page_prune() to heap_page_prune_and_freeze(), as\n> freezing is now an integral part of the function. And mention it in the\n> function comment, too.\n\nI've done this.\n\n> In heap_prune_chain:\n>\n> > * Tuple visibility information is provided in presult->htsv.\n>\n> Not this patch's fault directly, but it's not immediate clear what \"is\n> provided\" means here. Does the caller provide it, or does the function\n> set it, ie. is it an input or output argument? Looking at the code, it's\n> an input, but now it looks a bit weird that an input argument is called\n> 'presult'.\n\nI haven't updated the comments about this in the intermediate commits\nsince it ends up in the PruneState as an input.\n\n- Melanie",
"msg_date": "Wed, 13 Mar 2024 19:25:56 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Wed, Mar 13, 2024 at 07:25:56PM -0400, Melanie Plageman wrote:\n> On Mon, Mar 11, 2024 at 6:38 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> >\n> > On 09/03/2024 22:41, Melanie Plageman wrote:\n> > > On Wed, Mar 6, 2024 at 7:59 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> > >> Does GlobalVisTestIsRemovableXid() handle FrozenTransactionId correctly?\n> > >\n> > > Okay, so I thought a lot about this, and I don't understand how\n> > > GlobalVisTestIsRemovableXid() would not handle FrozenTransactionId\n> > > correctly.\n> > >\n> > > vacrel->cutoffs.OldestXmin is computed initially from\n> > > GetOldestNonRemovableTransactionId() which uses ComputeXidHorizons().\n> > > GlobalVisState is updated by ComputeXidHorizons() (when it is\n> > > updated).\n> > >\n> > > I do see that the comment above GlobalVisTestIsRemovableXid() says\n> > >\n> > > * It is crucial that this only gets called for xids from a source that\n> > > * protects against xid wraparounds (e.g. from a table and thus protected by\n> > > * relfrozenxid).\n> > >\n> > > and then in\n> > >\n> > > * Convert 32 bit argument to FullTransactionId. We can do so safely\n> > > * because we know the xid has to, at the very least, be between\n> > > * [oldestXid, nextXid), i.e. within 2 billion of xid.\n> > >\n> > > I'm not sure what oldestXid is here.\n> > > It's true that I don't see GlobalVisTestIsRemovableXid() being called\n> > > anywhere else with an xmin as an input. I think that hints that it is\n> > > not safe with FrozenTransactionId. But I don't see what could go\n> > > wrong.\n> > >\n> > > Maybe it has something to do with converting it to a FullTransactionId?\n> > >\n> > > FullTransactionIdFromU64(U64FromFullTransactionId(rel) + (int32)\n> > > (xid - rel_xid));\n> > >\n> > > Sorry, I couldn't quite figure it out :(\n> >\n> > I just tested it. No, GlobalVisTestIsRemovableXid does not work for\n> > FrozenTransactionId. I just tested it with state->definitely_needed ==\n> > {0, 4000000000} and xid == FrozenTransactionid, and it incorrectly\n> > returned 'false'. It treats FrozenTransactionId as if was a regular xid '2'.\n> \n> I see. Looking at the original code:\n> if (!TransactionIdPrecedes(xmin,\n> vacrel->cutoffs.OldestXmin))\n> \n> And the source code for TransactionIdPrecedes:\n> \n> \tif (!TransactionIdIsNormal(id1) || !TransactionIdIsNormal(id2))\n> \t\treturn (id1 < id2);\n> \n> \tdiff = (int32) (id1 - id2);\n> \treturn (diff < 0);\n> \n> In your example, It seems like you mean GlobalVisState->maybe_needed is\n> 0 and GlobalVisState->definitely_needed = 4000000000. In this example,\n> if vacrel->cutoffs.OldestXmin was 0, we would get a wrong answer also.\n> \n> But, I do see that the comparison done by TransactionIdPrecedes() is is\n> quite different than that done by FullTransactionIdPrecedes() because of\n> the modulo 2**32 arithmetic.\n> \n> Solving the handling of FrozenTransactionId specifically by\n> GlobalVisTestIsRemovableXid() seems like it would be done easily in our\n> case by wrapping it in a function which checks if\n> TransactionIdIsNormal() and returns true if it is not normal. But, I'm\n> not sure if I am missing the larger problem.\n\nI've made such a wrapper in attached v3.\n\n> > >> The XLOG_HEAP2_FREEZE_PAGE record is a little smaller than\n> > >> XLOG_HEAP2_PRUNE. But we could optimize the XLOG_HEAP2_PRUNE format for\n> > >> the case that there's no pruning, just freezing. The record format\n> > >> (xl_heap_prune) looks pretty complex as it is, I think it could be made\n> > >> both more compact and more clear with some refactoring.\n> > >\n> > > I'm happy to change up xl_heap_prune format. In its current form,\n> > > according to pahole, it has no holes and just 3 bytes of padding at\n> > > the end.\n> > >\n> > > One way we could make it smaller is by moving the isCatalogRel member\n> > > to directly after snapshotConflictHorizon and then adding a flags\n> > > field and defining flags to indicate whether or not other members\n> > > exist at all. We could set bits for HAS_FREEZE_PLANS, HAS_REDIRECTED,\n> > > HAS_UNUSED, HAS_DEAD. Then I would remove the non-optional uint16\n> > > nredirected, nunused, nplans, ndead and just put the number of\n> > > redirected/unused/etc at the beginning of the arrays containing the\n> > > offsets.\n> >\n> > Sounds good.\n> >\n> > > Then I could write various macros for accessing them. That\n> > > would make it smaller, but it definitely wouldn't make it less complex\n> > > (IMO).\n> >\n> > I don't know, it might turn out not that complex. If you define the\n> > formats of each of those \"sub-record types\" as explicit structs, per\n> > attached sketch, you won't need so many macros. Some care is still\n> > needed with alignment though.\n> \n> In the attached v2, I've done as you suggested and made all members\n> except flags and snapshotConflictHorizon optional in the xl_heap_prune\n> struct and obsoleted the xl_heap_freeze struct. I've kept the actual\n> xl_heap_freeze_page struct and heap_xlog_freeze_page() function so that\n> we can replay previously made XLOG_HEAP2_FREEZE_PAGE records.\n> \n> Because we may set line pointers unused during vacuum's first pass, I\n> couldn't use the presence of nowunused without redirected or dead items\n> to indicate that this was a record emitted by vacuum's second pass. As\n> such, I haven't obsoleted the xl_heap_vacuum struct. I was thinking I\n> could add a flag that indicates the record was emitted by vacuum's\n> second pass? We would want to distinguish this so that we could set the\n> items unused without calling heap_page_prune_execute() -- because that\n> calls PageRepairFragmentation() which requires a full cleanup lock.\n\nOkay, so I was going to start using xl_heap_prune for vacuum here too,\nbut I realized it would be bigger because of the\nsnapshotConflictHorizon. Do you think there is a non-terrible way to\nmake the snapshotConflictHorizon optional? Like with a flag?\n\n> I introduced a few sub-record types similar to what you suggested --\n> they help a bit with alignment, so I think they are worth keeping. There\n> are comments around them, but perhaps a larger diagram of the layout of\n> a the new XLOG_HEAP2_PRUNE record would be helpful.\n\nI started doing this, but I can't find a way of laying out the diagram\nthat pgindent doesn't destroy. I thought I remember other diagrams in\nthe source code showing the layout of something (something with pages\nsomewhere?) that don't get messed up by pgindent, but I couldn't find\nthem.\n\n> There is a bit of duplicated code between heap_xlog_prune() and\n> heap2_desc() since they both need to deserialize the record. Before the\n> code to do this was small and it didn't matter, but it might be worth\n> refactoring it that way now.\n\nI have added a helper function to do the deserialization,\nheap_xlog_deserialize_prune_and_freeze(). But I didn't start using it in\nheap2_desc() because of the way the pg_waldump build file works. Do you\nthink the helper belongs in any of waldump's existing sources?\n\n\tpg_waldump_sources = files(\n\t\t'compat.c',\n\t\t'pg_waldump.c',\n\t\t'rmgrdesc.c',\n\t)\n\n\tpg_waldump_sources += rmgr_desc_sources\n\tpg_waldump_sources += xlogreader_sources\n\tpg_waldump_sources += files('../../backend/access/transam/xlogstats.c')\n\nOtherwise, I assume I am suppose to avoid adding some big new include to\nwaldump.\n\n> On Wed, Mar 6, 2024 at 7:59 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> >\n> > I don't think we need XLOG_HEAP2_FREEZE_PAGE as a separate record type\n> > anymore. By removing that, you also get rid of the freeze-only codepath\n> > near the end of heap_page_prune(), and the\n> > heap_freeze_execute_prepared() function.\n> >\n> > The XLOG_HEAP2_FREEZE_PAGE record is a little smaller than\n> > XLOG_HEAP2_PRUNE. But we could optimize the XLOG_HEAP2_PRUNE format for\n> > the case that there's no pruning, just freezing. The record format\n> > (xl_heap_prune) looks pretty complex as it is, I think it could be made\n> > both more compact and more clear with some refactoring.\n> \n> On the point of removing the freeze-only code path from\n> heap_page_prune() (now heap_page_prune_and_freeze()): while doing this,\n> I realized that heap_pre_freeze_checks() was not being called in the\n> case that we decide to freeze because we emitted an FPI while setting\n> the hint bit. I've fixed that, however, I've done so by moving\n> heap_pre_freeze_checks() into the critical section. I think that is not\n> okay? I could move it earlier and not do call it when the hint bit FPI\n> leads us to freeze tuples. But, I think that would lead to us doing a\n> lot less validation of tuples being frozen when checksums are enabled.\n> Or, I could make two critical sections?\n\nI found another approach and just do the pre-freeze checks if we are\nconsidering freezing except for the FPI criteria.\n\n> > HeapPageFreeze has two \"trackers\", for the \"freeze\" and \"no freeze\"\n> > cases. heap_page_prune() needs to track both, until it decides whether\n> > to freeze or not. But it doesn't make much sense that the caller\n> > (lazy_scan_prune()) has to initialize both, and has to choose which of\n> > the values to use after the call depending on whether heap_page_prune()\n> > froze or not. The two trackers should be just heap_page_prune()'s\n> > internal business.\n> \n> I've added new_relminmxid and new_relfrozenxid to PruneFreezeResult and\n> set them appropriately in heap_page_prune_and_freeze().\n> \n> It's a bit sad because if it wasn't for vacrel->skippedallvis,\n> vacrel->NewRelfrozenXid and vacrel->NewRelminMxid would be\n> vacrel->cutoffs.OldestXmin and vacrel->cutoffs.OldestMxact respectively\n> and we could avoid having lazy_scan_prune() initializing the\n> HeapPageFreeze altogether and just pass VacuumCutoffs (and\n> heap_page_prune_opt() could pass NULL) to heap_page_prune_and_freeze().\n> \n> I think it is probably worse to add both of them as additional optional\n> arguments, so I've just left lazy_scan_prune() with the job of\n> initializing them.\n> \n> In heap_page_prune_and_freeze(), I initialize new_relminmxid and\n> new_relfrozenxid to InvalidMultiXactId and InvalidTransactionId\n> respectively because on-access pruning doesn't have a value to set them\n> to. But I wasn't sure if this was okay -- since I don't see validation\n> that TransactionIdIsValid() in vac_update_relstats(). It will work now\n> -- just worried about future issues. I could add an assert there?\n\nI looked more closely at vac_update_relstats() and it won't update\nrelfrozenxid unless the proposed value is smaller than the existing one.\nAnd for MultiXactIds, it checks if it is valid. So, this is not an\nissue.\n\nI've also optimized the member ordering of PruneFreezeResult. pahole\nidentified some avoidable holes. I went through each commit and\noptimized the PruneResult data structure as members are being added and\nremoved.\n\n- Melanie",
"msg_date": "Thu, 14 Mar 2024 20:56:58 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 15/03/2024 02:56, Melanie Plageman wrote:\n> Okay, so I was going to start using xl_heap_prune for vacuum here too,\n> but I realized it would be bigger because of the\n> snapshotConflictHorizon. Do you think there is a non-terrible way to\n> make the snapshotConflictHorizon optional? Like with a flag?\n\nYeah, another flag would do the trick.\n\n>> I introduced a few sub-record types similar to what you suggested --\n>> they help a bit with alignment, so I think they are worth keeping. There\n>> are comments around them, but perhaps a larger diagram of the layout of\n>> a the new XLOG_HEAP2_PRUNE record would be helpful.\n> \n> I started doing this, but I can't find a way of laying out the diagram\n> that pgindent doesn't destroy. I thought I remember other diagrams in\n> the source code showing the layout of something (something with pages\n> somewhere?) that don't get messed up by pgindent, but I couldn't find\n> them.\n\nSee src/tools/pgindent/README, section \"Cleaning up in case of failure \nor ugly output\":\n\n /*----------\n * Text here will not be touched by pgindent.\n */\n\n>> There is a bit of duplicated code between heap_xlog_prune() and\n>> heap2_desc() since they both need to deserialize the record. Before the\n>> code to do this was small and it didn't matter, but it might be worth\n>> refactoring it that way now.\n> \n> I have added a helper function to do the deserialization,\n> heap_xlog_deserialize_prune_and_freeze(). But I didn't start using it in\n> heap2_desc() because of the way the pg_waldump build file works. Do you\n> think the helper belongs in any of waldump's existing sources?\n> \n> \tpg_waldump_sources = files(\n> \t\t'compat.c',\n> \t\t'pg_waldump.c',\n> \t\t'rmgrdesc.c',\n> \t)\n> \n> \tpg_waldump_sources += rmgr_desc_sources\n> \tpg_waldump_sources += xlogreader_sources\n> \tpg_waldump_sources += files('../../backend/access/transam/xlogstats.c')\n> \n> Otherwise, I assume I am suppose to avoid adding some big new include to\n> waldump.\n\nDidn't look closely at that, but there's some precedent with \ncommit/prepare/abort records. See ParseCommitRecord, xl_xact_commit, \nxl_parsed_commit et al.\n\nNote that we don't provide WAL compatibility across major versions. You \ncan fully remove the old xl_heap_freeze_page format. (We should bump \nXLOG_PAGE_MAGIC when this is committed though)\n\n>> On the point of removing the freeze-only code path from\n>> heap_page_prune() (now heap_page_prune_and_freeze()): while doing this,\n>> I realized that heap_pre_freeze_checks() was not being called in the\n>> case that we decide to freeze because we emitted an FPI while setting\n>> the hint bit. I've fixed that, however, I've done so by moving\n>> heap_pre_freeze_checks() into the critical section. I think that is not\n>> okay? I could move it earlier and not do call it when the hint bit FPI\n>> leads us to freeze tuples. But, I think that would lead to us doing a\n>> lot less validation of tuples being frozen when checksums are enabled.\n>> Or, I could make two critical sections?\n> \n> I found another approach and just do the pre-freeze checks if we are\n> considering freezing except for the FPI criteria.\n\nHmm, I think you can make this simpler if you use \nXLogCheckBufferNeedsBackup() to check if the hint-bit update will \ngenerate a full-page-image before entering the critical section. Like \nyou did to check if pruning will generate a full-page-image. I included \nthat change in the attached patches.\n\nI don't fully understand this:\n\n> \t/*\n> \t * If we will freeze tuples on the page or they were all already frozen\n> \t * on the page, if we will set the page all-frozen in the visibility map,\n> \t * we can advance relfrozenxid and relminmxid to the values in\n> \t * pagefrz->FreezePageRelfrozenXid and pagefrz->FreezePageRelminMxid.\n> \t */\n> \tif (presult->all_frozen || presult->nfrozen > 0)\n> \t{\n> \t\tpresult->new_relfrozenxid = pagefrz->FreezePageRelfrozenXid;\n> \t\tpresult->new_relminmxid = pagefrz->FreezePageRelminMxid;\n> \t}\n> \telse\n> \t{\n> \t\tpresult->new_relfrozenxid = pagefrz->NoFreezePageRelfrozenXid;\n> \t\tpresult->new_relminmxid = pagefrz->NoFreezePageRelminMxid;\n> \t}\n\nFirstly, the comment is outdated, because we have already done the \nfreezing at this point. But more importantly, I don't understand the \nlogic here. Could we check just presult->nfrozen > 0 here and get the \nsame result?\n\n>> I think it is probably worse to add both of them as additional optional\n>> arguments, so I've just left lazy_scan_prune() with the job of\n>> initializing them.\n\nOk.\n\n\nHere are some patches on top of your patches for some further \nrefactorings. Some notable changes in heap_page_prune_and_freeze():\n\n- I moved the heap_prepare_freeze_tuple() work from the 2nd loop to the \n1st one. It seems more clear and efficient that way.\n\n- I extracted the code to generate the WAL record to a separate function.\n\n- Refactored the \"will setting hint bit generate FPI\" check as discussed \nabove\n\nThese patches are in a very rough WIP state, but I wanted to share \nearly. I haven't done much testing, and I'm not wedded to these changes, \nbut I think they make it more readable. Please include / squash in the \npatch set if you agree with them.\n\nPlease also take a look at the comments I marked with HEIKKI or FIXME, \nin the patches and commit messages.\n\nI'll wait for a new version from you before reviewing more.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)",
"msg_date": "Mon, 18 Mar 2024 01:15:21 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Mon, Mar 18, 2024 at 01:15:21AM +0200, Heikki Linnakangas wrote:\n> On 15/03/2024 02:56, Melanie Plageman wrote:\n> > Okay, so I was going to start using xl_heap_prune for vacuum here too,\n> > but I realized it would be bigger because of the\n> > snapshotConflictHorizon. Do you think there is a non-terrible way to\n> > make the snapshotConflictHorizon optional? Like with a flag?\n> \n> Yeah, another flag would do the trick.\n\nOkay, I've done this in attached v4 (including removing\nXLOG_HEAP2_VACUUM). I had to put the snapshot conflict horizon in the\n\"main chunk\" of data available at replay regardless of whether or not\nthe record ended up including an FPI.\n\nI made it its own sub-record (xlhp_conflict_horizon) less to help with\nalignment (though we can use all the help we can get there) and more to\nkeep it from getting lost. When you look at heapam_xlog.h, you can see\nwhat a XLOG_HEAP2_PRUNE record will contain starting with the\nxl_heap_prune struct and then all the sub-record types.\n\n> > > I introduced a few sub-record types similar to what you suggested --\n> > > they help a bit with alignment, so I think they are worth keeping. There\n> > > are comments around them, but perhaps a larger diagram of the layout of\n> > > a the new XLOG_HEAP2_PRUNE record would be helpful.\n> > \n> > I started doing this, but I can't find a way of laying out the diagram\n> > that pgindent doesn't destroy. I thought I remember other diagrams in\n> > the source code showing the layout of something (something with pages\n> > somewhere?) that don't get messed up by pgindent, but I couldn't find\n> > them.\n> \n> See src/tools/pgindent/README, section \"Cleaning up in case of failure or\n> ugly output\":\n> \n> /*----------\n> * Text here will not be touched by pgindent.\n> */\n> \n\nCool. This version doesn't include the spiffy drawing I promised yet.\n\n> Note that we don't provide WAL compatibility across major versions. You can\n> fully remove the old xl_heap_freeze_page format. (We should bump\n> XLOG_PAGE_MAGIC when this is committed though)\n\nI've removed the xl_heap_freeze (and xl_heap_prune). I didn't bump\nXLOG_PAGE_MAGIC.\n\n> > > On the point of removing the freeze-only code path from\n> > > heap_page_prune() (now heap_page_prune_and_freeze()): while doing this,\n> > > I realized that heap_pre_freeze_checks() was not being called in the\n> > > case that we decide to freeze because we emitted an FPI while setting\n> > > the hint bit. I've fixed that, however, I've done so by moving\n> > > heap_pre_freeze_checks() into the critical section. I think that is not\n> > > okay? I could move it earlier and not do call it when the hint bit FPI\n> > > leads us to freeze tuples. But, I think that would lead to us doing a\n> > > lot less validation of tuples being frozen when checksums are enabled.\n> > > Or, I could make two critical sections?\n> > \n> > I found another approach and just do the pre-freeze checks if we are\n> > considering freezing except for the FPI criteria.\n> \n> Hmm, I think you can make this simpler if you use\n> XLogCheckBufferNeedsBackup() to check if the hint-bit update will generate a\n> full-page-image before entering the critical section. Like you did to check\n> if pruning will generate a full-page-image. I included that change in the\n> attached patches.\n\nI used your proposed structure. You had XLogCheckBufferNeedsBackup()\ntwice in your proposed version a few lines apart. I don't think there is\nany point in checking it twice. If we are going to rely on\nXLogCheckBufferNeedsBackup() to tell us whether or not setting the hint\nbit is *likely* to emit an FPI, then we might as well just call\nXLogCheckBufferNeedsBackup() once.\n\n> I don't fully understand this:\n> \n> > \t/*\n> > \t * If we will freeze tuples on the page or they were all already frozen\n> > \t * on the page, if we will set the page all-frozen in the visibility map,\n> > \t * we can advance relfrozenxid and relminmxid to the values in\n> > \t * pagefrz->FreezePageRelfrozenXid and pagefrz->FreezePageRelminMxid.\n> > \t */\n> > \tif (presult->all_frozen || presult->nfrozen > 0)\n> > \t{\n> > \t\tpresult->new_relfrozenxid = pagefrz->FreezePageRelfrozenXid;\n> > \t\tpresult->new_relminmxid = pagefrz->FreezePageRelminMxid;\n> > \t}\n> > \telse\n> > \t{\n> > \t\tpresult->new_relfrozenxid = pagefrz->NoFreezePageRelfrozenXid;\n> > \t\tpresult->new_relminmxid = pagefrz->NoFreezePageRelminMxid;\n> > \t}\n> \n> Firstly, the comment is outdated, because we have already done the freezing\n> at this point. But more importantly, I don't understand the logic here.\n> Could we check just presult->nfrozen > 0 here and get the same result?\n\nI've updated the comment. The reason I had\nif (presult->all_frozen || presult->nfrozen > 0) was because of this\ncomment in heapam.h in the HeapPageFreeze struct\n\n\t * \"Freeze\" NewRelfrozenXid/NewRelminMxid trackers.\n\t *\n\t * Trackers used when heap_freeze_execute_prepared freezes, or when there\n\t * are zero freeze plans for a page. It is always valid for vacuumlazy.c\n\t * to freeze any page, by definition. This even includes pages that have\n\t * no tuples with storage to consider in the first place. That way the\n\t * 'totally_frozen' results from heap_prepare_freeze_tuple can always be\n\t * used in the same way, even when no freeze plans need to be executed to\n\t * \"freeze the page\". Only the \"freeze\" path needs to consider the need\n\t * to set pages all-frozen in the visibility map under this scheme.\n\t *\n\t * When we freeze a page, we generally freeze all XIDs < OldestXmin, only\n\t * leaving behind XIDs that are ineligible for freezing, if any. And so\n\t * you might wonder why these trackers are necessary at all; why should\n\t * _any_ page that VACUUM freezes _ever_ be left with XIDs/MXIDs that\n\t * ratchet back the top-level NewRelfrozenXid/NewRelminMxid trackers?\n\t *\n\t * It is useful to use a definition of \"freeze the page\" that does not\n\t * overspecify how MultiXacts are affected. heap_prepare_freeze_tuple\n\t * generally prefers to remove Multis eagerly, but lazy processing is used\n\t * in cases where laziness allows VACUUM to avoid allocating a new Multi.\n\t * The \"freeze the page\" trackers enable this flexibility.\n\t */\n\nSo, I don't really know if it is right to just check presult->nfrozen >\n0 when updating relminmxid. I have changed it to the way you suggested.\nBut we can change it back.\n\n> Here are some patches on top of your patches for some further refactorings.\n> Some notable changes in heap_page_prune_and_freeze():\n> \n> - I moved the heap_prepare_freeze_tuple() work from the 2nd loop to the 1st\n> one. It seems more clear and efficient that way.\n\ncool. I kept this.\n\n> - I extracted the code to generate the WAL record to a separate function.\n\ncool. kept this.\n\n> These patches are in a very rough WIP state, but I wanted to share early. I\n> haven't done much testing, and I'm not wedded to these changes, but I think\n> they make it more readable. Please include / squash in the patch set if you\n> agree with them.\n\nI've squashed the changes into and across my nineteen patches :)\n\nI cleaned up your sugestions a bit and made a few stylistic choices.\n\nIn this version, I also broke up the last couple commits which\nstreamlined the WAL record and eliminated XLOG_HEAP2_FREEZE/VACUUM and\nredistributed those changes in a way that I thought made sense.\n\nNow, the progression is that in one commit we merge the prune and freeze\nrecord, eliminating the XLOG_HEAP2_FREEZE record. Then, in another\ncommit, we eliminate the XLOG_HEAP2_VACUUM record. Then a later commit\nstreamlines the new mega xl_heap_prune struct into the variable size\nstructure based on which modifications it includes.\n\n> From 622620a7875ae8c1626e9cd118156e0c734d44ed Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Sun, 17 Mar 2024 22:52:28 +0200\n> Subject: [PATCH v3heikki 1/4] Inline heap_frz_conflict_horizon() to the\n> caller.\n> \n> FIXME: This frz_conflict_horizon business looks fishy to me. We have:\n> - local frz_conflict_horizon variable,\n> - presult->frz_conflict_horizon, and\n> - prstate.snapshotConflictHorizon\n\nYea, this is a mistake I made when I was rebasing some changes in. The\nlocal variable is gone now.\n\n\n> should we really have all three, and what are the differences?\n\nWe do need both the prstate.snapshotConflictHorizon and the\npresult->frz_conflict_horizon because the youngest freezable xmin will\noften be different than the oldest removable xmax, so we have to track\nboth and take the most conservative one if we are both freezing and\npruning.\n\nThe third (local variable) one was an oops.\n\n> From 0219842487931f899abcf183c863c43270c098f0 Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Sun, 17 Mar 2024 23:05:31 +0200\n> Subject: [PATCH v3heikki 2/4] Misc cleanup\n> ---\n> src/backend/access/heap/pruneheap.c | 16 +++++++---------\n> src/backend/access/heap/vacuumlazy.c | 7 ++++++-\n> 2 files changed, 13 insertions(+), 10 deletions(-)\n> diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c\n> index 8d3723faf3a..d3df7029667 100644\n> --- a/src/backend/access/heap/vacuumlazy.c\n> +++ b/src/backend/access/heap/vacuumlazy.c\n> @@ -433,7 +433,9 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,\n> \t * heap_page_prune_and_freeze(). We expect vistest will always make\n> \t * heap_page_prune_and_freeze() remove any deleted tuple whose xmax is <\n> \t * OldestXmin. lazy_scan_prune must never become confused about whether a\n> -\t * tuple should be frozen or removed. (In the future we might want to\n> +\t * tuple should be frozen or removed.\n> +\t * HEIKKI: Is such confusion possible anymore?\n> +\t * (In the future we might want to\n> \t * teach lazy_scan_prune to recompute vistest from time to time, to\n> \t * increase the number of dead tuples it can prune away.)\n\nTBH, I don't really know what this comment is even saying. But\nlazy_scan_prune() doesn't do any freezing anymore, so I removed this\nsentence.\n\n> \t */\n> @@ -1387,6 +1389,9 @@ lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,\n> * so we could deal with tuples that were DEAD to VACUUM, but nevertheless were\n> * left with storage after pruning.\n> *\n> + * HEIKKI: does the above paragraph still make sense? We don't call\n> + * HeapTupleSatisfiesVacuum() here anymore\n> + *\n\nYea this whole comment definitely doesn't belong here anymore. Even\nthough we are calling HeapTupleSatisfiesVacuum() (from inside\nheap_prune_satisifes_vacuum()) inside heap_page_prune_and_freeze(), the\ncomment really doesn't fit anywhere in there either. The comment is\ndescribing a situation that is no longer possible. So describing a\nsituation that is no longer possible in a part of the code that it never\ncould have been possible does not make sense to me. I've removed the\ncomment.\n\n> * As of Postgres 17, we circumvent this problem altogether by reusing the\n> * result of heap_page_prune_and_freeze()'s visibility check. Without the\n> * second call to HeapTupleSatisfiesVacuum(), there is no new HTSV_Result and\n> -- \n> 2.39.2\n> \n\n> From d72cebf13f9866112309883f72a382fc2cb57e17 Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Sun, 17 Mar 2024 23:08:42 +0200\n> Subject: [PATCH v3heikki 3/4] Move work to the first loop\n> src/backend/access/heap/pruneheap.c | 141 ++++++++++------------------\n> 1 file changed, 52 insertions(+), 89 deletions(-)\n> \n> diff --git a/src/backend/access/heap/pruneheap.c b/src/backend/access/heap/pruneheap.c\n> index b3573bb628b..3541628799a 100644\n> --- a/src/backend/access/heap/pruneheap.c\n> +++ b/src/backend/access/heap/pruneheap.c\n> @@ -78,9 +78,6 @@ static int\theap_prune_chain(Buffer buffer,\n> \t\t\t\t\t\t\t PruneState *prstate, PruneFreezeResult *presult);\n> \n> static inline HTSV_Result htsv_get_valid_status(int status);\n> -static void prune_prepare_freeze_tuple(Page page, OffsetNumber offnum, PruneState *prstate,\n> -\t\t\t\t\t\t\t\t\t HeapPageFreeze *pagefrz, HeapTupleFreeze *frozen,\n> -\t\t\t\t\t\t\t\t\t PruneFreezeResult *presult);\n> static void heap_prune_record_prunable(PruneState *prstate, TransactionId xid);\n> static void heap_prune_record_redirect(PruneState *prstate,\n> \t\t\t\t\t\t\t\t\t OffsetNumber offnum, OffsetNumber rdoffnum,\n> @@ -322,6 +319,16 @@ heap_page_prune_and_freeze(Relation relation, Buffer buffer,\n> \t/* for recovery conflicts */\n> \tpresult->frz_conflict_horizon = InvalidTransactionId;\n> \n> +\t/*\n> +\t * We will update the VM after pruning, collecting LP_DEAD items, and\n> +\t * freezing tuples. Keep track of whether or not the page is all_visible\n> +\t * and all_frozen and use this information to update the VM. all_visible\n> +\t * implies lpdead_items == 0, but don't trust all_frozen result unless\n> +\t * all_visible is also set to true.\n> +\t */\n> +\t/* HEIKKI: the caller updates the VM? not us */\n\nI've updated this comment.\n\nOther questions and notes on v4:\n\nxl_heap_prune->flags is a uint8, but we are already using 7 of the bits.\nShould we make it a unit16?\n\nEventually, I would like to avoid emitting a separate XLOG_HEAP2_VISIBLE\nrecord for vacuum's first and second passes and just include the VM\nupdate flags in the xl_heap_prune record. xl_heap_visible->flags is a\nuint8. If we made xl_heap_prune->flags uint16, we could probably combine\nthem (though maybe we want other bits available). Also vacuum's second\npass doesn't set a snapshotConflictHorizon, so if we combined\nxl_heap_visible and xl_heap_prune for vacuum we would end up saving even\nmore space (since vacuum sets xl_heap_visible->snapshotConflictHorizon\nto InvalidXLogRecPtr).\n\nA note on sub-record naming: I kept xl_heap_freeze_plan's name but\nprefixed the other sub-records with xlhp. Do you think it is worth\nrenaming it (to xlhp_freeze_plan)? Also, should I change xlhp_freeze to\nxlhp_freeze_page?\n\n- Melanie",
"msg_date": "Tue, 19 Mar 2024 21:36:02 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 20/03/2024 03:36, Melanie Plageman wrote:\n> On Mon, Mar 18, 2024 at 01:15:21AM +0200, Heikki Linnakangas wrote:\n>> On 15/03/2024 02:56, Melanie Plageman wrote:\n>>> Okay, so I was going to start using xl_heap_prune for vacuum here too,\n>>> but I realized it would be bigger because of the\n>>> snapshotConflictHorizon. Do you think there is a non-terrible way to\n>>> make the snapshotConflictHorizon optional? Like with a flag?\n>>\n>> Yeah, another flag would do the trick.\n> \n> Okay, I've done this in attached v4 (including removing\n> XLOG_HEAP2_VACUUM). I had to put the snapshot conflict horizon in the\n> \"main chunk\" of data available at replay regardless of whether or not\n> the record ended up including an FPI.\n> \n> I made it its own sub-record (xlhp_conflict_horizon) less to help with\n> alignment (though we can use all the help we can get there) and more to\n> keep it from getting lost. When you look at heapam_xlog.h, you can see\n> what a XLOG_HEAP2_PRUNE record will contain starting with the\n> xl_heap_prune struct and then all the sub-record types.\n\nOk, now that I look at this, I wonder if we're being overly cautious \nabout the WAL size. We probably could just always include the snapshot \nfield, and set it to InvalidTransactionId and waste 4 bytes when it's \nnot needed. For the sake of simplicity. I don't feel strongly either way \nthough, the flag is pretty simple too.\n\n> xl_heap_prune->flags is a uint8, but we are already using 7 of the bits.\n> Should we make it a unit16?\n\nIt doesn't matter much either way. We can also make it larger when we \nneed more bits, there's no need make room for them them beforehand.\n\n> Eventually, I would like to avoid emitting a separate XLOG_HEAP2_VISIBLE\n> record for vacuum's first and second passes and just include the VM\n> update flags in the xl_heap_prune record. xl_heap_visible->flags is a\n> uint8. If we made xl_heap_prune->flags uint16, we could probably combine\n> them (though maybe we want other bits available). Also vacuum's second\n> pass doesn't set a snapshotConflictHorizon, so if we combined\n> xl_heap_visible and xl_heap_prune for vacuum we would end up saving even\n> more space (since vacuum sets xl_heap_visible->snapshotConflictHorizon\n> to InvalidXLogRecPtr).\n\nMakes sense.\n\n> A note on sub-record naming: I kept xl_heap_freeze_plan's name but\n> prefixed the other sub-records with xlhp. Do you think it is worth\n> renaming it (to xlhp_freeze_plan)?\n\nYeah, perhaps.\n\n> Also, should I change xlhp_freeze to xlhp_freeze_page?\nI renamed it to xlhp_freeze_plans, for some consistency with \nxlhp_prune_items.\n\n\nI realized that the WAL record format changes are pretty independent \nfrom the rest of the patches. They could be applied before the rest. \nWithout the rest of the changes, we'll still write two WAL records per \npage in vacuum, one to prune and another one to freeze, but it's another \nmeaningful incremental step. So I reshuffled the patches, so that the \nWAL format is changed first, before the rest of the changes.\n\n0001-0008: These are the WAL format changes. There's some comment \ncleanup needed, but as far as the code goes, I think these are pretty \nmuch ready to be squashed & committed.\n\n0009-: The rest of the v4 patches, rebased over the WAL format changes. \nI also added a few small commits for little cleanups that caught my eye, \nlet me know if you disagree with those.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)",
"msg_date": "Wed, 20 Mar 2024 15:15:49 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Wed, Mar 20, 2024 at 03:15:49PM +0200, Heikki Linnakangas wrote:\n> On 20/03/2024 03:36, Melanie Plageman wrote:\n> > On Mon, Mar 18, 2024 at 01:15:21AM +0200, Heikki Linnakangas wrote:\n> > > On 15/03/2024 02:56, Melanie Plageman wrote:\n> > > > Okay, so I was going to start using xl_heap_prune for vacuum here too,\n> > > > but I realized it would be bigger because of the\n> > > > snapshotConflictHorizon. Do you think there is a non-terrible way to\n> > > > make the snapshotConflictHorizon optional? Like with a flag?\n> > > \n> > > Yeah, another flag would do the trick.\n> > \n> > Okay, I've done this in attached v4 (including removing\n> > XLOG_HEAP2_VACUUM). I had to put the snapshot conflict horizon in the\n> > \"main chunk\" of data available at replay regardless of whether or not\n> > the record ended up including an FPI.\n> > \n> > I made it its own sub-record (xlhp_conflict_horizon) less to help with\n> > alignment (though we can use all the help we can get there) and more to\n> > keep it from getting lost. When you look at heapam_xlog.h, you can see\n> > what a XLOG_HEAP2_PRUNE record will contain starting with the\n> > xl_heap_prune struct and then all the sub-record types.\n> \n> Ok, now that I look at this, I wonder if we're being overly cautious about\n> the WAL size. We probably could just always include the snapshot field, and\n> set it to InvalidTransactionId and waste 4 bytes when it's not needed. For\n> the sake of simplicity. I don't feel strongly either way though, the flag is\n> pretty simple too.\n\nThat will mean that all vacuum records are at least 3 bytes bigger than\nbefore -- which makes it somewhat less defensible to get rid of\nxl_heap_vacuum.\n\nThat being said, I ended up doing an unaligned access when I\npacked it and made it optional, so maybe it is less user-friendly.\n\nBut I also think that making it optional is more clear for vacuum which\nwill never use it.\n\n> I realized that the WAL record format changes are pretty independent from\n> the rest of the patches. They could be applied before the rest. Without the\n> rest of the changes, we'll still write two WAL records per page in vacuum,\n> one to prune and another one to freeze, but it's another meaningful\n> incremental step. So I reshuffled the patches, so that the WAL format is\n> changed first, before the rest of the changes.\n\nAh, great idea! That eliminates the issue of preliminary commits having\nlarger WAL records that then get streamlined.\n\n> 0001-0008: These are the WAL format changes. There's some comment cleanup\n> needed, but as far as the code goes, I think these are pretty much ready to\n> be squashed & committed.\n\nMy review in this email is *only* for 0001-0008. I have not looked at\nthe rest yet.\n\n> From 06d5ff5349a8aa95cbfd06a8043fe503b7b1bf7b Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Wed, 20 Mar 2024 14:50:14 +0200\n> Subject: [PATCH v5 01/26] Merge prune, freeze and vacuum WAL record formats\n> \n> The new combined WAL record is now used for pruning, freezing and 2nd\n> pass of vacuum. This is in preparation of changing vacuuming to write\n> a combined prune+freeze record per page, instead of separate two\n> records. The new WAL record format now supports that, but the code\n> still always writes separate records for pruning and freezing.\n\nAttached patch changes-for-0001.patch has a bunch of updated comments --\nespecially for heapam_xlog.h (including my promised diagram). And a few\nsuggestions (mostly changes that I should have made before).\n\n> \n> XXX I tried to lift-and-shift the code from v4 patch set as unchanged\n> as possible, for easier review, but some noteworthy changes:\n\nIn the final commit message, I think it is worth calling out that all of\nthose freeze logging functions heap_log_freeze_eq/cmp/etc are lifted and\nshifted from one file to another. When I am reviewing a big diff, it is\nalways helpful to know where I need to review line-by-line.\n\n> \n> - Instead of passing PruneState and PageFreezeResult to\n> log_heap_prune_and_freeze(), pass the arrays of frozen, redirected\n> et al offsets directly. That way, it can be called from other places.\n\ngood idea.\n\n> - moved heap_xlog_deserialize_prune_and_freeze() from xactdesc.c to\n> heapdesc.c. (Because that's clearly where it belongs)\n\n:)\n\n> From cd6cdaebb362b014733e99ecd868896caf0fb3aa Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Wed, 20 Mar 2024 13:45:01 +0200\n> Subject: [PATCH v5 02/26] Keep the original numbers for existing WAL records\n> \n> Doesn't matter much because the WAL format is not compatible across\n> major versions anyway. But still seems nice to keep the identifiers\n> unchanged when we can. (There's some precedence for this if you search\n> the git history for \"is free, was\").\n\nsounds good.\n\n> From d3207bb557aa1d2868a50d357a06318a6c0cb5cd Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Wed, 20 Mar 2024 13:48:29 +0200\n> Subject: [PATCH v5 03/26] Rename record to XLOG_HEAP2_PRUNE_FREEZE\n> \n> To clarify that it also freezes now, and to make it clear that it's\n> significantly different from the old XLOG_HEAP2_PRUNE format.\n\n+1 \n\n> From 5d6fc2ffbdd839e0b69242af16446a46cf6a2dc7 Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Wed, 20 Mar 2024 13:49:59 +0200\n> Subject: [PATCH v5 04/26] 'nplans' is a pointer\n> \n> I'm surprised the compiler didn't warn about this\n\noops. while looking at this, I noticed that the asserts I added that\nnredirected > 0, ndead > 0, and nunused > 0 have the same problem.\n\n> ---\n> src/backend/access/rmgrdesc/heapdesc.c | 3 +--\n> 1 file changed, 1 insertion(+), 2 deletions(-)\n> \n> diff --git a/src/backend/access/rmgrdesc/heapdesc.c b/src/backend/access/rmgrdesc/heapdesc.c\n> index 8b94c869faf..9ef8a745982 100644\n> --- a/src/backend/access/rmgrdesc/heapdesc.c\n> +++ b/src/backend/access/rmgrdesc/heapdesc.c\n> @@ -155,8 +155,7 @@ heap_xlog_deserialize_prune_and_freeze(char *cursor, uint8 flags,\n> \t\tcursor += sizeof(OffsetNumber) * *nunused;\n> \t}\n> \n> -\tif (nplans > 0)\n\n> From 59f3f80f82ed7a63d86c991d0cb025e4cde2caec Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Wed, 20 Mar 2024 13:36:41 +0200\n> Subject: [PATCH v5 06/26] Fix logging snapshot conflict horizon.\n> \n> - it was accessed without proper alignment, which won't work on\n> architectures that are strict about alignment. Use memcpy.\n\nwow, oops. thanks for fixing this!\n\n> - in heap_xlog_prune_freeze, the code tried to access the xid with\n> \"(xlhp_conflict_horizon *) (xlrec + SizeOfHeapPrune);\" But 'xlrec'\n> was \"xl_heap_prune *\" rather than \"char *\". That happened to work,\n> because sizeof(xl_heap_prune) == 1, but make it more robust by\n> adding a cast to char *.\n\ngood catch.\n\n> - remove xlhp_conflict_horizon and store a TransactionId directly. A\n> separate struct would make sense if we needed to store anything else\n> there, but for now it just seems like more code.\n\nmakes sense. I just want to make sure heapam_xlog.h makes it extra clear\nthat this is happening. I see your comment addition. If you combine it\nwith my comment additions in the attached patch for 0001, hopefully that\nmakes it clear enough.\n\n> From 8af186ee9dd8c7dc20f37a69b34cab7b95faa43b Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Wed, 20 Mar 2024 14:03:06 +0200\n> Subject: [PATCH v5 07/26] Add comment to log_heap_prune_and_freeze().\n> \n> XXX: This should be rewritten, but I tried to at least list some\n> important points.\n\nAre you thinking that it needs to mention more things or that the things\nit mentions need more detail?\n\n> From b26e36ba8614d907a6e15810ed4f684f8f628dd2 Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Wed, 20 Mar 2024 14:53:31 +0200\n> Subject: [PATCH v5 08/26] minor refactoring in log_heap_prune_and_freeze()\n> \n> Mostly to make local variables more tightly-scoped.\n\nSo, I don't think you can move those sub-records into the tighter scope.\nIf you run tests with this applied, you'll see it crashes and a lot of\nthe data in the record is wrong. If you move the sub-record declarations\nout to a wider scope, the tests pass.\n\nThe WAL record data isn't actually copied into the buffer until\n\n\trecptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_PRUNE_FREEZE);\n\nafter registering everything.\nSo all of those sub-records you made are out of scope the time it tries\nto copy from them.\n\nI spent the better part of a day last week trying to figure out what was\nhappening after I did the exact same thing. I must say that I found the\nxloginsert API incredibly unhelpful on this point.\n\nI would like to review the rest of the suggested changes in this patch\nafter we fix the issue I just mentioned.\n\n- Melanie",
"msg_date": "Wed, 20 Mar 2024 15:17:10 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Wed, Mar 20, 2024 at 9:15 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> > I made it its own sub-record (xlhp_conflict_horizon) less to help with\n> > alignment (though we can use all the help we can get there) and more to\n> > keep it from getting lost. When you look at heapam_xlog.h, you can see\n> > what a XLOG_HEAP2_PRUNE record will contain starting with the\n> > xl_heap_prune struct and then all the sub-record types.\n>\n> Ok, now that I look at this, I wonder if we're being overly cautious\n> about the WAL size. We probably could just always include the snapshot\n> field, and set it to InvalidTransactionId and waste 4 bytes when it's\n> not needed. For the sake of simplicity. I don't feel strongly either way\n> though, the flag is pretty simple too.\n\nWhat about the issue of cleanup locks, which aren't needed and aren't\ntaken with the current heapam VACUUM record type? Will you preserve\nthat aspect of the existing design?\n\n-- \nPeter Geoghegan\n\n\n",
"msg_date": "Wed, 20 Mar 2024 16:04:28 -0400",
"msg_from": "Peter Geoghegan <pg@bowt.ie>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Wed, Mar 20, 2024 at 4:04 PM Peter Geoghegan <pg@bowt.ie> wrote:\n>\n> On Wed, Mar 20, 2024 at 9:15 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> > > I made it its own sub-record (xlhp_conflict_horizon) less to help with\n> > > alignment (though we can use all the help we can get there) and more to\n> > > keep it from getting lost. When you look at heapam_xlog.h, you can see\n> > > what a XLOG_HEAP2_PRUNE record will contain starting with the\n> > > xl_heap_prune struct and then all the sub-record types.\n> >\n> > Ok, now that I look at this, I wonder if we're being overly cautious\n> > about the WAL size. We probably could just always include the snapshot\n> > field, and set it to InvalidTransactionId and waste 4 bytes when it's\n> > not needed. For the sake of simplicity. I don't feel strongly either way\n> > though, the flag is pretty simple too.\n>\n> What about the issue of cleanup locks, which aren't needed and aren't\n> taken with the current heapam VACUUM record type? Will you preserve\n> that aspect of the existing design?\n\nYep, we have a flag to indicate whether or not a cleanup lock is needed.\n\n- Melanie\n\n\n",
"msg_date": "Wed, 20 Mar 2024 16:06:13 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Wed, Mar 20, 2024 at 4:06 PM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n> > What about the issue of cleanup locks, which aren't needed and aren't\n> > taken with the current heapam VACUUM record type? Will you preserve\n> > that aspect of the existing design?\n>\n> Yep, we have a flag to indicate whether or not a cleanup lock is needed.\n\nThanks for confirming.\n\nI realize that this is fairly obvious, but thought it better to ask.\n\n-- \nPeter Geoghegan\n\n\n",
"msg_date": "Wed, 20 Mar 2024 16:10:11 -0400",
"msg_from": "Peter Geoghegan <pg@bowt.ie>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Wed, Mar 20, 2024 at 03:15:49PM +0200, Heikki Linnakangas wrote:\n>\n> 0009-: The rest of the v4 patches, rebased over the WAL format changes. I\n> also added a few small commits for little cleanups that caught my eye, let\n> me know if you disagree with those.\n\nThis review is just of the patches containing changes you made in\n0009-0026.\n\n> From d36138b5bf0a93557273b5e47f8cd5ea089057c7 Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Wed, 20 Mar 2024 11:47:42 +0200\n> Subject: [PATCH v5 13/26] still use a local 'cutoffs' variable\n> \n> Given how often 'cutoffs' is used in the function, I think it still\n> makes sense to have a local variable for it, just to keep the source\n> lines shorter.\n\nWorks for me.\n\n> From 913617ed98cfddd678a6f620db7dee68d1d61c89 Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Wed, 20 Mar 2024 10:51:13 +0200\n> Subject: [PATCH v5 21/26] move whole_page_freezable to tighter scope\n\nWorks for me.\n\n> From e2b50f9b64f7e4255f4f764e2a348e1b446573dc Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Wed, 20 Mar 2024 11:43:31 +0200\n> Subject: [PATCH v5 22/26] make 'all_visible_except_removable' local\n> \n> The caller doesn't need it, so it doesn't belong in PruneFreezeResult\n\nMakes sense to me.\n\n> From e993e0d98cd0ef1ecbd229f6ddbe23d59a427e3a Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Wed, 20 Mar 2024 11:40:34 +0200\n> Subject: [PATCH v5 26/26] reorder PruneFreezeResult fields\n> \n> ---\n> src/include/access/heapam.h | 5 ++++-\n> 1 file changed, 4 insertions(+), 1 deletion(-)\n> \n> diff --git a/src/include/access/heapam.h b/src/include/access/heapam.h\n> index ee0eca8ae02..b2015f5a1ac 100644\n> --- a/src/include/access/heapam.h\n> +++ b/src/include/access/heapam.h\n> @@ -202,14 +202,17 @@ typedef struct PruneFreezeResult\n> \tint\t\t\trecently_dead_tuples;\n> \tint\t\t\tndeleted;\t\t/* Number of tuples deleted from the page */\n> \tint\t\t\tnnewlpdead;\t\t/* Number of newly LP_DEAD items */\n> +\tint\t\t\tnfrozen;\n\nLet's add a comment after int nfrozen like\n/* Number of newly frozen tuples */\n\n> +\n> \tbool\t\tall_visible;\t/* Whether or not the page is all visible */\n> \tbool\t\thastup;\t\t\t/* Does page make rel truncation unsafe */\n> \n> +\t/* The following fields are only set if freezing */\n\nSo, all_frozen will be set correctly if we are even considering freezing\n(if pagefrz is passed). all_frozen will be true even if we didn't freeze\nanything if the page is all-frozen and can be set as such in the VM. And\nit will be false if the page is not all-frozen. So, maybe we say\n\"considering freezing\".\n\nBut, I'm glad you thought to call out which of these fields will make\nsense to the caller.\n\nAlso, maybe we should just name the members to which this applies. It is\na bit confusing that I can't tell if the comment also refers to the\nother members following it (lpdead_items and deadoffsets) -- which it\ndoesn't.\n\n> +\n> \t/* Whether or not the page can be set all frozen in the VM */\n> \tbool\t\tall_frozen;\n> \n> \t/* Number of newly frozen tuples */\n> -\tint\t\t\tnfrozen;\n> \tTransactionId frz_conflict_horizon; /* Newest xmin on the page */\n> \n> \t/* New value of relfrozenxid found by heap_page_prune_and_freeze() */\n> -- \n> 2.39.2\n> \n\n- Melanie\n\n\n",
"msg_date": "Wed, 20 Mar 2024 17:03:46 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 20/03/2024 23:03, Melanie Plageman wrote:\n> On Wed, Mar 20, 2024 at 03:15:49PM +0200, Heikki Linnakangas wrote:\n>> diff --git a/src/include/access/heapam.h b/src/include/access/heapam.h\n>> index ee0eca8ae02..b2015f5a1ac 100644\n>> --- a/src/include/access/heapam.h\n>> +++ b/src/include/access/heapam.h\n>> @@ -202,14 +202,17 @@ typedef struct PruneFreezeResult\n>> \tint\t\t\trecently_dead_tuples;\n>> \tint\t\t\tndeleted;\t\t/* Number of tuples deleted from the page */\n>> \tint\t\t\tnnewlpdead;\t\t/* Number of newly LP_DEAD items */\n>> +\tint\t\t\tnfrozen;\n> \n> Let's add a comment after int nfrozen like\n> /* Number of newly frozen tuples */\n> \n>> +\n>> \tbool\t\tall_visible;\t/* Whether or not the page is all visible */\n>> \tbool\t\thastup;\t\t\t/* Does page make rel truncation unsafe */\n>> \n>> +\t/* The following fields are only set if freezing */\n> \n> So, all_frozen will be set correctly if we are even considering freezing\n> (if pagefrz is passed). all_frozen will be true even if we didn't freeze\n> anything if the page is all-frozen and can be set as such in the VM. And\n> it will be false if the page is not all-frozen. So, maybe we say\n> \"considering freezing\".\n> \n> But, I'm glad you thought to call out which of these fields will make\n> sense to the caller.\n> \n> Also, maybe we should just name the members to which this applies. It is\n> a bit confusing that I can't tell if the comment also refers to the\n> other members following it (lpdead_items and deadoffsets) -- which it\n> doesn't.\n\nRight, sorry, I spotted the general issue that it's not clear which \nfields are valid when. I added that comment to remind about that, but I \nthen forgot about it.\n\nIn heap_page_prune_and_freeze(), we now do some extra work on each live \ntuple, to set the all_visible_except_removable correctly. And also to \nupdate live_tuples, recently_dead_tuples and hastup. When we're not \nfreezing, that's a waste of cycles, the caller doesn't care. I hope it's \nenough that it doesn't matter, but is it?\n\nThe first commit (after the WAL format changes) changes the all-visible \ncheck to use GlobalVisTestIsRemovableXid. The commit message says that \nit's because we don't have 'cutoffs' available, but we only care about \nthat when we're freezing, and when we're freezing, we actually do have \n'cutoffs' in HeapPageFreeze. Using GlobalVisTestIsRemovableXid seems \nsensible anyway, because that's what we use in \nheap_prune_satisfies_vacuum() too, but just wanted to point that out.\n\n\nThe 'frz_conflict_horizon' stuff is still fuzzy to me. (Not necessarily \nthese patches's fault). This at least is wrong, because Max(a, b) \ndoesn't handle XID wraparound correctly:\n\n> \t\t\tif (do_freeze)\n> \t\t\t\tconflict_xid = Max(prstate.snapshotConflictHorizon,\n> \t\t\t\t\t\t\t\t presult->frz_conflict_horizon);\n> \t\t\telse\n> \t\t\t\tconflict_xid = prstate.snapshotConflictHorizon;\n\nThen there's this in lazy_scan_prune():\n\n> \t\t/* Using same cutoff when setting VM is now unnecessary */\n> \t\tif (presult.all_frozen)\n> \t\t\tpresult.frz_conflict_horizon = InvalidTransactionId;\nThis does the right thing in the end, but if all the tuples are frozen \nshouldn't frz_conflict_horizon already be InvalidTransactionId? The \ncomment says it's \"newest xmin on the page\", and if everything was \nfrozen, all xmins are FrozenTransactionId. In other words, that should \nbe moved to heap_page_prune_and_freeze() so that it doesn't lie to its \ncaller. Also, frz_conflict_horizon is only set correctly if \n'all_frozen==true', would be good to mention that in the comments too.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Thu, 21 Mar 2024 15:28:48 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 20/03/2024 21:17, Melanie Plageman wrote:\n> Attached patch changes-for-0001.patch has a bunch of updated comments --\n> especially for heapam_xlog.h (including my promised diagram). And a few\n> suggestions (mostly changes that I should have made before).\n\nNew version of these WAL format changes attached. Squashed to one patch now.\n\n> +\t// TODO: should we avoid this if we only froze? heap_xlog_freeze() doesn't\n> +\t// do it\n\nAh yes, that makes sense, did that.\n\n> In the final commit message, I think it is worth calling out that all of\n> those freeze logging functions heap_log_freeze_eq/cmp/etc are lifted and\n> shifted from one file to another. When I am reviewing a big diff, it is\n> always helpful to know where I need to review line-by-line.\n\nDone.\n\n>> From 5d6fc2ffbdd839e0b69242af16446a46cf6a2dc7 Mon Sep 17 00:00:00 2001\n>> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n>> Date: Wed, 20 Mar 2024 13:49:59 +0200\n>> Subject: [PATCH v5 04/26] 'nplans' is a pointer\n>>\n>> I'm surprised the compiler didn't warn about this\n> \n> oops. while looking at this, I noticed that the asserts I added that\n> nredirected > 0, ndead > 0, and nunused > 0 have the same problem.\n\nGood catch, fixed.\n\n>> - remove xlhp_conflict_horizon and store a TransactionId directly. A\n>> separate struct would make sense if we needed to store anything else\n>> there, but for now it just seems like more code.\n> \n> makes sense. I just want to make sure heapam_xlog.h makes it extra clear\n> that this is happening. I see your comment addition. If you combine it\n> with my comment additions in the attached patch for 0001, hopefully that\n> makes it clear enough.\n\nThanks. I spent more time on the comments throughout the patch. And one \nnotable code change: I replaced the XLHP_LP_TRUNCATE_ONLY flag with \nXLHP_CLEANUP_LOCK. XLHP_CLEANUP_LOCK directly indicates if you need a \ncleanup lock to replay the record. It must always be set when \nXLHP_HAS_REDIRECTIONS or XLHP_HAS_DEAD_ITEMS is set, because replaying \nthose always needs a cleanup lock. That felt easier to document and \nunderstand than XLHP_LP_TRUNCATE_ONLY.\n\n>> From 8af186ee9dd8c7dc20f37a69b34cab7b95faa43b Mon Sep 17 00:00:00 2001\n>> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n>> Date: Wed, 20 Mar 2024 14:03:06 +0200\n>> Subject: [PATCH v5 07/26] Add comment to log_heap_prune_and_freeze().\n>>\n>> XXX: This should be rewritten, but I tried to at least list some\n>> important points.\n> \n> Are you thinking that it needs to mention more things or that the things\n> it mentions need more detail?\n\nI previously just quickly jotted down things that seemed worth \nmentioning in the comment. It was not so bad actually, but I reworded it \na little.\n\n>> From b26e36ba8614d907a6e15810ed4f684f8f628dd2 Mon Sep 17 00:00:00 2001\n>> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n>> Date: Wed, 20 Mar 2024 14:53:31 +0200\n>> Subject: [PATCH v5 08/26] minor refactoring in log_heap_prune_and_freeze()\n>>\n>> Mostly to make local variables more tightly-scoped.\n> \n> So, I don't think you can move those sub-records into the tighter scope.\n> If you run tests with this applied, you'll see it crashes and a lot of\n> the data in the record is wrong. If you move the sub-record declarations\n> out to a wider scope, the tests pass.\n> \n> The WAL record data isn't actually copied into the buffer until\n> \n> \trecptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_PRUNE_FREEZE);\n> \n> after registering everything.\n> So all of those sub-records you made are out of scope the time it tries\n> to copy from them.\n> \n> I spent the better part of a day last week trying to figure out what was\n> happening after I did the exact same thing. I must say that I found the\n> xloginsert API incredibly unhelpful on this point.\n\nOops. I had that in mind and that was actually why I moved the \nXLogRegisterData() call to the end of the function, because I found it \nconfusing to register the struct before filling it in completely, even \nthough it works perfectly fine. But then I missed it anyway when I moved \nthe local variables. I added a brief comment on that.\n\n> I would like to review the rest of the suggested changes in this patch\n> after we fix the issue I just mentioned.\n\nThanks, review is appreciated. I feel this is ready now, so barring any \nbig new issues, I plan to commit this early next week.\n\nThere is another patch in the commitfest that touches this area: \n\"Recording whether Heap2/PRUNE records are from VACUUM or from \nopportunistic pruning\" [1]. That actually goes in the opposite direction \nthan this patch. That patch wants to add more information, to show \nwhether a record was emitted by VACUUM or on-access pruning, while this \npatch makes the freezing and VACUUM's 2nd phase records also look the \nsame. We could easily add more flags to xl_heap_prune to distinguish \nthem. Or assign different xl_info code for them, like that other patch \nproposed. But I don't think that needs to block this patch, that can be \nadded as a separate patch.\n\n[1] \nhttps://www.postgresql.org/message-id/CAH2-Wzmsevhox+HJpFmQgCxWWDgNzP0R9F+VBnpOK6TgxMPrRw@mail.gmail.com\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)",
"msg_date": "Sat, 23 Mar 2024 01:09:30 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Thu, Mar 21, 2024 at 9:28 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> In heap_page_prune_and_freeze(), we now do some extra work on each live\n> tuple, to set the all_visible_except_removable correctly. And also to\n> update live_tuples, recently_dead_tuples and hastup. When we're not\n> freezing, that's a waste of cycles, the caller doesn't care. I hope it's\n> enough that it doesn't matter, but is it?\n\nLast year on an early version of the patch set I did some pgbench\ntpcb-like benchmarks -- since there is a lot of on-access pruning in\nthat workload -- and I don't remember it being a showstopper. The code\nhas changed a fair bit since then. However, I think it might be safer\nto pass a flag \"by_vacuum\" to heap_page_prune_and_freeze() and skip\nthe rest of the loop after heap_prune_satisifies_vacuum() when\non-access pruning invokes it. I had avoided that because it felt ugly\nand error-prone, however it addresses a few other of your points as\nwell.\n\nFor example, I think we should set a bit in the prune/freeze WAL\nrecord's flags to indicate if pruning was done by vacuum or on access\n(mentioned in another of your recent emails).\n\n> The first commit (after the WAL format changes) changes the all-visible\n> check to use GlobalVisTestIsRemovableXid. The commit message says that\n> it's because we don't have 'cutoffs' available, but we only care about\n> that when we're freezing, and when we're freezing, we actually do have\n> 'cutoffs' in HeapPageFreeze. Using GlobalVisTestIsRemovableXid seems\n> sensible anyway, because that's what we use in\n> heap_prune_satisfies_vacuum() too, but just wanted to point that out.\n\nYes, this is true. If we skip this part of the loop when on-access\npruning invokes it, we can go back to using the OldestXmin. I have\ndone that as well as some other changes in the attached patch,\nconflict_horizon_updates.diff. Note that this patch may not apply on\nyour latest patch as I wrote it on top of an older version. Switching\nback to using OldestXmin for page visibility determination makes this\npatch set more similar to master as well. We could keep the\nalternative check (with GlobalVisState) to maintain the illusion that\ncallers passing by_vacuum as True can pass NULL for pagefrz, but I was\nworried about the extra overhead.\n\nIt would be nice to pick a single reasonable visibility horizon (the\noldest running xid we compare things to) at the beginning of\nheap_page_prune_and_freeze() and use it for determining if we can\nremove tuples, if we can freeze tuples, and if the page is all\nvisible. It makes it confusing that we use OldestXmin for freezing and\nsetting the page visibility in the VM and GlobalVisState for\ndetermining prunability. I think using GlobalVisState for freezing has\nbeen discussed before and ruled out for a variety of reasons, and I\ndefinitely don't suggest making that change in this patch set.\n\n> The 'frz_conflict_horizon' stuff is still fuzzy to me. (Not necessarily\n> these patches's fault). This at least is wrong, because Max(a, b)\n> doesn't handle XID wraparound correctly:\n>\n> > if (do_freeze)\n> > conflict_xid = Max(prstate.snapshotConflictHorizon,\n> > presult->frz_conflict_horizon);\n> > else\n> > conflict_xid = prstate.snapshotConflictHorizon;\n>\n> Then there's this in lazy_scan_prune():\n>\n> > /* Using same cutoff when setting VM is now unnecessary */\n> > if (presult.all_frozen)\n> > presult.frz_conflict_horizon = InvalidTransactionId;\n> This does the right thing in the end, but if all the tuples are frozen\n> shouldn't frz_conflict_horizon already be InvalidTransactionId? The\n> comment says it's \"newest xmin on the page\", and if everything was\n> frozen, all xmins are FrozenTransactionId. In other words, that should\n> be moved to heap_page_prune_and_freeze() so that it doesn't lie to its\n> caller. Also, frz_conflict_horizon is only set correctly if\n> 'all_frozen==true', would be good to mention that in the comments too.\n\nYes, this is a good point. I've spent some time swapping all of this\nback into my head. I think we should change the names of all these\nconflict horizon variables and introduce some local variables again.\nIn the attached patch, I've updated the name of the variable in\nPruneFreezeResult to vm_conflict_horizon, as it is only used for\nemitting a VM update record. Now, I don't set it until the end of\nheap_page_prune_and_freeze(). It is only updated from\nInvalidTransactionId if the page is not all frozen. As you say, if the\npage is all frozen, there can be no conflict.\n\nI've also changed PruneState->snapshotConflictHorizon to\nPruneState->latest_xid_removed.\n\nAnd I introduced the local variables visibility_cutoff_xid and\nfrz_conflict_horizon. I think it is important we distinguish between\nthe latest xid pruned, the latest xmin of tuples frozen, and the\nlatest xid of all live tuples on the page.\n\nThough we end up using visibility_cutoff_xid as the freeze conflict\nhorizon if the page is all frozen, I think it is more clear to have\nthe three variables and name them what they are. Then, we calculate\nthe correct one for the combined WAL record before emitting it. I've\ndone that in the attached. I've tried to reduce the scope of the\nvariables as much as possible to keep it as clear as I could.\n\nI think I've also fixed the issue with using Max() to compare\nTransactionIds by using TransactionIdFollows() instead.\n\nNote that I still don't think we have a resolution on what to\ncorrectly update new_relfrozenxid and new_relminmxid to at the end\nwhen presult->nfrozen == 0 and presult->all_frozen is true.\n\n if (presult->nfrozen > 0)\n {\n presult->new_relfrozenxid = pagefrz->FreezePageRelfrozenXid;\n presult->new_relminmxid = pagefrz->FreezePageRelminMxid;\n }\n else\n {\n presult->new_relfrozenxid = pagefrz->NoFreezePageRelfrozenXid;\n presult->new_relminmxid = pagefrz->NoFreezePageRelminMxid;\n }\n\n- Melanie",
"msg_date": "Sun, 24 Mar 2024 12:32:46 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Sat, Mar 23, 2024 at 01:09:30AM +0200, Heikki Linnakangas wrote:\n> On 20/03/2024 21:17, Melanie Plageman wrote:\n> > Attached patch changes-for-0001.patch has a bunch of updated comments --\n> > especially for heapam_xlog.h (including my promised diagram). And a few\n> > suggestions (mostly changes that I should have made before).\n> \n> New version of these WAL format changes attached. Squashed to one patch now.\n> I spent more time on the comments throughout the patch. And one\n> notable code change: I replaced the XLHP_LP_TRUNCATE_ONLY flag with\n> XLHP_CLEANUP_LOCK. XLHP_CLEANUP_LOCK directly indicates if you need a\n> cleanup lock to replay the record. It must always be set when\n> XLHP_HAS_REDIRECTIONS or XLHP_HAS_DEAD_ITEMS is set, because replaying those\n> always needs a cleanup lock. That felt easier to document and understand\n> than XLHP_LP_TRUNCATE_ONLY.\n\nMakes sense to me.\n\n> > > From b26e36ba8614d907a6e15810ed4f684f8f628dd2 Mon Sep 17 00:00:00 2001\n> > > From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> > > Date: Wed, 20 Mar 2024 14:53:31 +0200\n> > > Subject: [PATCH v5 08/26] minor refactoring in log_heap_prune_and_freeze()\n> > > \n> > > Mostly to make local variables more tightly-scoped.\n> > \n> > So, I don't think you can move those sub-records into the tighter scope.\n> > If you run tests with this applied, you'll see it crashes and a lot of\n> > the data in the record is wrong. If you move the sub-record declarations\n> > out to a wider scope, the tests pass.\n> > \n> > The WAL record data isn't actually copied into the buffer until\n> > \n> > \trecptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_PRUNE_FREEZE);\n> > \n> > after registering everything.\n> > So all of those sub-records you made are out of scope the time it tries\n> > to copy from them.\n> > \n> > I spent the better part of a day last week trying to figure out what was\n> > happening after I did the exact same thing. I must say that I found the\n> > xloginsert API incredibly unhelpful on this point.\n> \n> Oops. I had that in mind and that was actually why I moved the\n> XLogRegisterData() call to the end of the function, because I found it\n> confusing to register the struct before filling it in completely, even\n> though it works perfectly fine. But then I missed it anyway when I moved the\n> local variables. I added a brief comment on that.\n\nComment was a good idea.\n\n> There is another patch in the commitfest that touches this area: \"Recording\n> whether Heap2/PRUNE records are from VACUUM or from opportunistic pruning\"\n> [1]. That actually goes in the opposite direction than this patch. That\n> patch wants to add more information, to show whether a record was emitted by\n> VACUUM or on-access pruning, while this patch makes the freezing and\n> VACUUM's 2nd phase records also look the same. We could easily add more\n> flags to xl_heap_prune to distinguish them. Or assign different xl_info code\n> for them, like that other patch proposed. But I don't think that needs to\n> block this patch, that can be added as a separate patch.\n> \n> [1] https://www.postgresql.org/message-id/CAH2-Wzmsevhox+HJpFmQgCxWWDgNzP0R9F+VBnpOK6TgxMPrRw@mail.gmail.com\n\nI think it would be very helpful to distinguish amongst vacuum pass 1,\n2, and on-access pruning. I often want to know what did most of the\npruning -- and I could see also wanting to know if the first or second\nvacuum pass was responsible for removing the tuples. I agree it could be\ndone separately, but it would be very helpful to have as soon as\npossible now that the record type will be the same for all three.\n\n> From 042185d3de14dcb7088bbe50e9c64e365ac42c2a Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Fri, 22 Mar 2024 23:10:22 +0200\n> Subject: [PATCH v6] Merge prune, freeze and vacuum WAL record formats\n> \n> /*\n> - * Handles XLOG_HEAP2_PRUNE record type.\n> - *\n> - * Acquires a full cleanup lock.\n> + * Replay XLOG_HEAP2_PRUNE_FREEZE record.\n> */\n> static void\n> -heap_xlog_prune(XLogReaderState *record)\n> +heap_xlog_prune_freeze(XLogReaderState *record)\n> {\n> \tXLogRecPtr\tlsn = record->EndRecPtr;\n> -\txl_heap_prune *xlrec = (xl_heap_prune *) XLogRecGetData(record);\n> +\tchar\t *ptr;\n> +\txl_heap_prune *xlrec;\n> \tBuffer\t\tbuffer;\n> \tRelFileLocator rlocator;\n> \tBlockNumber blkno;\n> \tXLogRedoAction action;\n> \n> \tXLogRecGetBlockTag(record, 0, &rlocator, NULL, &blkno);\n> +\tptr = XLogRecGetData(record);\n\nI don't love having two different pointers that alias each other and we\ndon't know which one is for what. Perhaps we could memcpy xlrec like in\nmy attached diff (log_updates.diff). It also might perform slightly\nbetter than accessing flags through a xl_heap_prune\n* -- since it wouldn't be doing pointer dereferencing.\n\n> +\txlrec = (xl_heap_prune *) ptr;\n> +\tptr += SizeOfHeapPrune;\n> \n> \t/*\n> -\t * We're about to remove tuples. In Hot Standby mode, ensure that there's\n> -\t * no queries running for which the removed tuples are still visible.\n> +\t * We will take an ordinary exclusive lock or a cleanup lock depending on\n> +\t * whether the XLHP_CLEANUP_LOCK flag is set. With an ordinary exclusive\n> +\t * lock, we better not be doing anything that requires moving existing\n> +\t * tuple data.\n> \t */\n> -\tif (InHotStandby)\n> -\t\tResolveRecoveryConflictWithSnapshot(xlrec->snapshotConflictHorizon,\n> -\t\t\t\t\t\t\t\t\t\t\txlrec->isCatalogRel,\n> +\tAssert((xlrec->flags & XLHP_CLEANUP_LOCK) != 0 ||\n> +\t\t (xlrec->flags & (XLHP_HAS_REDIRECTIONS | XLHP_HAS_DEAD_ITEMS)) == 0);\n> +\n> +\t/*\n> +\t * We are about to remove and/or freeze tuples. In Hot Standby mode,\n> +\t * ensure that there are no queries running for which the removed tuples\n> +\t * are still visible or which still consider the frozen xids as running.\n> +\t * The conflict horizon XID comes after xl_heap_prune.\n> +\t */\n> +\tif (InHotStandby && (xlrec->flags & XLHP_HAS_CONFLICT_HORIZON) != 0)\n> +\t{\n\nMy attached patch has a TODO here for the comment. It sticks out that\nthe serialization and deserialization conditions are different for the\nsnapshot conflict horizon. We don't deserialize if InHotStandby is\nfalse. That's still correct now because we don't write anything else to\nthe main data chunk afterward. But, if someone were to add another\nmember after snapshot_conflict_horizon, they would want to know to\ndeserialize snapshot_conflict_horizon first even if InHotStandby is\nfalse.\n\n> +\t\tTransactionId snapshot_conflict_horizon;\n> +\n\nI would throw a comment in about the memcpy being required because the\nsnapshot_conflict_horizon is in the buffer unaligned.\n\n> +\t\tmemcpy(&snapshot_conflict_horizon, ptr, sizeof(TransactionId));\n> +\t\tResolveRecoveryConflictWithSnapshot(snapshot_conflict_horizon,\n> +\t\t\t\t\t\t\t\t\t\t\t(xlrec->flags & XLHP_IS_CATALOG_REL) != 0,\n> \t\t\t\t\t\t\t\t\t\t\trlocator);\n> +\t}\n> \n> \t/*\n\n> +\n> +/*\n> + * Given a MAXALIGNed buffer returned by XLogRecGetBlockData() and pointed to\n> + * by cursor and any xl_heap_prune flags, deserialize the arrays of\n> + * OffsetNumbers contained in an XLOG_HEAP2_PRUNE_FREEZE record.\n> + *\n> + * This is in heapdesc.c so it can be shared between heap2_redo and heap2_desc\n> + * code, the latter of which is used in frontend (pg_waldump) code.\n> + */\n> +void\n> +heap_xlog_deserialize_prune_and_freeze(char *cursor, uint8 flags,\n> +\t\t\t\t\t\t\t\t\t int *nredirected, OffsetNumber **redirected,\n> +\t\t\t\t\t\t\t\t\t int *ndead, OffsetNumber **nowdead,\n> +\t\t\t\t\t\t\t\t\t int *nunused, OffsetNumber **nowunused,\n> +\t\t\t\t\t\t\t\t\t int *nplans, xlhp_freeze_plan **plans,\n> +\t\t\t\t\t\t\t\t\t OffsetNumber **frz_offsets)\n> +{\n> +\tif (flags & XLHP_HAS_FREEZE_PLANS)\n> +\t{\n> +\t\txlhp_freeze_plans *freeze_plans = (xlhp_freeze_plans *) cursor;\n> +\n> +\t\t*nplans = freeze_plans->nplans;\n> +\t\tAssert(*nplans > 0);\n> +\t\t*plans = freeze_plans->plans;\n> +\n> +\t\tcursor += offsetof(xlhp_freeze_plans, plans);\n> +\t\tcursor += sizeof(xlhp_freeze_plan) * *nplans;\n> +\t}\n\nI noticed you decided to set these in the else statements. Is that to\nemphasize that it is important to correctness that they be properly\ninitialized?\n\n> +\telse\n> +\t{\n> +\t\t*nplans = 0;\n> +\t\t*plans = NULL;\n> +\t}\n> +\n\nThanks again for all your work on this set!\n\n- Melanie",
"msg_date": "Sun, 24 Mar 2024 15:55:22 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 24/03/2024 21:55, Melanie Plageman wrote:\n> On Sat, Mar 23, 2024 at 01:09:30AM +0200, Heikki Linnakangas wrote:\n>> On 20/03/2024 21:17, Melanie Plageman wrote:\n>> There is another patch in the commitfest that touches this area: \"Recording\n>> whether Heap2/PRUNE records are from VACUUM or from opportunistic pruning\"\n>> [1]. That actually goes in the opposite direction than this patch. That\n>> patch wants to add more information, to show whether a record was emitted by\n>> VACUUM or on-access pruning, while this patch makes the freezing and\n>> VACUUM's 2nd phase records also look the same. We could easily add more\n>> flags to xl_heap_prune to distinguish them. Or assign different xl_info code\n>> for them, like that other patch proposed. But I don't think that needs to\n>> block this patch, that can be added as a separate patch.\n>>\n>> [1] https://www.postgresql.org/message-id/CAH2-Wzmsevhox+HJpFmQgCxWWDgNzP0R9F+VBnpOK6TgxMPrRw@mail.gmail.com\n> \n> I think it would be very helpful to distinguish amongst vacuum pass 1,\n> 2, and on-access pruning. I often want to know what did most of the\n> pruning -- and I could see also wanting to know if the first or second\n> vacuum pass was responsible for removing the tuples. I agree it could be\n> done separately, but it would be very helpful to have as soon as\n> possible now that the record type will be the same for all three.\n\nOk, I used separate 'info' codes for records generated on on-access \npruning and vacuum's 1st and 2nd pass. Similar to Peter's patch on that \nother thread, except that I didn't reserve the whole high bit for this, \nbut used three different 'info' codes. Freezing uses the same \nXLOG_HEAP2_PRUNE_VACUUM_SCAN as the pruning in vacuum's 1st pass. You \ncan distinguish them based on whether the record has nfrozen > 0, and \nwith the rest of the patches, they will be merged anyway.\n\n>> From 042185d3de14dcb7088bbe50e9c64e365ac42c2a Mon Sep 17 00:00:00 2001\n>> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n>> Date: Fri, 22 Mar 2024 23:10:22 +0200\n>> Subject: [PATCH v6] Merge prune, freeze and vacuum WAL record formats\n>> \n>> /*\n>> - * Handles XLOG_HEAP2_PRUNE record type.\n>> - *\n>> - * Acquires a full cleanup lock.\n>> + * Replay XLOG_HEAP2_PRUNE_FREEZE record.\n>> */\n>> static void\n>> -heap_xlog_prune(XLogReaderState *record)\n>> +heap_xlog_prune_freeze(XLogReaderState *record)\n>> {\n>> \tXLogRecPtr\tlsn = record->EndRecPtr;\n>> -\txl_heap_prune *xlrec = (xl_heap_prune *) XLogRecGetData(record);\n>> +\tchar\t *ptr;\n>> +\txl_heap_prune *xlrec;\n>> \tBuffer\t\tbuffer;\n>> \tRelFileLocator rlocator;\n>> \tBlockNumber blkno;\n>> \tXLogRedoAction action;\n>> \n>> \tXLogRecGetBlockTag(record, 0, &rlocator, NULL, &blkno);\n>> +\tptr = XLogRecGetData(record);\n> \n> I don't love having two different pointers that alias each other and we\n> don't know which one is for what. Perhaps we could memcpy xlrec like in\n> my attached diff (log_updates.diff). It also might perform slightly\n> better than accessing flags through a xl_heap_prune\n> * -- since it wouldn't be doing pointer dereferencing.\n\nOk.\n\n>> \t/*\n>> -\t * We're about to remove tuples. In Hot Standby mode, ensure that there's\n>> -\t * no queries running for which the removed tuples are still visible.\n>> +\t * We will take an ordinary exclusive lock or a cleanup lock depending on\n>> +\t * whether the XLHP_CLEANUP_LOCK flag is set. With an ordinary exclusive\n>> +\t * lock, we better not be doing anything that requires moving existing\n>> +\t * tuple data.\n>> \t */\n>> -\tif (InHotStandby)\n>> -\t\tResolveRecoveryConflictWithSnapshot(xlrec->snapshotConflictHorizon,\n>> -\t\t\t\t\t\t\t\t\t\t\txlrec->isCatalogRel,\n>> +\tAssert((xlrec->flags & XLHP_CLEANUP_LOCK) != 0 ||\n>> +\t\t (xlrec->flags & (XLHP_HAS_REDIRECTIONS | XLHP_HAS_DEAD_ITEMS)) == 0);\n>> +\n>> +\t/*\n>> +\t * We are about to remove and/or freeze tuples. In Hot Standby mode,\n>> +\t * ensure that there are no queries running for which the removed tuples\n>> +\t * are still visible or which still consider the frozen xids as running.\n>> +\t * The conflict horizon XID comes after xl_heap_prune.\n>> +\t */\n>> +\tif (InHotStandby && (xlrec->flags & XLHP_HAS_CONFLICT_HORIZON) != 0)\n>> +\t{\n> \n> My attached patch has a TODO here for the comment. It sticks out that\n> the serialization and deserialization conditions are different for the\n> snapshot conflict horizon. We don't deserialize if InHotStandby is\n> false. That's still correct now because we don't write anything else to\n> the main data chunk afterward. But, if someone were to add another\n> member after snapshot_conflict_horizon, they would want to know to\n> deserialize snapshot_conflict_horizon first even if InHotStandby is\n> false.\n\nGood point. Fixed so that 'snapshot_conflict_horizon' is deserialized \neven if !InHotStandby. A memcpy is cheap, and is probably optimized away \nby the compiler anyway.\n\n>> +\t\tTransactionId snapshot_conflict_horizon;\n>> +\n> \n> I would throw a comment in about the memcpy being required because the\n> snapshot_conflict_horizon is in the buffer unaligned.\n\nAdded.\n\n>> +/*\n>> + * Given a MAXALIGNed buffer returned by XLogRecGetBlockData() and pointed to\n>> + * by cursor and any xl_heap_prune flags, deserialize the arrays of\n>> + * OffsetNumbers contained in an XLOG_HEAP2_PRUNE_FREEZE record.\n>> + *\n>> + * This is in heapdesc.c so it can be shared between heap2_redo and heap2_desc\n>> + * code, the latter of which is used in frontend (pg_waldump) code.\n>> + */\n>> +void\n>> +heap_xlog_deserialize_prune_and_freeze(char *cursor, uint8 flags,\n>> +\t\t\t\t\t\t\t\t\t int *nredirected, OffsetNumber **redirected,\n>> +\t\t\t\t\t\t\t\t\t int *ndead, OffsetNumber **nowdead,\n>> +\t\t\t\t\t\t\t\t\t int *nunused, OffsetNumber **nowunused,\n>> +\t\t\t\t\t\t\t\t\t int *nplans, xlhp_freeze_plan **plans,\n>> +\t\t\t\t\t\t\t\t\t OffsetNumber **frz_offsets)\n>> +{\n>> +\tif (flags & XLHP_HAS_FREEZE_PLANS)\n>> +\t{\n>> +\t\txlhp_freeze_plans *freeze_plans = (xlhp_freeze_plans *) cursor;\n>> +\n>> +\t\t*nplans = freeze_plans->nplans;\n>> +\t\tAssert(*nplans > 0);\n>> +\t\t*plans = freeze_plans->plans;\n>> +\n>> +\t\tcursor += offsetof(xlhp_freeze_plans, plans);\n>> +\t\tcursor += sizeof(xlhp_freeze_plan) * *nplans;\n>> +\t}\n> \n> I noticed you decided to set these in the else statements. Is that to\n> emphasize that it is important to correctness that they be properly\n> initialized?\n\nThe point was to always initialize *nplans et al in the function. You \nrequired the caller to initialize them to zero, but that seems error-prone.\n\nI made one more last minute change: I changed the order of the array \narguments in heap_xlog_deserialize_prune_and_freeze() to match the order \nin log_heap_prune_and_freeze().\n\nCommitted with the above little changes. Thank you! Now, back to the \nrest of the patches :-).\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Mon, 25 Mar 2024 15:01:58 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 24/03/2024 18:32, Melanie Plageman wrote:\n> On Thu, Mar 21, 2024 at 9:28 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>>\n>> In heap_page_prune_and_freeze(), we now do some extra work on each live\n>> tuple, to set the all_visible_except_removable correctly. And also to\n>> update live_tuples, recently_dead_tuples and hastup. When we're not\n>> freezing, that's a waste of cycles, the caller doesn't care. I hope it's\n>> enough that it doesn't matter, but is it?\n> \n> Last year on an early version of the patch set I did some pgbench\n> tpcb-like benchmarks -- since there is a lot of on-access pruning in\n> that workload -- and I don't remember it being a showstopper. The code\n> has changed a fair bit since then. However, I think it might be safer\n> to pass a flag \"by_vacuum\" to heap_page_prune_and_freeze() and skip\n> the rest of the loop after heap_prune_satisifies_vacuum() when\n> on-access pruning invokes it. I had avoided that because it felt ugly\n> and error-prone, however it addresses a few other of your points as\n> well.\n\nOk. I'm not a fan of the name 'by_vacuum' though. It'd be nice if the \nargument described what it does, rather than who it's for. For example, \n'need_all_visible'. If set to true, the function determines \n'all_visible', otherwise it does not.\n\nI started to look closer at the loops in heap_prune_chain() and how they \nupdate all the various flags and counters. There's a lot going on there. \nWe have:\n\n- live_tuples counter\n- recently_dead_tuples counter\n- all_visible[_except_removable]\n- all_frozen\n- visibility_cutoff_xid\n- hastup\n- prstate.frozen array\n- nnewlpdead\n- deadoffsets array\n\nAnd that doesn't even include all the local variables and the final \ndead/redirected arrays.\n\nSome of those are set in the first loop that initializes 'htsv' for each \ntuple on the page. Others are updated in heap_prune_chain(). Some are \nupdated in both. It's hard to follow which are set where.\n\nI think recently_dead_tuples is updated incorrectly, for tuples that are \npart of a completely dead HOT chain. For example, imagine a hot chain \nwith two tuples: RECENTLY_DEAD -> DEAD. heap_prune_chain() would follow \nthe chain, see the DEAD tuple at the end of the chain, and mark both \ntuples for pruning. However, we already updated 'recently_dead_tuples' \nin the first loop, which is wrong if we remove the tuple.\n\nMaybe that's the only bug like this, but I'm a little scared. Is there \nsomething we could do to make this simpler? Maybe move all the new work \nthat we added to the first loop, into heap_prune_chain() ? Maybe \nintroduce a few more helper heap_prune_record_*() functions, to update \nthe flags and counters also for live and insert/delete-in-progress \ntuples and for dead line pointers? Something like \nheap_prune_record_live() and heap_prune_record_lp_dead().\n\n>> The 'frz_conflict_horizon' stuff is still fuzzy to me. (Not necessarily\n>> these patches's fault). This at least is wrong, because Max(a, b)\n>> doesn't handle XID wraparound correctly:\n>>\n>>> if (do_freeze)\n>>> conflict_xid = Max(prstate.snapshotConflictHorizon,\n>>> presult->frz_conflict_horizon);\n>>> else\n>>> conflict_xid = prstate.snapshotConflictHorizon;\n>>\n>> Then there's this in lazy_scan_prune():\n>>\n>>> /* Using same cutoff when setting VM is now unnecessary */\n>>> if (presult.all_frozen)\n>>> presult.frz_conflict_horizon = InvalidTransactionId;\n>> This does the right thing in the end, but if all the tuples are frozen\n>> shouldn't frz_conflict_horizon already be InvalidTransactionId? The\n>> comment says it's \"newest xmin on the page\", and if everything was\n>> frozen, all xmins are FrozenTransactionId. In other words, that should\n>> be moved to heap_page_prune_and_freeze() so that it doesn't lie to its\n>> caller. Also, frz_conflict_horizon is only set correctly if\n>> 'all_frozen==true', would be good to mention that in the comments too.\n> \n> Yes, this is a good point. I've spent some time swapping all of this\n> back into my head. I think we should change the names of all these\n> conflict horizon variables and introduce some local variables again.\n> In the attached patch, I've updated the name of the variable in\n> PruneFreezeResult to vm_conflict_horizon, as it is only used for\n> emitting a VM update record. Now, I don't set it until the end of\n> heap_page_prune_and_freeze(). It is only updated from\n> InvalidTransactionId if the page is not all frozen. As you say, if the\n> page is all frozen, there can be no conflict.\n\nMakes sense.\n\n> I've also changed PruneState->snapshotConflictHorizon to\n> PruneState->latest_xid_removed.\n> \n> And I introduced the local variables visibility_cutoff_xid and\n> frz_conflict_horizon. I think it is important we distinguish between\n> the latest xid pruned, the latest xmin of tuples frozen, and the\n> latest xid of all live tuples on the page.\n>\n> Though we end up using visibility_cutoff_xid as the freeze conflict\n> horizon if the page is all frozen, I think it is more clear to have\n> the three variables and name them what they are.\n\nAgreed.\n\n> Note that I still don't think we have a resolution on what to\n> correctly update new_relfrozenxid and new_relminmxid to at the end\n> when presult->nfrozen == 0 and presult->all_frozen is true.\n> \n> if (presult->nfrozen > 0)\n> {\n> presult->new_relfrozenxid = pagefrz->FreezePageRelfrozenXid;\n> presult->new_relminmxid = pagefrz->FreezePageRelminMxid;\n> }\n> else\n> {\n> presult->new_relfrozenxid = pagefrz->NoFreezePageRelfrozenXid;\n> presult->new_relminmxid = pagefrz->NoFreezePageRelminMxid;\n> }\n\nOne approach is to take them out of the PageFreezeResult struct again, \nand pass them as pointers:\n\nvoid\nheap_page_prune_and_freeze(Relation relation, Buffer buffer,\n\t...\n\tTransactionId *new_relfrozenxid,\n\tMultiXactId *new_relminmxid,\n\t...\n)\n\nThat would be natural for the caller too, as it wouldn't need to set up \nthe old values to HeapPageFreeze before each call, nor copy the new \nvalues to 'vacrel' after the call. I'm thinking that we'd move the \nresponsibility of setting up HeapPageFreeze to \nheap_page_prune_and_freeze(), instead of having the caller set it up. So \nthe caller would look something like this:\n\n\theap_page_prune_and_freeze(rel, buf, vacrel->vistest,\n\t &vacrel->cutoffs, &vacrel->NewRelfrozenXid, &vacrel->NewRelminMxid,\n\t &presult,\n\t PRUNE_VACUUM_SCAN, flags,\n\t &vacrel->offnum);\n\nIn this setup, heap_page_prune_and_freeze() would update \n*new_relfrozenxid and *new_relminmxid when it has a new value for them, \nand leave them unchanged otherwise.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Mon, 25 Mar 2024 21:33:38 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "Thanks for committing the new WAL format!\n\nOn Mon, Mar 25, 2024 at 3:33 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> On 24/03/2024 18:32, Melanie Plageman wrote:\n> > On Thu, Mar 21, 2024 at 9:28 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> >>\n> >> In heap_page_prune_and_freeze(), we now do some extra work on each live\n> >> tuple, to set the all_visible_except_removable correctly. And also to\n> >> update live_tuples, recently_dead_tuples and hastup. When we're not\n> >> freezing, that's a waste of cycles, the caller doesn't care. I hope it's\n> >> enough that it doesn't matter, but is it?\n> >\n> > Last year on an early version of the patch set I did some pgbench\n> > tpcb-like benchmarks -- since there is a lot of on-access pruning in\n> > that workload -- and I don't remember it being a showstopper. The code\n> > has changed a fair bit since then. However, I think it might be safer\n> > to pass a flag \"by_vacuum\" to heap_page_prune_and_freeze() and skip\n> > the rest of the loop after heap_prune_satisifies_vacuum() when\n> > on-access pruning invokes it. I had avoided that because it felt ugly\n> > and error-prone, however it addresses a few other of your points as\n> > well.\n>\n> Ok. I'm not a fan of the name 'by_vacuum' though. It'd be nice if the\n> argument described what it does, rather than who it's for. For example,\n> 'need_all_visible'. If set to true, the function determines\n> 'all_visible', otherwise it does not.\n\nI like that way of putting it -- describing what it does instead of\nwho it is for. However, we now have PruneReason as an argument to\nheap_page_prune(), which would be usable for this purpose (for\nskipping the rest of the first loop). It is not descriptive of how we\nwould use it in this scenario, though.\n\n> I started to look closer at the loops in heap_prune_chain() and how they\n> update all the various flags and counters. There's a lot going on there.\n> We have:\n>\n> - live_tuples counter\n> - recently_dead_tuples counter\n> - all_visible[_except_removable]\n> - all_frozen\n> - visibility_cutoff_xid\n> - hastup\n> - prstate.frozen array\n> - nnewlpdead\n> - deadoffsets array\n>\n> And that doesn't even include all the local variables and the final\n> dead/redirected arrays.\n\nYes, there are a lot of things happening. In an early version, I had\nhoped for the first loop to be just getting the visibility information\nand then to do most of the other stuff as we went in\nheap_prune_chain() as you mention below. I couldn't quite get a\nversion of that working that looked nice. I agree that the whole thing\nfeels a bit brittle and error-prone. It's hard to be objective after\nfiddling with something over the course of a year. I'm trying to take\na step back now and rethink it.\n\n> Some of those are set in the first loop that initializes 'htsv' for each\n> tuple on the page. Others are updated in heap_prune_chain(). Some are\n> updated in both. It's hard to follow which are set where.\n\nYep.\n\n> I think recently_dead_tuples is updated incorrectly, for tuples that are\n> part of a completely dead HOT chain. For example, imagine a hot chain\n> with two tuples: RECENTLY_DEAD -> DEAD. heap_prune_chain() would follow\n> the chain, see the DEAD tuple at the end of the chain, and mark both\n> tuples for pruning. However, we already updated 'recently_dead_tuples'\n> in the first loop, which is wrong if we remove the tuple.\n>\n> Maybe that's the only bug like this, but I'm a little scared. Is there\n> something we could do to make this simpler? Maybe move all the new work\n> that we added to the first loop, into heap_prune_chain() ? Maybe\n> introduce a few more helper heap_prune_record_*() functions, to update\n> the flags and counters also for live and insert/delete-in-progress\n> tuples and for dead line pointers? Something like\n> heap_prune_record_live() and heap_prune_record_lp_dead().\n\nI had discarded previous attempts to get everything done in\nheap_prune_chain() because it was hard to make sure I was doing the\nright thing given that it visits the line pointers out of order so\nmaking sure you've considered all of them once and only once was hard.\nI hadn't thought of the approach you suggested with record_live() --\nthat might help. I will work on this tomorrow. I had hoped to get\nsomething out today, but I am still in the middle of rebasing the back\n20 patches from your v5 over current master and then adding in the\nsuggestions that I made in the various diffs on the thread.\n\n> > Note that I still don't think we have a resolution on what to\n> > correctly update new_relfrozenxid and new_relminmxid to at the end\n> > when presult->nfrozen == 0 and presult->all_frozen is true.\n> >\n> > if (presult->nfrozen > 0)\n> > {\n> > presult->new_relfrozenxid = pagefrz->FreezePageRelfrozenXid;\n> > presult->new_relminmxid = pagefrz->FreezePageRelminMxid;\n> > }\n> > else\n> > {\n> > presult->new_relfrozenxid = pagefrz->NoFreezePageRelfrozenXid;\n> > presult->new_relminmxid = pagefrz->NoFreezePageRelminMxid;\n> > }\n>\n> One approach is to take them out of the PageFreezeResult struct again,\n> and pass them as pointers:\n>\n> void\n> heap_page_prune_and_freeze(Relation relation, Buffer buffer,\n> ...\n> TransactionId *new_relfrozenxid,\n> MultiXactId *new_relminmxid,\n> ...\n> )\n\nWhat about the question about whether or not we should be using\nFreezePageRelfrozenXid when all_frozen is true and nrfrozen == 0. I\nwas confused about whether or not we had to do this by the comment in\nHeapPageFreeze.\n\n> That would be natural for the caller too, as it wouldn't need to set up\n> the old values to HeapPageFreeze before each call, nor copy the new\n> values to 'vacrel' after the call. I'm thinking that we'd move the\n> responsibility of setting up HeapPageFreeze to\n> heap_page_prune_and_freeze(), instead of having the caller set it up. So\n> the caller would look something like this:\n>\n> heap_page_prune_and_freeze(rel, buf, vacrel->vistest,\n> &vacrel->cutoffs, &vacrel->NewRelfrozenXid, &vacrel->NewRelminMxid,\n> &presult,\n> PRUNE_VACUUM_SCAN, flags,\n> &vacrel->offnum);\n>\n> In this setup, heap_page_prune_and_freeze() would update\n> *new_relfrozenxid and *new_relminmxid when it has a new value for them,\n> and leave them unchanged otherwise.\n\nI do prefer having heap_page_prune_and_freeze() own HeapPageFreeze.\n\n- Melanie\n\n\n",
"msg_date": "Mon, 25 Mar 2024 20:28:24 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Mon, Mar 25, 2024 at 09:33:38PM +0200, Heikki Linnakangas wrote:\n> On 24/03/2024 18:32, Melanie Plageman wrote:\n> > On Thu, Mar 21, 2024 at 9:28 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> > > \n> > > In heap_page_prune_and_freeze(), we now do some extra work on each live\n> > > tuple, to set the all_visible_except_removable correctly. And also to\n> > > update live_tuples, recently_dead_tuples and hastup. When we're not\n> > > freezing, that's a waste of cycles, the caller doesn't care. I hope it's\n> > > enough that it doesn't matter, but is it?\n> > \n> > Last year on an early version of the patch set I did some pgbench\n> > tpcb-like benchmarks -- since there is a lot of on-access pruning in\n> > that workload -- and I don't remember it being a showstopper. The code\n> > has changed a fair bit since then. However, I think it might be safer\n> > to pass a flag \"by_vacuum\" to heap_page_prune_and_freeze() and skip\n> > the rest of the loop after heap_prune_satisifies_vacuum() when\n> > on-access pruning invokes it. I had avoided that because it felt ugly\n> > and error-prone, however it addresses a few other of your points as\n> > well.\n> \n> Ok. I'm not a fan of the name 'by_vacuum' though. It'd be nice if the\n> argument described what it does, rather than who it's for. For example,\n> 'need_all_visible'. If set to true, the function determines 'all_visible',\n> otherwise it does not.\n\nA very rough v7 is attached. The whole thing is rebased over master and\nthen 0016 contains an attempt at the refactor we discussed in this\nemail.\n\nInstead of just using the PruneReason to avoid doing the extra steps\nwhen on-access pruning calls heap_page_prune_and_freeze(), I've made an\n\"actions\" variable and defined different flags for it. One of them is\na replacement for the existing mark_unused_now flag. I defined another\none, PRUNE_DO_TRY_FREEZE, which could be used in place of checking if\npagefrz is NULL.\n\nThere is a whole group of activities that only the vacuum caller does\noutside of freezing -- setting hastup, counting live and recently dead\ntuples, determining whole page visibility and a snapshot conflict\nhorizon for updating the VM. But I didn't want to introduce separate\nflags for each of them, because then I would have to check each of them\nbefore taking the action. That would be lots of extra branching and\non-access pruning does none of those actions while vacuum does all of\nthem.\n\n> I started to look closer at the loops in heap_prune_chain() and how they\n> update all the various flags and counters. There's a lot going on there. We\n> have:\n> \n> - live_tuples counter\n> - recently_dead_tuples counter\n> - all_visible[_except_removable]\n> - all_frozen\n> - visibility_cutoff_xid\n> - hastup\n> - prstate.frozen array\n> - nnewlpdead\n> - deadoffsets array\n> \n> And that doesn't even include all the local variables and the final\n> dead/redirected arrays.\n> \n> Some of those are set in the first loop that initializes 'htsv' for each\n> tuple on the page. Others are updated in heap_prune_chain(). Some are\n> updated in both. It's hard to follow which are set where.\n> \n> I think recently_dead_tuples is updated incorrectly, for tuples that are\n> part of a completely dead HOT chain. For example, imagine a hot chain with\n> two tuples: RECENTLY_DEAD -> DEAD. heap_prune_chain() would follow the\n> chain, see the DEAD tuple at the end of the chain, and mark both tuples for\n> pruning. However, we already updated 'recently_dead_tuples' in the first\n> loop, which is wrong if we remove the tuple.\n\nAh, yes, you are so right about this bug.\n\n> Maybe that's the only bug like this, but I'm a little scared. Is there\n> something we could do to make this simpler? Maybe move all the new work that\n> we added to the first loop, into heap_prune_chain() ? Maybe introduce a few\n> more helper heap_prune_record_*() functions, to update the flags and\n> counters also for live and insert/delete-in-progress tuples and for dead\n> line pointers? Something like heap_prune_record_live() and\n> heap_prune_record_lp_dead().\n\nI like the idea of a heap_prune_record_live_or_recently_dead() function.\nThat's what I've attempted to implement in the attached 0016. I haven't\nupdated and cleaned up everything (especially comments) in the refactor,\nbut there are two major issues:\n\n1) In heap_prune_chain(), a heap-only tuple which is not HOT updated may\nend up being a live tuple not part of any chain or it may end up the\nredirect target in a HOT chain. At the top of heap_prune_chain(), we\nreturn if (HeapTupleHeaderIsHeapOnly(htup)). We may come back to this\ntuple later if it is part of a chain. If we don't, we need to have\ncalled heap_prune_record_live_or_recently_dead(). However, there are\nother tuples that get redirected to which do not meet this criteria, so\nwe must call heap_prune_record_live_or_recently_dead() when setting an\nitem redirected to. If we call heap_prune_record_live_or_recently_dead()\nin both places, we will double-count. To fix this, I introduced an\narray, \"counted\". But that takes up extra space in the PruneState and\nextra cycles to memset it.\n\nI can't think of a way to make sure we count the right tuples without\nanother array. The tuples we need to count are those not pointed to by\nprstate->marked + those tuples whose line pointers will be redirected to\n(those are marked).\n\n2) A large number of the members of PruneFreezeResult are only\ninitialized for the vacuum caller now. Even with a comment, this is a\nbit confusing. And, it seems like there should be some symmetry between\nthe actions the caller tells heap_page_prune_and_freeze() to take and\nthe result parameters that are filled in.\n\nI am concerned about adding all of the actions (setting hastup,\ndetermining whole page visibility, etc as mentioned above) because then\nI also have to check all the actions and that will add extra branching.\nAnd out of the two callers of heap_page_prune_and_freeze(), one will do\nall of the actions and one will do none of them except \"main\" pruning.\n\n> > Note that I still don't think we have a resolution on what to\n> > correctly update new_relfrozenxid and new_relminmxid to at the end\n> > when presult->nfrozen == 0 and presult->all_frozen is true.\n> > \n> > if (presult->nfrozen > 0)\n> > {\n> > presult->new_relfrozenxid = pagefrz->FreezePageRelfrozenXid;\n> > presult->new_relminmxid = pagefrz->FreezePageRelminMxid;\n> > }\n> > else\n> > {\n> > presult->new_relfrozenxid = pagefrz->NoFreezePageRelfrozenXid;\n> > presult->new_relminmxid = pagefrz->NoFreezePageRelminMxid;\n> > }\n> \n> One approach is to take them out of the PageFreezeResult struct again, and\n> pass them as pointers:\n> \n> void\n> heap_page_prune_and_freeze(Relation relation, Buffer buffer,\n> \t...\n> \tTransactionId *new_relfrozenxid,\n> \tMultiXactId *new_relminmxid,\n> \t...\n> )\n> \n> That would be natural for the caller too, as it wouldn't need to set up the\n> old values to HeapPageFreeze before each call, nor copy the new values to\n> 'vacrel' after the call. I'm thinking that we'd move the responsibility of\n> setting up HeapPageFreeze to heap_page_prune_and_freeze(), instead of having\n> the caller set it up. So the caller would look something like this:\n> \n> \theap_page_prune_and_freeze(rel, buf, vacrel->vistest,\n> \t &vacrel->cutoffs, &vacrel->NewRelfrozenXid, &vacrel->NewRelminMxid,\n> \t &presult,\n> \t PRUNE_VACUUM_SCAN, flags,\n> \t &vacrel->offnum);\n> \n> In this setup, heap_page_prune_and_freeze() would update *new_relfrozenxid\n> and *new_relminmxid when it has a new value for them, and leave them\n> unchanged otherwise.\n\nI've passed new_relfrozen_xid and new_relmin_mxid as arguments.\n\nBut as for only updating them when there is a new value, that doesn't\nsound cheaper than just setting them when they are passed in with the\nvalues from [No]FreezePageRelfrozenXid, [No]FreezePageRelminMxid. Unless\nyou are imagining a way to simplify the current\n[No]FreezePageRelfrozenXid, [No]FreezePageRelminMxid.\n\n- Melanie",
"msg_date": "Tue, 26 Mar 2024 17:45:59 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Tue, Mar 26, 2024 at 5:46 PM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n>\n> On Mon, Mar 25, 2024 at 09:33:38PM +0200, Heikki Linnakangas wrote:\n> > On 24/03/2024 18:32, Melanie Plageman wrote:\n> > > On Thu, Mar 21, 2024 at 9:28 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> > > >\n> > > > In heap_page_prune_and_freeze(), we now do some extra work on each live\n> > > > tuple, to set the all_visible_except_removable correctly. And also to\n> > > > update live_tuples, recently_dead_tuples and hastup. When we're not\n> > > > freezing, that's a waste of cycles, the caller doesn't care. I hope it's\n> > > > enough that it doesn't matter, but is it?\n> > >\n> > > Last year on an early version of the patch set I did some pgbench\n> > > tpcb-like benchmarks -- since there is a lot of on-access pruning in\n> > > that workload -- and I don't remember it being a showstopper. The code\n> > > has changed a fair bit since then. However, I think it might be safer\n> > > to pass a flag \"by_vacuum\" to heap_page_prune_and_freeze() and skip\n> > > the rest of the loop after heap_prune_satisifies_vacuum() when\n> > > on-access pruning invokes it. I had avoided that because it felt ugly\n> > > and error-prone, however it addresses a few other of your points as\n> > > well.\n> >\n> > Ok. I'm not a fan of the name 'by_vacuum' though. It'd be nice if the\n> > argument described what it does, rather than who it's for. For example,\n> > 'need_all_visible'. If set to true, the function determines 'all_visible',\n> > otherwise it does not.\n>\n> A very rough v7 is attached. The whole thing is rebased over master and\n> then 0016 contains an attempt at the refactor we discussed in this\n> email.\n>\n> Instead of just using the PruneReason to avoid doing the extra steps\n> when on-access pruning calls heap_page_prune_and_freeze(), I've made an\n> \"actions\" variable and defined different flags for it. One of them is\n> a replacement for the existing mark_unused_now flag. I defined another\n> one, PRUNE_DO_TRY_FREEZE, which could be used in place of checking if\n> pagefrz is NULL.\n>\n> There is a whole group of activities that only the vacuum caller does\n> outside of freezing -- setting hastup, counting live and recently dead\n> tuples, determining whole page visibility and a snapshot conflict\n> horizon for updating the VM. But I didn't want to introduce separate\n> flags for each of them, because then I would have to check each of them\n> before taking the action. That would be lots of extra branching and\n> on-access pruning does none of those actions while vacuum does all of\n> them.\n>\n> > I started to look closer at the loops in heap_prune_chain() and how they\n> > update all the various flags and counters. There's a lot going on there. We\n> > have:\n> >\n> > - live_tuples counter\n> > - recently_dead_tuples counter\n> > - all_visible[_except_removable]\n> > - all_frozen\n> > - visibility_cutoff_xid\n> > - hastup\n> > - prstate.frozen array\n> > - nnewlpdead\n> > - deadoffsets array\n> >\n> > And that doesn't even include all the local variables and the final\n> > dead/redirected arrays.\n> >\n> > Some of those are set in the first loop that initializes 'htsv' for each\n> > tuple on the page. Others are updated in heap_prune_chain(). Some are\n> > updated in both. It's hard to follow which are set where.\n> >\n> > I think recently_dead_tuples is updated incorrectly, for tuples that are\n> > part of a completely dead HOT chain. For example, imagine a hot chain with\n> > two tuples: RECENTLY_DEAD -> DEAD. heap_prune_chain() would follow the\n> > chain, see the DEAD tuple at the end of the chain, and mark both tuples for\n> > pruning. However, we already updated 'recently_dead_tuples' in the first\n> > loop, which is wrong if we remove the tuple.\n>\n> Ah, yes, you are so right about this bug.\n>\n> > Maybe that's the only bug like this, but I'm a little scared. Is there\n> > something we could do to make this simpler? Maybe move all the new work that\n> > we added to the first loop, into heap_prune_chain() ? Maybe introduce a few\n> > more helper heap_prune_record_*() functions, to update the flags and\n> > counters also for live and insert/delete-in-progress tuples and for dead\n> > line pointers? Something like heap_prune_record_live() and\n> > heap_prune_record_lp_dead().\n>\n> I like the idea of a heap_prune_record_live_or_recently_dead() function.\n> That's what I've attempted to implement in the attached 0016. I haven't\n> updated and cleaned up everything (especially comments) in the refactor,\n> but there are two major issues:\n>\n> 1) In heap_prune_chain(), a heap-only tuple which is not HOT updated may\n> end up being a live tuple not part of any chain or it may end up the\n> redirect target in a HOT chain. At the top of heap_prune_chain(), we\n> return if (HeapTupleHeaderIsHeapOnly(htup)). We may come back to this\n> tuple later if it is part of a chain. If we don't, we need to have\n> called heap_prune_record_live_or_recently_dead(). However, there are\n> other tuples that get redirected to which do not meet this criteria, so\n> we must call heap_prune_record_live_or_recently_dead() when setting an\n> item redirected to. If we call heap_prune_record_live_or_recently_dead()\n> in both places, we will double-count. To fix this, I introduced an\n> array, \"counted\". But that takes up extra space in the PruneState and\n> extra cycles to memset it.\n>\n> I can't think of a way to make sure we count the right tuples without\n> another array. The tuples we need to count are those not pointed to by\n> prstate->marked + those tuples whose line pointers will be redirected to\n> (those are marked).\n>\n> 2) A large number of the members of PruneFreezeResult are only\n> initialized for the vacuum caller now. Even with a comment, this is a\n> bit confusing. And, it seems like there should be some symmetry between\n> the actions the caller tells heap_page_prune_and_freeze() to take and\n> the result parameters that are filled in.\n>\n> I am concerned about adding all of the actions (setting hastup,\n> determining whole page visibility, etc as mentioned above) because then\n> I also have to check all the actions and that will add extra branching.\n> And out of the two callers of heap_page_prune_and_freeze(), one will do\n> all of the actions and one will do none of them except \"main\" pruning.\n\nThis morning I worked on a version of this patchset which moved the\ncounting of live and recently dead tuples and the calculation of the\nvm conflict horizon back to lazy_scan_prune() but kept the freezing\nand dead offset collection in heap_prune_chain(). I encountered the\nsame problem with ensuring each tuple was considered for freezing\nexactly once. It also made me realize that my patch set (v7) still has\nthe same problem in which all_visible_except_removable will be\nincorrectly set to false and recently dead tuples incorrectly\nincremented when encountering HEAPTUPLE_RECENTLY_DEAD tuples whose\nline pointers get set LP_DEAD during pruning. And I think I am\nincorrectly calling heap_prepare_freeze_tuple() on them too.\n\nI need some way to modify the control flow or accounting such that I\nknow which HEAPTUPLE_RECENTLY_DEAD tuples will not be marked LP_DEAD.\nAnd a way to consider freezing and do live tuple accounting for these\nand HEAPTUPLE_LIVE tuples exactly once.\n\n- Melanie\n\n\n",
"msg_date": "Wed, 27 Mar 2024 11:18:46 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 27/03/2024 17:18, Melanie Plageman wrote:\n> I need some way to modify the control flow or accounting such that I\n> know which HEAPTUPLE_RECENTLY_DEAD tuples will not be marked LP_DEAD.\n> And a way to consider freezing and do live tuple accounting for these\n> and HEAPTUPLE_LIVE tuples exactly once.\n\nJust a quick update: I've been massaging this some more today, and I \nthink I'm onto got something palatable. I'll send an updated patch later \ntoday, but the key is to note that for each item on the page, there is \none point where we determine the fate of the item, whether it's pruned \nor not. That can happen in different points in in heap_page_prune(). \nThat's also when we set marked[offnum] = true. Whenever that happens, we \nall call one of the a heap_page_prune_record_*() subroutines. We already \nhave those subroutines for when a tuple is marked as dead or unused, but \nlet's add similar subroutines for the case that we're leaving the tuple \nunchanged. If we move all the bookkeeping logic to those subroutines, we \ncan ensure that it gets done exactly once for each tuple, and at that \npoint we know what we are going to do to the tuple, so we can count it \ncorrectly. So heap_prune_chain() decides what to do with each tuple, and \nensures that each tuple is marked only once, and the subroutines update \nall the variables, add the item to the correct arrays etc. depending on \nwhat we're doing with it.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Wed, 27 Mar 2024 18:18:46 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Tue, Mar 19, 2024 at 9:36 PM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n> * \"Freeze\" NewRelfrozenXid/NewRelminMxid trackers.\n> *\n> * Trackers used when heap_freeze_execute_prepared freezes, or when there\n> * are zero freeze plans for a page. It is always valid for vacuumlazy.c\n> * to freeze any page, by definition. This even includes pages that have\n> * no tuples with storage to consider in the first place. That way the\n> * 'totally_frozen' results from heap_prepare_freeze_tuple can always be\n> * used in the same way, even when no freeze plans need to be executed to\n> * \"freeze the page\". Only the \"freeze\" path needs to consider the need\n> * to set pages all-frozen in the visibility map under this scheme.\n> *\n> * When we freeze a page, we generally freeze all XIDs < OldestXmin, only\n> * leaving behind XIDs that are ineligible for freezing, if any. And so\n> * you might wonder why these trackers are necessary at all; why should\n> * _any_ page that VACUUM freezes _ever_ be left with XIDs/MXIDs that\n> * ratchet back the top-level NewRelfrozenXid/NewRelminMxid trackers?\n> *\n> * It is useful to use a definition of \"freeze the page\" that does not\n> * overspecify how MultiXacts are affected. heap_prepare_freeze_tuple\n> * generally prefers to remove Multis eagerly, but lazy processing is used\n> * in cases where laziness allows VACUUM to avoid allocating a new Multi.\n> * The \"freeze the page\" trackers enable this flexibility.\n> */\n>\n> So, I don't really know if it is right to just check presult->nfrozen >\n> 0 when updating relminmxid. I have changed it to the way you suggested.\n> But we can change it back.\n\nI think that this is just about safe. I had to check, though. I see\nthat the FRM_NOOP case (within\nFreezeMultiXactId/heap_prepare_freeze_tuple) will ratchet back both\nsets of trackers (both the freeze and no freeze variants). However,\nit's rather hard to see that this is true.\n\nThe intent here was that cases where \"presult->nfrozen == 0\" would\nalways take the \"freeze\" path. That seems more natural to me, at\nleast, since I think of the freeze path as the default choice. By\ndefinition, lazy_scan_prune() can always take the freeze path -- even\nwhen the page has no tuples with storage. But it cannot always take\nthe no-freeze path -- \"disobeying\" pagefrz.freeze_required creates the\nrisk that relfrozenxid/relminmxid will be advanced to unsafe values at\nthe end of the VACUUM. IMV you should stick with that approach now,\neven if it is currently safe to do it the other way around.\n\n-- \nPeter Geoghegan\n\n\n",
"msg_date": "Wed, 27 Mar 2024 13:11:58 -0400",
"msg_from": "Peter Geoghegan <pg@bowt.ie>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Wed, Mar 27, 2024 at 12:18 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> On 27/03/2024 17:18, Melanie Plageman wrote:\n> > I need some way to modify the control flow or accounting such that I\n> > know which HEAPTUPLE_RECENTLY_DEAD tuples will not be marked LP_DEAD.\n> > And a way to consider freezing and do live tuple accounting for these\n> > and HEAPTUPLE_LIVE tuples exactly once.\n>\n> Just a quick update: I've been massaging this some more today, and I\n> think I'm onto got something palatable. I'll send an updated patch later\n> today, but the key is to note that for each item on the page, there is\n> one point where we determine the fate of the item, whether it's pruned\n> or not. That can happen in different points in in heap_page_prune().\n> That's also when we set marked[offnum] = true. Whenever that happens, we\n> all call one of the a heap_page_prune_record_*() subroutines. We already\n> have those subroutines for when a tuple is marked as dead or unused, but\n> let's add similar subroutines for the case that we're leaving the tuple\n> unchanged. If we move all the bookkeeping logic to those subroutines, we\n> can ensure that it gets done exactly once for each tuple, and at that\n> point we know what we are going to do to the tuple, so we can count it\n> correctly. So heap_prune_chain() decides what to do with each tuple, and\n> ensures that each tuple is marked only once, and the subroutines update\n> all the variables, add the item to the correct arrays etc. depending on\n> what we're doing with it.\n\nYes, this would be ideal.\n\nI was doing some experimentation with pageinspect today (trying to\nfind that single place where live tuples fates are decided) and it\nseems like a heap-only tuple that is not HOT-updated will usually be\nthe one at the end of the chain. Which seems like it would be covered\nby adding a record_live() type function call in the loop of\nheap_prune_chain():\n\n /*\n * If the tuple is not HOT-updated, then we are at the end of this\n * HOT-update chain.\n */\n if (!HeapTupleHeaderIsHotUpdated(htup))\n {\n heap_prune_record_live_or_recently_dead(dp, prstate,\noffnum, presult);\n break;\n }\n\nbut that doesn't end up producing the same results as\n\n if (HeapTupleHeaderIsHeapOnly(htup)\n && !HeapTupleHeaderIsHotUpdated(htup) &&\npresult->htsv[rootoffnum] == HEAPTUPLE_DEAD)\n heap_prune_record_live_or_recently_dead(dp, prstate,\noffnum, presult);\n\nat the top of heap_prune_chain().\n\n- Melanie\n\n\n",
"msg_date": "Wed, 27 Mar 2024 14:26:34 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Wed, Mar 27, 2024 at 2:26 PM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n>\n> On Wed, Mar 27, 2024 at 12:18 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> >\n> > On 27/03/2024 17:18, Melanie Plageman wrote:\n> > > I need some way to modify the control flow or accounting such that I\n> > > know which HEAPTUPLE_RECENTLY_DEAD tuples will not be marked LP_DEAD.\n> > > And a way to consider freezing and do live tuple accounting for these\n> > > and HEAPTUPLE_LIVE tuples exactly once.\n> >\n> > Just a quick update: I've been massaging this some more today, and I\n> > think I'm onto got something palatable. I'll send an updated patch later\n> > today, but the key is to note that for each item on the page, there is\n> > one point where we determine the fate of the item, whether it's pruned\n> > or not. That can happen in different points in in heap_page_prune().\n> > That's also when we set marked[offnum] = true. Whenever that happens, we\n> > all call one of the a heap_page_prune_record_*() subroutines. We already\n> > have those subroutines for when a tuple is marked as dead or unused, but\n> > let's add similar subroutines for the case that we're leaving the tuple\n> > unchanged. If we move all the bookkeeping logic to those subroutines, we\n> > can ensure that it gets done exactly once for each tuple, and at that\n> > point we know what we are going to do to the tuple, so we can count it\n> > correctly. So heap_prune_chain() decides what to do with each tuple, and\n> > ensures that each tuple is marked only once, and the subroutines update\n> > all the variables, add the item to the correct arrays etc. depending on\n> > what we're doing with it.\n>\n> Yes, this would be ideal.\n>\n> I was doing some experimentation with pageinspect today (trying to\n> find that single place where live tuples fates are decided) and it\n> seems like a heap-only tuple that is not HOT-updated will usually be\n> the one at the end of the chain. Which seems like it would be covered\n> by adding a record_live() type function call in the loop of\n> heap_prune_chain():\n>\n> /*\n> * If the tuple is not HOT-updated, then we are at the end of this\n> * HOT-update chain.\n> */\n> if (!HeapTupleHeaderIsHotUpdated(htup))\n> {\n> heap_prune_record_live_or_recently_dead(dp, prstate,\n> offnum, presult);\n> break;\n> }\n>\n> but that doesn't end up producing the same results as\n>\n> if (HeapTupleHeaderIsHeapOnly(htup)\n> && !HeapTupleHeaderIsHotUpdated(htup) &&\n> presult->htsv[rootoffnum] == HEAPTUPLE_DEAD)\n> heap_prune_record_live_or_recently_dead(dp, prstate,\n> offnum, presult);\n\nsorry, that should say presult->htsv[rootoffnum] != HEAPTUPLE_DEAD.\n\nThe latter should be a subset of the former. But instead it seems\nthere are cases I missed by doing only the former.\n\n- Melanie\n\n\n",
"msg_date": "Wed, 27 Mar 2024 14:36:46 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 27/03/2024 20:26, Melanie Plageman wrote:\n> On Wed, Mar 27, 2024 at 12:18 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>>\n>> On 27/03/2024 17:18, Melanie Plageman wrote:\n>>> I need some way to modify the control flow or accounting such that I\n>>> know which HEAPTUPLE_RECENTLY_DEAD tuples will not be marked LP_DEAD.\n>>> And a way to consider freezing and do live tuple accounting for these\n>>> and HEAPTUPLE_LIVE tuples exactly once.\n>>\n>> Just a quick update: I've been massaging this some more today, and I\n>> think I'm onto got something palatable. I'll send an updated patch later\n>> today, but the key is to note that for each item on the page, there is\n>> one point where we determine the fate of the item, whether it's pruned\n>> or not. That can happen in different points in in heap_page_prune().\n>> That's also when we set marked[offnum] = true. Whenever that happens, we\n>> all call one of the a heap_page_prune_record_*() subroutines. We already\n>> have those subroutines for when a tuple is marked as dead or unused, but\n>> let's add similar subroutines for the case that we're leaving the tuple\n>> unchanged. If we move all the bookkeeping logic to those subroutines, we\n>> can ensure that it gets done exactly once for each tuple, and at that\n>> point we know what we are going to do to the tuple, so we can count it\n>> correctly. So heap_prune_chain() decides what to do with each tuple, and\n>> ensures that each tuple is marked only once, and the subroutines update\n>> all the variables, add the item to the correct arrays etc. depending on\n>> what we're doing with it.\n> \n> Yes, this would be ideal.\n\nWell, that took me a lot longer than expected. My approach of \"make sure \nyou all the right heap_prune_record_*() subroutine in all cases didn't \nwork out quite as easily as I thought. Because, as you pointed out, it's \ndifficult to know if a non-DEAD tuple that is part of a HOT chain will \nbe visited later as part of the chain processing, or needs to be counted \nat the top of heap_prune_chain().\n\nThe solution I came up with is to add a third phase to pruning. At the \ntop of heap_prune_chain(), if we see a live heap-only tuple, and we're \nnot sure if it will be counted later as part of a HOT chain, we stash it \naway and revisit it later, after processing all the hot chains. That's \nsomewhat similar to your 'counted' array, but not quite.\n\nAttached is that approach, on top of v7. It's a bit messy, I made a \nbunch of other changes too and didn't fully separate them out to \nseparate patch. Sorry about that.\n\nOne change with this is that live_tuples and many of the other fields \nare now again updated, even if the caller doesn't need them. It was hard \nto skip them in a way that would save any cycles, with the other \nrefactorings.\n\nSome other notable changes are mentioned in the commit message.\n\n> I was doing some experimentation with pageinspect today (trying to\n> find that single place where live tuples fates are decided) and it\n> seems like a heap-only tuple that is not HOT-updated will usually be\n> the one at the end of the chain. Which seems like it would be covered\n> by adding a record_live() type function call in the loop of\n> heap_prune_chain():\n> \n> /*\n> * If the tuple is not HOT-updated, then we are at the end of this\n> * HOT-update chain.\n> */\n> if (!HeapTupleHeaderIsHotUpdated(htup))\n> {\n> heap_prune_record_live_or_recently_dead(dp, prstate,\n> offnum, presult);\n> break;\n> }\n> \n> but that doesn't end up producing the same results as\n> \n> if (HeapTupleHeaderIsHeapOnly(htup)\n> && !HeapTupleHeaderIsHotUpdated(htup) &&\n> presult->htsv[rootoffnum] == HEAPTUPLE_DEAD)\n> heap_prune_record_live_or_recently_dead(dp, prstate,\n> offnum, presult);\n> \n> at the top of heap_prune_chain().\n\nYep, this is tricky, I also spent a lot of time trying to find a good \n\"choke point\" where we could say for sure that a live tuple is processed \nexactly once, but fumbled just like you.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)",
"msg_date": "Thu, 28 Mar 2024 01:04:04 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Thu, Mar 28, 2024 at 01:04:04AM +0200, Heikki Linnakangas wrote:\n> On 27/03/2024 20:26, Melanie Plageman wrote:\n> > On Wed, Mar 27, 2024 at 12:18 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> > > \n> > > On 27/03/2024 17:18, Melanie Plageman wrote:\n> > > > I need some way to modify the control flow or accounting such that I\n> > > > know which HEAPTUPLE_RECENTLY_DEAD tuples will not be marked LP_DEAD.\n> > > > And a way to consider freezing and do live tuple accounting for these\n> > > > and HEAPTUPLE_LIVE tuples exactly once.\n> > > \n> > > Just a quick update: I've been massaging this some more today, and I\n> > > think I'm onto got something palatable. I'll send an updated patch later\n> > > today, but the key is to note that for each item on the page, there is\n> > > one point where we determine the fate of the item, whether it's pruned\n> > > or not. That can happen in different points in in heap_page_prune().\n> > > That's also when we set marked[offnum] = true. Whenever that happens, we\n> > > all call one of the a heap_page_prune_record_*() subroutines. We already\n> > > have those subroutines for when a tuple is marked as dead or unused, but\n> > > let's add similar subroutines for the case that we're leaving the tuple\n> > > unchanged. If we move all the bookkeeping logic to those subroutines, we\n> > > can ensure that it gets done exactly once for each tuple, and at that\n> > > point we know what we are going to do to the tuple, so we can count it\n> > > correctly. So heap_prune_chain() decides what to do with each tuple, and\n> > > ensures that each tuple is marked only once, and the subroutines update\n> > > all the variables, add the item to the correct arrays etc. depending on\n> > > what we're doing with it.\n> > \n> > Yes, this would be ideal.\n> \n> Well, that took me a lot longer than expected. My approach of \"make sure you\n> all the right heap_prune_record_*() subroutine in all cases didn't work out\n> quite as easily as I thought. Because, as you pointed out, it's difficult to\n> know if a non-DEAD tuple that is part of a HOT chain will be visited later\n> as part of the chain processing, or needs to be counted at the top of\n> heap_prune_chain().\n> \n> The solution I came up with is to add a third phase to pruning. At the top\n> of heap_prune_chain(), if we see a live heap-only tuple, and we're not sure\n> if it will be counted later as part of a HOT chain, we stash it away and\n> revisit it later, after processing all the hot chains. That's somewhat\n> similar to your 'counted' array, but not quite.\n\nI like this idea (the third phase). I've just started reviewing this but\nI thought I would give the initial thoughts I had inline.\n\n> One change with this is that live_tuples and many of the other fields are\n> now again updated, even if the caller doesn't need them. It was hard to skip\n> them in a way that would save any cycles, with the other refactorings.\n\nI am worried we are writing checks that are going to have to come out of\nSELECT queries' bank accounts, but I'll do some benchmarking when we're\nall done with major refactoring.\n\n> From 2f38628373ccfb6e8f8fd883955056030092569d Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Thu, 28 Mar 2024 00:16:09 +0200\n> Subject: [PATCH v8 21/22] Add comment about a pre-existing issue\n> \n> Not sure if we want to keep this, but I wanted to document it for\n> discussion at least.\n> ---\n> src/backend/access/heap/pruneheap.c | 17 +++++++++++++++++\n> 1 file changed, 17 insertions(+)\n> \n> diff --git a/src/backend/access/heap/pruneheap.c b/src/backend/access/heap/pruneheap.c\n> index e37ba655a7d..2b720ab6aa1 100644\n> --- a/src/backend/access/heap/pruneheap.c\n> +++ b/src/backend/access/heap/pruneheap.c\n> @@ -792,6 +792,23 @@ heap_prune_chain(Buffer buffer, OffsetNumber rootoffnum,\n> \t\t\t * Note that we might first arrive at a dead heap-only tuple\n> \t\t\t * either here or while following a chain below. Whichever path\n> \t\t\t * gets there first will mark the tuple unused.\n> +\t\t\t *\n> +\t\t\t * FIXME: The next paragraph isn't new with these patches, but\n> +\t\t\t * just something I realized while looking at this. But maybe we should\n> +\t\t\t * add a comment like this? Or is it too much detail?\n\nI think a comment is a good idea.\n\n> +\t\t\t *\n> +\t\t\t * Whether we arrive at the dead HOT tuple first here or while\n> +\t\t\t * following a chain below affects whether preceding RECENTLY_DEAD\n> +\t\t\t * tuples in the chain can be removed or not. Imagine that you\n> +\t\t\t * have a chain with two tuples: RECENTLY_DEAD -> DEAD. If we\n> +\t\t\t * reach the RECENTLY_DEAD tuple first, the chain-following logic\n> +\t\t\t * will find the DEAD tuple and conclude that both tuples are in\n> +\t\t\t * fact dead and can be removed. But if we reach the DEAD tuple\n> +\t\t\t * at the end of the chain first, when we reach the RECENTLY_DEAD\n> +\t\t\t * tuple later, we will not follow the chain because the DEAD\n> +\t\t\t * TUPLE is already 'marked', and will not remove the\n> +\t\t\t * RECENTLY_DEAD tuple. This is not a correctness issue, and the\n> +\t\t\t * RECENTLY_DEAD tuple will be removed by a later VACUUM.\n> \t\t\t */\n> \t\t\tif (!HeapTupleHeaderIsHotUpdated(htup))\n\nIs this intentional? Like would it be correct to remove the\nRECENTLY_DEAD tuple during the current vacuum?\n\n> From c2ee7508456d0e76de985f9997a6840450e342a8 Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Thu, 28 Mar 2024 00:45:26 +0200\n> Subject: [PATCH v8 22/22] WIP\n> \n> - Got rid of all_visible_except_removable again. We're back to the\n> roughly the same mechanism as on 'master', where the all_visible\n> doesn't include LP_DEAD items, but at the end of\n> heap_page_prune_and_freeze() when we return to the caller, we clear\n> it if there were any LP_DEAD items. I considered calling the\n> variable 'all_visible_except_lp_dead', which would be more accurate,\n> but it's also very long.\n\nnot longer than all_visible_except_removable. I would be happy to keep\nit more exact, but I'm also okay with just all_visible.\n\n> - I duplicated all the fields from PageFreezeResult to PruneState. Now\n> heap_prune_chain() and all the subroutines don't need the\n> PageFreezeResult argument, and you don't need to remember which\n> struct each field is kept in. It's all now in PruneState, and the\n> fields that the caller is interested in are copied to\n> PageFreezeResult at the end of heap_page_prune_and_freeze()\n\nyea, this makes sense to me. Makes me wonder if we shouldn't just have\nPruneFreezeResult->live_tuples/recently_dead_tuples/etc be pointers and\nthen lazy_scan_prune() can pass the actual vacrel->live_tuples counter\nand heap_page_prune_and_freeze() can increment it itself. Maybe that's\nweird though.\n\n> - Replaced the 'counted' array with 'revisit' array. I thought I could\n> get rid of it altogether, by just being careful to call the right\n> heap_prune_record_*() subroutine for each tuple in heap_prune_chain(),\n> but with live and recently-dead tuples that are part of a HOT chain,\n> we might visit the tuple as part of the HOT chain or not, depending\n> on what it's position in the chain is. So I invented a new revisit\n> phase. All live heap-only tuples that we find, that haven't already\n> been processed as part of a hot chain, are stashed away in the\n> 'revisit' array. After processing all the HOT chains, the 'revisit'\n> tuples are re-checked, and counted if they haven't already been counted.\n\nmakes sense.\n\n> - Live tuples are now also marked in the 'marked' array, when they are\n> counted. This gives a nice invariant: all tuples must be marked\n> exactly once, as part of a hot chain or otherwise. Added an\n> assertion for that.\n\nthis is a nice thing to have.\n\n> ---\n> src/backend/access/heap/pruneheap.c | 706 +++++++++++++++++----------\n> src/backend/access/heap/vacuumlazy.c | 6 +-\n> src/include/access/heapam.h | 37 +-\n> 3 files changed, 464 insertions(+), 285 deletions(-)\n> \n> diff --git a/src/backend/access/heap/pruneheap.c b/src/backend/access/heap/pruneheap.c\n> index 2b720ab6aa1..a8ed11a1858 100644\n> --- a/src/backend/access/heap/pruneheap.c\n> +++ b/src/backend/access/heap/pruneheap.c\n> \n> -static void heap_prune_record_live_or_recently_dead(Page page, PruneState *prstate,\n> -\t\t\t\t\t\t\t\t\t\t\t\t\tOffsetNumber offnum, PruneFreezeResult *presult);\n> static void page_verify_redirects(Page page);\n> \n> \n> @@ -242,6 +284,8 @@ heap_page_prune_opt(Relation relation, Buffer buffer)\n> * vistest is used to distinguish whether tuples are DEAD or RECENTLY_DEAD\n> * (see heap_prune_satisfies_vacuum).\n> *\n\nWhat's this \"cutoffs TODO\"?\n\n> + * cutoffs TODO\n> + *\n> * presult contains output parameters needed by callers such as the number of\n> * tuples removed and the number of line pointers newly marked LP_DEAD.\n> * heap_page_prune_and_freeze() is responsible for initializing it.\n> @@ -326,70 +370,63 @@ heap_page_prune_and_freeze(Relation relation, Buffer buffer,\n> \tprstate.latest_xid_removed = InvalidTransactionId;\n> \tprstate.nredirected = prstate.ndead = prstate.nunused = prstate.nfrozen = 0;\n> \tmemset(prstate.marked, 0, sizeof(prstate.marked));\n> -\tmemset(prstate.counted, 0, sizeof(prstate.counted));\n> +\tprstate.nrevisit = 0;\n> \n\n> \t\tif (presult->nfrozen > 0)\n> @@ -728,10 +832,12 @@ htsv_get_valid_status(int status)\n> * DEAD, our visibility test is just too coarse to detect it.\n> *\n> * In general, pruning must never leave behind a DEAD tuple that still has\n> - * tuple storage. VACUUM isn't prepared to deal with that case. That's why\n> + * tuple storage. VACUUM isn't prepared to deal with that case (FIXME: it no longer cares, right?).\n> + * That's why\n> * VACUUM prunes the same heap page a second time (without dropping its lock\n> * in the interim) when it sees a newly DEAD tuple that we initially saw as\n> - * in-progress. Retrying pruning like this can only happen when an inserting\n> + * in-progress (FIXME: Really? Does it still do that?).\n\nYea, I think all that is no longer true. I missed this comment back\nthen.\n\n> + * Retrying pruning like this can only happen when an inserting\n> * transaction concurrently aborts.\n> *\n> * The root line pointer is redirected to the tuple immediately after the\n> @@ -743,15 +849,18 @@ htsv_get_valid_status(int status)\n> * prstate showing the changes to be made. Items to be redirected are added\n> * to the redirected[] array (two entries per redirection); items to be set to\n> * LP_DEAD state are added to nowdead[]; and items to be set to LP_UNUSED\n> - * state are added to nowunused[].\n> - *\n> - * Returns the number of tuples (to be) deleted from the page.\n> + * state are added to nowunused[]. We perform bookkeeping of live tuples,\n> + * visibility etc. based on what the page will look like after the changes\n> + * applied. All that bookkeeping is performed in the heap_prune_record_*()\n> + * subroutines. The division of labor is that heap_prune_chain() decides the\n> + * fate of each tuple, ie. whether it's going to be removed, redirected or\n> + * left unchanged, and the heap_prune_record_*() subroutines update PruneState\n> + * based on that outcome.\n> */\n> -static int\n> +static void\n> heap_prune_chain(Buffer buffer, OffsetNumber rootoffnum,\n> -\t\t\t\t PruneState *prstate, PruneFreezeResult *presult)\n> +\t\t\t\t PruneState *prstate)\n> {\n> -\tint\t\t\tndeleted = 0;\n> \tPage\t\tdp = (Page) BufferGetPage(buffer);\n> \tTransactionId priorXmax = InvalidTransactionId;\n> \tItemId\t\trootlp;\n> @@ -794,8 +903,8 @@ heap_prune_chain(Buffer buffer, OffsetNumber rootoffnum,\n> \t\t\t * gets there first will mark the tuple unused.\n> \t\t\t *\n> \t\t\t * FIXME: The next paragraph isn't new with these patches, but\n> -\t\t\t * just something I realized while looking at this. But maybe we should\n> -\t\t\t * add a comment like this? Or is it too much detail?\n> +\t\t\t * just something I realized while looking at this. But maybe we\n> +\t\t\t * should add a comment like this? Or is it too much detail?\n\ni don't think it is too much detail.\n\n> \t\t\t *\n> \t\t\t * Whether we arrive at the dead HOT tuple first here or while\n> \t\t\t * following a chain below affects whether preceding RECENTLY_DEAD\n> @@ -809,43 +918,52 @@ heap_prune_chain(Buffer buffer, OffsetNumber rootoffnum,\n> \t\t\t * TUPLE is already 'marked', and will not remove the\n> \t\t\t * RECENTLY_DEAD tuple. This is not a correctness issue, and the\n> \t\t\t * RECENTLY_DEAD tuple will be removed by a later VACUUM.\n> +\t\t\t *\n> +\t\t\t * FIXME: Now that we have the 'revisit' array, we could stash\n> +\t\t\t * these DEAD items there too, instead of processing them here\n> +\t\t\t * immediately. That way, DEAD tuples that are still part of a\n> +\t\t\t * chain would always get processed as part of the chain.\n> \t\t\t */\n\nI really like this idea!\n\n> \t\t\tif (!HeapTupleHeaderIsHotUpdated(htup))\n> \t\t\t{\n> \t\t\t\tif (prstate->htsv[rootoffnum] == HEAPTUPLE_DEAD)\n> \t\t\t\t{\n> -\t\t\t\t\theap_prune_record_unused(prstate, rootoffnum);\n> +\t\t\t\t\theap_prune_record_unused(prstate, rootoffnum, true);\n> \t\t\t\t\tHeapTupleHeaderAdvanceConflictHorizon(htup,\n> \t\t\t\t\t\t\t\t\t\t\t\t\t\t &prstate->latest_xid_removed);\n> -\t\t\t\t\tndeleted++;\n> -\t\t\t\t}\n\nI think we could really do with some more comments with examples like\nthis in the pruning code (that go through an example series of steps).\nNot least of which because you can't see RECENTLY_DEAD in pageinspect\n(you'd have to create some kind of status for it from the different\ntuples on the page).\n\nFor example, I hadn't thought of this one:\n\nREDIRECT -> RECENTY_DEAD -> DEAD -> RECENTLY_DEAD -> DEAD\n\n> +\t/*----\n> +\t * FIXME: this helped me to visualize how different chains might look like\n> +\t * here. It's not an exhaustive list, just some examples to help with\n> +\t * thinking. Remove this comment from final version, or refine.\n> +\t *\n> +\t * REDIRECT -> LIVE (stop) -> ...\n> +\t * REDIRECT -> RECENTY_DEAD -> LIVE (stop) -> ...\n> +\t * REDIRECT -> RECENTY_DEAD -> RECENTLY_DEAD\n> +\t * REDIRECT -> RECENTY_DEAD -> DEAD\n> +\t * REDIRECT -> RECENTY_DEAD -> DEAD -> RECENTLY_DEAD -> DEAD\n> +\t * RECENTLY_DEAD -> ...\n> +\t */\n> +\n> \t/* while not end of the chain */\n> \tfor (;;)\n> \t{\n> @@ -897,19 +1015,12 @@ heap_prune_chain(Buffer buffer, OffsetNumber rootoffnum,\n> \n> \t\t\tcase HEAPTUPLE_RECENTLY_DEAD:\n> \t\t\t\trecent_dead = true;\n> -\n> -\t\t\t\t/*\n> -\t\t\t\t * This tuple may soon become DEAD. Update the hint field so\n> -\t\t\t\t * that the page is reconsidered for pruning in future.\n> -\t\t\t\t */\n> -\t\t\t\theap_prune_record_prunable(prstate,\n> -\t\t\t\t\t\t\t\t\t\t HeapTupleHeaderGetUpdateXid(htup));\n> \t\t\t\tbreak;\n> \n> \t\t\tcase HEAPTUPLE_DELETE_IN_PROGRESS:\n> -\n> -\t\t\t\t/*\n> -\t\t\t\t * This tuple may soon become DEAD. Update the hint field so\n> -\t\t\t\t * that the page is reconsidered for pruning in future.\n> -\t\t\t\t */\n> -\t\t\t\theap_prune_record_prunable(prstate,\n> -\t\t\t\t\t\t\t\t\t\t HeapTupleHeaderGetUpdateXid(htup));\n> -\t\t\t\tbreak;\n> -\n> \t\t\tcase HEAPTUPLE_LIVE:\n> \t\t\tcase HEAPTUPLE_INSERT_IN_PROGRESS:\n> -\n> -\t\t\t\t/*\n> -\t\t\t\t * If we wanted to optimize for aborts, we might consider\n> -\t\t\t\t * marking the page prunable when we see INSERT_IN_PROGRESS.\n> -\t\t\t\t * But we don't. See related decisions about when to mark the\n> -\t\t\t\t * page prunable in heapam.c.\n> -\t\t\t\t */\n> \t\t\t\tbreak;\n> \n> \t\t\tdefault:\n> @@ -981,7 +1069,18 @@ heap_prune_chain(Buffer buffer, OffsetNumber rootoffnum,\n> \t\t * RECENTLY_DEAD tuples just in case there's a DEAD one after them;\n> \t\t * but we can't advance past anything else. We have to make sure that\n> \t\t * we don't miss any DEAD tuples, since DEAD tuples that still have\n> -\t\t * tuple storage after pruning will confuse VACUUM.\n> +\t\t * tuple storage after pruning will confuse VACUUM (FIXME: not anymore\n> +\t\t * I think?).\n\nMeaning, it won't confuse vacuum anymore or there won't be DEAD tuples\nwith storage after pruning anymore?\n\n> +\t\t *\n> +\t\t * FIXME: Not a new issue, but spotted it now : If there is a chain\n> +\t\t * like RECENTLY_DEAD -> DEAD, we will remove both tuples, but will\n> +\t\t * not call HeapTupleHeaderAdvanceConflictHorizon() for the\n> +\t\t * RECENTLY_DEAD tuple. Is that OK? I think it is. In a HOT chain,\n> +\t\t * we know that the later tuple committed before any earlier tuples in\n> +\t\t * the chain, therefore it ought to be enough to set the conflict\n> +\t\t * horizon based on the later tuple. If all snapshots on the standby\n> +\t\t * see the deleter of the last tuple as committed, they must consider\n> +\t\t * all the earlier ones as committed too.\n> \t\t */\n\nThis makes sense to me. (that if all the snapshots on the standby see\nthe deleter of the last tuple as committed, then they consider the\nearlier ones deleted too). Probably wouldn't hurt to call this out here\nthough.\n\n> @@ -1206,15 +1318,6 @@ heap_prune_record_live_or_recently_dead(Page page, PruneState *prstate, OffsetNu\n> \t * can't run inside a transaction block, which makes some cases impossible\n> \t * (e.g. in-progress insert from the same transaction).\n> \t *\n> -\t * We treat LP_DEAD items (which are the closest thing to DEAD tuples that\n> -\t * might be seen here) differently, too: we assume that they'll become\n> -\t * LP_UNUSED before VACUUM finishes. This difference is only superficial.\n> -\t * VACUUM effectively agrees with ANALYZE about DEAD items, in the end.\n> -\t * VACUUM won't remember LP_DEAD items, but only because they're not\n> -\t * supposed to be left behind when it is done. (Cases where we bypass\n> -\t * index vacuuming will violate this optimistic assumption, but the\n> -\t * overall impact of that should be negligible.)\n> -\t *\n> \t * HEAPTUPLE_LIVE tuples are naturally counted as live. This is also what\n> \t * acquire_sample_rows() does.\n> \t *\n> @@ -1224,10 +1327,21 @@ heap_prune_record_live_or_recently_dead(Page page, PruneState *prstate, OffsetNu\n> \t * ensure the math works out. The assumption that the transaction will\n> \t * commit and update the counters after we report is a bit shaky; but it\n> \t * is what acquire_sample_rows() does, so we do the same to be consistent.\n> +\t *\n> +\t * HEAPTUPLE_DEAD are handled by the other heap_prune_record_*()\n> +\t * subroutines. They don't count dead items like acquire_sample_rows()\n> +\t * does, because we assume that all dead items will become LP_UNUSED\n> +\t * before VACUUM finishes. This difference is only superficial. VACUUM\n> +\t * effectively agrees with ANALYZE about DEAD items, in the end. VACUUM\n> +\t * won't remember LP_DEAD items, but only because they're not supposed to\n> +\t * be left behind when it is done. (Cases where we bypass index vacuuming\n> +\t * will violate this optimistic assumption, but the overall impact of that\n> +\t * should be negligible.) FIXME: I don't understand that last sentence in\n> +\t * parens. It was copied from elsewhere.\n\nIf we bypass index vacuuming, there will be LP_DEAD items left behind\nwhen we are done because we didn't do index vacuuming and then reaping\nof those dead items. All of these comments are kind of a copypasta,\nthough.\n\n> \t */\n> \thtup = (HeapTupleHeader) PageGetItem(page, PageGetItemId(page, offnum));\n> \n> -\tswitch (status)\n\nOkay, that's all for now. I'll do more in-depth review tomorrow.\n\n- Melanie\n\n\n",
"msg_date": "Wed, 27 Mar 2024 21:53:26 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 28/03/2024 03:53, Melanie Plageman wrote:\n> On Thu, Mar 28, 2024 at 01:04:04AM +0200, Heikki Linnakangas wrote:\n>> One change with this is that live_tuples and many of the other fields are\n>> now again updated, even if the caller doesn't need them. It was hard to skip\n>> them in a way that would save any cycles, with the other refactorings.\n> \n> I am worried we are writing checks that are going to have to come out of\n> SELECT queries' bank accounts, but I'll do some benchmarking when we're\n> all done with major refactoring.\n\nSounds good, thanks.\n\n>> +\t\t\t *\n>> +\t\t\t * Whether we arrive at the dead HOT tuple first here or while\n>> +\t\t\t * following a chain below affects whether preceding RECENTLY_DEAD\n>> +\t\t\t * tuples in the chain can be removed or not. Imagine that you\n>> +\t\t\t * have a chain with two tuples: RECENTLY_DEAD -> DEAD. If we\n>> +\t\t\t * reach the RECENTLY_DEAD tuple first, the chain-following logic\n>> +\t\t\t * will find the DEAD tuple and conclude that both tuples are in\n>> +\t\t\t * fact dead and can be removed. But if we reach the DEAD tuple\n>> +\t\t\t * at the end of the chain first, when we reach the RECENTLY_DEAD\n>> +\t\t\t * tuple later, we will not follow the chain because the DEAD\n>> +\t\t\t * TUPLE is already 'marked', and will not remove the\n>> +\t\t\t * RECENTLY_DEAD tuple. This is not a correctness issue, and the\n>> +\t\t\t * RECENTLY_DEAD tuple will be removed by a later VACUUM.\n>> \t\t\t */\n>> \t\t\tif (!HeapTupleHeaderIsHotUpdated(htup))\n> \n> Is this intentional? Like would it be correct to remove the\n> RECENTLY_DEAD tuple during the current vacuum?\n\nYes, it would be correct. And if we happen to visit the items in \ndifferent order, the RECENTLY_DEAD tuple first, it will get removed.\n\n(This is just based on me reading the code, I'm not sure if I've missed \nsomething. Would be nice to construct a test case for that and step \nthrough it with a debugger to really see what happens. But this is not a \nnew issue, doesn't need to be part of this patch)\n\n>> From c2ee7508456d0e76de985f9997a6840450e342a8 Mon Sep 17 00:00:00 2001\n>> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n>> Date: Thu, 28 Mar 2024 00:45:26 +0200\n>> Subject: [PATCH v8 22/22] WIP\n>>\n>> - Got rid of all_visible_except_removable again. We're back to the\n>> roughly the same mechanism as on 'master', where the all_visible\n>> doesn't include LP_DEAD items, but at the end of\n>> heap_page_prune_and_freeze() when we return to the caller, we clear\n>> it if there were any LP_DEAD items. I considered calling the\n>> variable 'all_visible_except_lp_dead', which would be more accurate,\n>> but it's also very long.\n> \n> not longer than all_visible_except_removable. I would be happy to keep\n> it more exact, but I'm also okay with just all_visible.\n\nOk, let's make it 'all_visible_except_lp_dead' for clarity.\n\n> What's this \"cutoffs TODO\"?\n> \n>> + * cutoffs TODO\n>> + *\n>> * presult contains output parameters needed by callers such as the number of\n>> * tuples removed and the number of line pointers newly marked LP_DEAD.\n>> * heap_page_prune_and_freeze() is responsible for initializing it.\n\nAll the other arguments are documented in the comment, except 'cutoffs'.\n\n>> @@ -728,10 +832,12 @@ htsv_get_valid_status(int status)\n>> * DEAD, our visibility test is just too coarse to detect it.\n>> *\n>> * In general, pruning must never leave behind a DEAD tuple that still has\n>> - * tuple storage. VACUUM isn't prepared to deal with that case. That's why\n>> + * tuple storage. VACUUM isn't prepared to deal with that case (FIXME: it no longer cares, right?).\n>> + * That's why\n>> * VACUUM prunes the same heap page a second time (without dropping its lock\n>> * in the interim) when it sees a newly DEAD tuple that we initially saw as\n>> - * in-progress. Retrying pruning like this can only happen when an inserting\n>> + * in-progress (FIXME: Really? Does it still do that?).\n> \n> Yea, I think all that is no longer true. I missed this comment back\n> then.\n\nCommitted a patch to remove it.\n\n>> @@ -981,7 +1069,18 @@ heap_prune_chain(Buffer buffer, OffsetNumber rootoffnum,\n>> \t\t * RECENTLY_DEAD tuples just in case there's a DEAD one after them;\n>> \t\t * but we can't advance past anything else. We have to make sure that\n>> \t\t * we don't miss any DEAD tuples, since DEAD tuples that still have\n>> -\t\t * tuple storage after pruning will confuse VACUUM.\n>> +\t\t * tuple storage after pruning will confuse VACUUM (FIXME: not anymore\n>> +\t\t * I think?).\n> \n> Meaning, it won't confuse vacuum anymore or there won't be DEAD tuples\n> with storage after pruning anymore?\n\nI meant that it won't confuse VACUUM anymore. lazy_scan_prune() doesn't \nloop through the items on the page checking their visibility anymore.\n\nHmm, one confusion remains though: In the 2nd phase of vacuum, we remove \nall the dead line pointers that we have now removed from the indexes. \nWhen we do that, we assume them all to be dead line pointers, without \nstorage, rather than normal tuples that happen to be HEAPTUPLE_DEAD. So \nit's important that if pruning would leave behind HEAPTUPLE_DEAD tuples, \nthey are not included in 'deadoffsets'.\n\nIn any case, let's just make sure that pruning doesn't leave \nHEAPTUPLE_DEAD tuples. There's no reason it should.\n\n\n>> @@ -1224,10 +1327,21 @@ heap_prune_record_live_or_recently_dead(Page page, PruneState *prstate, OffsetNu\n>> \t * ensure the math works out. The assumption that the transaction will\n>> \t * commit and update the counters after we report is a bit shaky; but it\n>> \t * is what acquire_sample_rows() does, so we do the same to be consistent.\n>> +\t *\n>> +\t * HEAPTUPLE_DEAD are handled by the other heap_prune_record_*()\n>> +\t * subroutines. They don't count dead items like acquire_sample_rows()\n>> +\t * does, because we assume that all dead items will become LP_UNUSED\n>> +\t * before VACUUM finishes. This difference is only superficial. VACUUM\n>> +\t * effectively agrees with ANALYZE about DEAD items, in the end. VACUUM\n>> +\t * won't remember LP_DEAD items, but only because they're not supposed to\n>> +\t * be left behind when it is done. (Cases where we bypass index vacuuming\n>> +\t * will violate this optimistic assumption, but the overall impact of that\n>> +\t * should be negligible.) FIXME: I don't understand that last sentence in\n>> +\t * parens. It was copied from elsewhere.\n> \n> If we bypass index vacuuming, there will be LP_DEAD items left behind\n> when we are done because we didn't do index vacuuming and then reaping\n> of those dead items. All of these comments are kind of a copypasta,\n> though.\n\nAh, gotcha, makes sense now. I didn't remember that we sometimes by pass \nindex vacuuming if there are very few dead items. I thought this talked \nabout the case that there are no indexes, but that case is OK.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Thu, 28 Mar 2024 10:49:41 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Thu, Mar 28, 2024 at 4:49 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> On 28/03/2024 03:53, Melanie Plageman wrote:\n> > On Thu, Mar 28, 2024 at 01:04:04AM +0200, Heikki Linnakangas wrote:\n> >> One change with this is that live_tuples and many of the other fields are\n> >> now again updated, even if the caller doesn't need them. It was hard to skip\n> >> them in a way that would save any cycles, with the other refactorings.\n> >\n> > I am worried we are writing checks that are going to have to come out of\n> > SELECT queries' bank accounts, but I'll do some benchmarking when we're\n> > all done with major refactoring.\n>\n> Sounds good, thanks.\n\nActually, after having looked at it again, there really are only a few\nmore increments of various counters, the memory consumed by revisit,\nand the additional setting of offsets in marked. I think a few\ncarefully constructed queries which do on-access pruning could test\nthe impact of this (as opposed to a bigger benchmarking endeavor).\n\nI also wonder if there would be any actual impact of marking the\nvarious record_*() routines inline.\n\n> >> @@ -728,10 +832,12 @@ htsv_get_valid_status(int status)\n> >> * DEAD, our visibility test is just too coarse to detect it.\n> >> *\n> >> * In general, pruning must never leave behind a DEAD tuple that still has\n> >> - * tuple storage. VACUUM isn't prepared to deal with that case. That's why\n> >> + * tuple storage. VACUUM isn't prepared to deal with that case (FIXME: it no longer cares, right?).\n> >> + * That's why\n> >> * VACUUM prunes the same heap page a second time (without dropping its lock\n> >> * in the interim) when it sees a newly DEAD tuple that we initially saw as\n> >> - * in-progress. Retrying pruning like this can only happen when an inserting\n> >> + * in-progress (FIXME: Really? Does it still do that?).\n> >\n> > Yea, I think all that is no longer true. I missed this comment back\n> > then.\n>\n> Committed a patch to remove it.\n>\n> >> @@ -981,7 +1069,18 @@ heap_prune_chain(Buffer buffer, OffsetNumber rootoffnum,\n> >> * RECENTLY_DEAD tuples just in case there's a DEAD one after them;\n> >> * but we can't advance past anything else. We have to make sure that\n> >> * we don't miss any DEAD tuples, since DEAD tuples that still have\n> >> - * tuple storage after pruning will confuse VACUUM.\n> >> + * tuple storage after pruning will confuse VACUUM (FIXME: not anymore\n> >> + * I think?).\n> >\n> > Meaning, it won't confuse vacuum anymore or there won't be DEAD tuples\n> > with storage after pruning anymore?\n>\n> I meant that it won't confuse VACUUM anymore. lazy_scan_prune() doesn't\n> loop through the items on the page checking their visibility anymore.\n>\n> Hmm, one confusion remains though: In the 2nd phase of vacuum, we remove\n> all the dead line pointers that we have now removed from the indexes.\n> When we do that, we assume them all to be dead line pointers, without\n> storage, rather than normal tuples that happen to be HEAPTUPLE_DEAD. So\n> it's important that if pruning would leave behind HEAPTUPLE_DEAD tuples,\n> they are not included in 'deadoffsets'.\n\nIt seems like master only adds items it is marking LP_DEAD to\ndeadoffsets. And things marked LP_DEAD have lp_len set to 0.\n\n> In any case, let's just make sure that pruning doesn't leave\n> HEAPTUPLE_DEAD tuples. There's no reason it should.\n\nMaybe worth adding an assert to\n\nstatic void\nheap_prune_record_unchanged_lp_dead(ItemId itemid, PruneState\n*prstate, OffsetNumber offnum)\n{\n...\n Assert(!ItemIdHasStorage(itemid));\n prstate->deadoffsets[prstate->lpdead_items++] = offnum;\n}\n\nBy the way, I wasn't quite sure about the purpose of\nheap_prune_record_unchanged_lp_dead(). It is called in\nheap_prune_chain() in a place where we didn't add things to\ndeadoffsets before, no?\n\n /*\n * Likewise, a dead line pointer can't be part of the chain. (We\n * already eliminated the case of dead root tuple outside this\n * function.)\n */\n if (ItemIdIsDead(lp))\n {\n /*\n * If the caller set PRUNE_DO_MARK_UNUSED_NOW, we can set dead\n * line pointers LP_UNUSED now.\n */\n if (unlikely(prstate->actions & PRUNE_DO_MARK_UNUSED_NOW))\n heap_prune_record_unused(prstate, offnum, false);\n else\n heap_prune_record_unchanged_lp_dead(lp, prstate, offnum);\n break;\n }\n\n> >> @@ -1224,10 +1327,21 @@ heap_prune_record_live_or_recently_dead(Page page, PruneState *prstate, OffsetNu\n> >> * ensure the math works out. The assumption that the transaction will\n> >> * commit and update the counters after we report is a bit shaky; but it\n> >> * is what acquire_sample_rows() does, so we do the same to be consistent.\n> >> + *\n> >> + * HEAPTUPLE_DEAD are handled by the other heap_prune_record_*()\n> >> + * subroutines. They don't count dead items like acquire_sample_rows()\n> >> + * does, because we assume that all dead items will become LP_UNUSED\n> >> + * before VACUUM finishes. This difference is only superficial. VACUUM\n> >> + * effectively agrees with ANALYZE about DEAD items, in the end. VACUUM\n> >> + * won't remember LP_DEAD items, but only because they're not supposed to\n> >> + * be left behind when it is done. (Cases where we bypass index vacuuming\n> >> + * will violate this optimistic assumption, but the overall impact of that\n> >> + * should be negligible.) FIXME: I don't understand that last sentence in\n> >> + * parens. It was copied from elsewhere.\n> >\n> > If we bypass index vacuuming, there will be LP_DEAD items left behind\n> > when we are done because we didn't do index vacuuming and then reaping\n> > of those dead items. All of these comments are kind of a copypasta,\n> > though.\n>\n> Ah, gotcha, makes sense now. I didn't remember that we sometimes by pass\n> index vacuuming if there are very few dead items. I thought this talked\n> about the case that there are no indexes, but that case is OK.\n\nThese comments could use another pass. I had added some extra\n(probably redundant) content when I thought I was refactoring it a\ncertain way and then changed my mind.\n\nAttached is a diff with some ideas I had for a bit of code simplification.\n\nAre you working on cleaning this patch up or should I pick it up?\n\nI wonder if it makes sense to move some of the changes to\nheap_prune_chain() with setting things in marked/revisited to the\nstart of the patch set (to be committed first).\n\n- Melanie",
"msg_date": "Thu, 28 Mar 2024 11:07:10 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Thu, Mar 28, 2024 at 11:07:10AM -0400, Melanie Plageman wrote:\n> These comments could use another pass. I had added some extra\n> (probably redundant) content when I thought I was refactoring it a\n> certain way and then changed my mind.\n> \n> Attached is a diff with some ideas I had for a bit of code simplification.\n> \n> Are you working on cleaning this patch up or should I pick it up?\n\nAttached v9 is rebased over master. But, more importantly, I took\nanother pass at heap_prune_chain() and am pretty happy with what I came\nup with. See 0021. I simplified the traversal logic and then grouped the\nchain processing into three branches at the end. I find it much easier\nto understand what we are doing for different types of HOT chains.\n\nI got rid of revisited. We can put it back, but I was thinking: we stash\nall HOT tuples and then loop over them later, calling record_unchanged()\non the ones that aren't marked. But, if we have a lot of HOT tuples, is\nthis really that much better than just looping through all the offsets\nand calling record_unchanged() on just the ones that aren't marked?\n\nI've done that in my version. While testing this, I found that only\non-access pruning needed this final loop calling record_unchanged() on\nitems not yet marked. I know we can't skip this final loop entirely in\nthe ON ACCESS case because it calls record_prunable(), but we could\nconsider moving that back out into heap_prune_chain()? Or what do you\nthink?\n\nI haven't finished updating all the comments, but I am really interested\nto know what you think about heap_prune_chain() now.\n\nNote that patches 0001-0020 are still the same as before. Only 0021 is\nthe new changes I made (they are built on top of your v8 0022).\n\nTomorrow I will start first thing figuring out how to break this down\ninto parts that can apply on master and then rebase the rest of the\npatches on top of it.\n\n- Melanie",
"msg_date": "Fri, 29 Mar 2024 01:04:52 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 29/03/2024 07:04, Melanie Plageman wrote:\n> On Thu, Mar 28, 2024 at 11:07:10AM -0400, Melanie Plageman wrote:\n>> These comments could use another pass. I had added some extra\n>> (probably redundant) content when I thought I was refactoring it a\n>> certain way and then changed my mind.\n>>\n>> Attached is a diff with some ideas I had for a bit of code simplification.\n>>\n>> Are you working on cleaning this patch up or should I pick it up?\n> \n> Attached v9 is rebased over master. But, more importantly, I took\n> another pass at heap_prune_chain() and am pretty happy with what I came\n> up with. See 0021. I simplified the traversal logic and then grouped the\n> chain processing into three branches at the end. I find it much easier\n> to understand what we are doing for different types of HOT chains.\n\nAh yes, agreed, that's nicer.\n\nThe 'survivor' variable is a little confusing, especially here:\n\n\tif (!survivor)\n\t{\n\t\tint\t\t\ti;\n\n\t\t/*\n\t\t * If no DEAD tuple was found, and the root is redirected, mark it as\n\t\t * such.\n\t\t */\n\t\tif ((i = ItemIdIsRedirected(rootlp)))\n\t\t\theap_prune_record_unchanged_lp_redirect(prstate, rootoffnum);\n\n\t\t/* the rest of tuples in the chain are normal, unchanged tuples */\n\t\tfor (; i < nchain; i++)\n\t\t\theap_prune_record_unchanged(dp, prstate, chainitems[i]);\n\t}\n\nYou would think that \"if(!survivor)\", it means that there is no live \ntuples on the chain, i.e. no survivors. But in fact it's the opposite; \nit means that the are all live. Maybe call it 'ndeadchain' instead, \nmeaning the number of dead items in the chain.\n\n> I got rid of revisited. We can put it back, but I was thinking: we stash\n> all HOT tuples and then loop over them later, calling record_unchanged()\n> on the ones that aren't marked. But, if we have a lot of HOT tuples, is\n> this really that much better than just looping through all the offsets\n> and calling record_unchanged() on just the ones that aren't marked?\n\nWell, it requires looping through all the offsets one more time, and \nunless you have a lot of HOT tuples, most items would be marked already. \nBut maybe the overhead is negligible anyway.\n\n> I've done that in my version. While testing this, I found that only\n> on-access pruning needed this final loop calling record_unchanged() on\n> items not yet marked. I know we can't skip this final loop entirely in\n> the ON ACCESS case because it calls record_prunable(), but we could\n> consider moving that back out into heap_prune_chain()? Or what do you\n> think?\n\nHmm, why is that different with on-access pruning?\n\nHere's another idea: In the first loop through the offsets, where we \ngather the HTSV status of each item, also collect the offsets of all HOT \nand non-HOT items to two separate arrays. Call heap_prune_chain() for \nall the non-HOT items first, and then process any remaining HOT tuples \nthat haven't been marked yet.\n\n> I haven't finished updating all the comments, but I am really interested\n> to know what you think about heap_prune_chain() now.\n\nLooks much better now, thanks!\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Fri, 29 Mar 2024 18:00:28 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Fri, Mar 29, 2024 at 12:00 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> On 29/03/2024 07:04, Melanie Plageman wrote:\n> > On Thu, Mar 28, 2024 at 11:07:10AM -0400, Melanie Plageman wrote:\n> >> These comments could use another pass. I had added some extra\n> >> (probably redundant) content when I thought I was refactoring it a\n> >> certain way and then changed my mind.\n> >>\n> >> Attached is a diff with some ideas I had for a bit of code simplification.\n> >>\n> >> Are you working on cleaning this patch up or should I pick it up?\n> >\n> > Attached v9 is rebased over master. But, more importantly, I took\n> > another pass at heap_prune_chain() and am pretty happy with what I came\n> > up with. See 0021. I simplified the traversal logic and then grouped the\n> > chain processing into three branches at the end. I find it much easier\n> > to understand what we are doing for different types of HOT chains.\n>\n> Ah yes, agreed, that's nicer.\n>\n> The 'survivor' variable is a little confusing, especially here:\n>\n> if (!survivor)\n> {\n> int i;\n>\n> /*\n> * If no DEAD tuple was found, and the root is redirected, mark it as\n> * such.\n> */\n> if ((i = ItemIdIsRedirected(rootlp)))\n> heap_prune_record_unchanged_lp_redirect(prstate, rootoffnum);\n>\n> /* the rest of tuples in the chain are normal, unchanged tuples */\n> for (; i < nchain; i++)\n> heap_prune_record_unchanged(dp, prstate, chainitems[i]);\n> }\n>\n> You would think that \"if(!survivor)\", it means that there is no live\n> tuples on the chain, i.e. no survivors. But in fact it's the opposite;\n> it means that the are all live. Maybe call it 'ndeadchain' instead,\n> meaning the number of dead items in the chain.\n\nMakes sense.\n\n> > I've done that in my version. While testing this, I found that only\n> > on-access pruning needed this final loop calling record_unchanged() on\n> > items not yet marked. I know we can't skip this final loop entirely in\n> > the ON ACCESS case because it calls record_prunable(), but we could\n> > consider moving that back out into heap_prune_chain()? Or what do you\n> > think?\n>\n> Hmm, why is that different with on-access pruning?\n\nWell, it is highly possible we just don't hit cases like this with\nvacuum in our test suite (not that it is unreachable by vacuum).\n\nIt's just very easy to get in this situation with on-access pruning.\nImagine an UPDATE which caused the following chain:\n\nRECENTLY_DEAD -> DELETE_IN_PROGRESS -> INSERT_IN_PROGRESS\n\nIt invokes heap_page_prune_and_freeze() (assume the page meets the\ncriteria for on-access pruning) and eventually enters\nheap_prune_chain() with the first offset in this chain.\n\nThe first item is LP_NORMAL and the tuple is RECENTLY_DEAD, so the\nsurvivor variable stays 0 and we record_unchanged() for that tuple and\nreturn. The next two items are LP_NORMAL and the tuples are HOT\ntuples, so we just return from the \"fast path\" at the top of\nheap_prune_chain(). After invoking heap_prune_chain() for all of them,\nthe first offset is marked but the other two are not. Thus, we end up\nhaving to record_unchanged() later. This kind of thing is a super\ncommon case that we see all the time in queries in the regression test\nsuite.\n\n> Here's another idea: In the first loop through the offsets, where we\n> gather the HTSV status of each item, also collect the offsets of all HOT\n> and non-HOT items to two separate arrays. Call heap_prune_chain() for\n> all the non-HOT items first, and then process any remaining HOT tuples\n> that haven't been marked yet.\n\nThat's an interesting idea. I'll try it out and see how it works.\n\n> > I haven't finished updating all the comments, but I am really interested\n> > to know what you think about heap_prune_chain() now.\n>\n> Looks much better now, thanks!\n\nI am currently doing chain traversal refactoring in heap_prune_chain()\non top of master as the first patch in the set.\n\n- Melanie\n\n\n",
"msg_date": "Fri, 29 Mar 2024 12:32:21 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Fri, Mar 29, 2024 at 12:32:21PM -0400, Melanie Plageman wrote:\n> On Fri, Mar 29, 2024 at 12:00 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> >\n> > On 29/03/2024 07:04, Melanie Plageman wrote:\n> > > On Thu, Mar 28, 2024 at 11:07:10AM -0400, Melanie Plageman wrote:\n> > >> These comments could use another pass. I had added some extra\n> > >> (probably redundant) content when I thought I was refactoring it a\n> > >> certain way and then changed my mind.\n> > >>\n> > >> Attached is a diff with some ideas I had for a bit of code simplification.\n> > >>\n> > >> Are you working on cleaning this patch up or should I pick it up?\n> > >\n> > > Attached v9 is rebased over master. But, more importantly, I took\n> > > another pass at heap_prune_chain() and am pretty happy with what I came\n> > > up with. See 0021. I simplified the traversal logic and then grouped the\n> > > chain processing into three branches at the end. I find it much easier\n> > > to understand what we are doing for different types of HOT chains.\n> >\n> > Ah yes, agreed, that's nicer.\n> >\n> > The 'survivor' variable is a little confusing, especially here:\n> >\n> > if (!survivor)\n> > {\n> > int i;\n> >\n> > /*\n> > * If no DEAD tuple was found, and the root is redirected, mark it as\n> > * such.\n> > */\n> > if ((i = ItemIdIsRedirected(rootlp)))\n> > heap_prune_record_unchanged_lp_redirect(prstate, rootoffnum);\n> >\n> > /* the rest of tuples in the chain are normal, unchanged tuples */\n> > for (; i < nchain; i++)\n> > heap_prune_record_unchanged(dp, prstate, chainitems[i]);\n> > }\n> >\n> > You would think that \"if(!survivor)\", it means that there is no live\n> > tuples on the chain, i.e. no survivors. But in fact it's the opposite;\n> > it means that the are all live. Maybe call it 'ndeadchain' instead,\n> > meaning the number of dead items in the chain.\n> \n> Makes sense.\n\nI've done this in attached v10.\n\n> > Here's another idea: In the first loop through the offsets, where we\n> > gather the HTSV status of each item, also collect the offsets of all HOT\n> > and non-HOT items to two separate arrays. Call heap_prune_chain() for\n> > all the non-HOT items first, and then process any remaining HOT tuples\n> > that haven't been marked yet.\n> \n> That's an interesting idea. I'll try it out and see how it works.\n\nAttached v10 implements this method of dividing tuples into HOT and\nnon-HOT and processing the potential HOT chains first then processing\ntuples not marked by calling heap_prune_chain().\n\nI have applied the refactoring of heap_prune_chain() to master and then\nbuilt the other patches on top of that.\n\nI discovered while writing this that LP_DEAD item offsets must be in\norder in the deadoffsets array (the one that is used to populate\nLVRelState->dead_items).\n\nWhen I changed heap_page_prune_and_freeze() to partition the offsets\ninto HOT and non-HOT during the first loop through the item pointers\narray (where we get tuple visibility information), we add dead item\noffsets as they are encountered. So, they are no longer in order. I've\nadded a quicksort of the deadoffsets array to satisfy vacuum.\n\nI think that we are actually successfully removing more RECENTLY_DEAD\nHOT tuples than in master with heap_page_prune()'s new approach, and I\nthink it is correct; but let me know if I am missing something.\n\nThe early patches in the set include some additional comment cleanup as\nwell. 0001 is fairly polished. 0004 could use some variable renaming\n(this patch partitions the tuples into HOT and not HOT and then\nprocesses them). I was struggling with some of the names here\n(chainmembers and chaincandidates is confusing).\n\nThe bulk of the combining of pruning and freezing is lumped into 0010.\n\nI had planned to separate 0010 into 4 separate patches: 1 to execute\nfreezing in heap_prune_chain(), 1 for the freeze heuristic approximating\nwhat is on master, and 1 for emitting a single record containing both\nthe pruning and freezing page modifications.\n\nI ended up not doing this because I felt like the grouping of changes in\n0007-0009 is off. As long as I still execute freezing in\nlazy_scan_prune(), I have to share lots of state between\nlazy_scan_prune() and heap_page_prune(). This meant I added a lot of\nparameters to heap_page_prune() that later commits removed -- making the\nlater patches noisy and not so easy to understand.\n\nI'm actually not sure what should go in what commit (either for review\nclarity or for the actual final version).\n\nBut, I think we should probably focus on review of the code and not as\nmuch how it is split up yet.\n\nThe final state of the code could definitely use more cleanup. I've been\nstaring at it for awhile, so I could use some thoughts/ideas about what\npart to focus on improving.\n\n- Melanie",
"msg_date": "Sat, 30 Mar 2024 01:57:10 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Sat, Mar 30, 2024 at 1:57 AM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n> I think that we are actually successfully removing more RECENTLY_DEAD\n> HOT tuples than in master with heap_page_prune()'s new approach, and I\n> think it is correct; but let me know if I am missing something.\n\n/me blinks.\n\nIsn't zero the only correct number of RECENTLY_DEAD tuples to remove?\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n",
"msg_date": "Sat, 30 Mar 2024 08:00:23 -0400",
"msg_from": "Robert Haas <robertmhaas@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Sat, Mar 30, 2024 at 8:00 AM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> On Sat, Mar 30, 2024 at 1:57 AM Melanie Plageman\n> <melanieplageman@gmail.com> wrote:\n> > I think that we are actually successfully removing more RECENTLY_DEAD\n> > HOT tuples than in master with heap_page_prune()'s new approach, and I\n> > think it is correct; but let me know if I am missing something.\n>\n> /me blinks.\n>\n> Isn't zero the only correct number of RECENTLY_DEAD tuples to remove?\n\nAt the top of the comment for heap_prune_chain() in master, it says\n\n * If the item is an index-referenced tuple (i.e. not a heap-only tuple),\n * the HOT chain is pruned by removing all DEAD tuples at the start of the HOT\n * chain. We also prune any RECENTLY_DEAD tuples preceding a DEAD tuple.\n * This is OK because a RECENTLY_DEAD tuple preceding a DEAD tuple is really\n * DEAD, our visibility test is just too coarse to detect it.\n\nHeikki had added a comment in one of his patches to the fast path for\nHOT tuples at the top of heap_prune_chain():\n\n * Note that we might first arrive at a dead heap-only tuple\n * either while following a chain or here (in the fast\npath). Whichever path\n * gets there first will mark the tuple unused.\n *\n * Whether we arrive at the dead HOT tuple first here or while\n * following a chain above affects whether preceding RECENTLY_DEAD\n * tuples in the chain can be removed or not. Imagine that you\n * have a chain with two tuples: RECENTLY_DEAD -> DEAD. If we\n * reach the RECENTLY_DEAD tuple first, the chain-following logic\n * will find the DEAD tuple and conclude that both tuples are in\n * fact dead and can be removed. But if we reach the DEAD tuple\n * at the end of the chain first, when we reach the RECENTLY_DEAD\n * tuple later, we will not follow the chain because the DEAD\n * TUPLE is already 'marked', and will not remove the\n * RECENTLY_DEAD tuple. This is not a correctness issue, and the\n * RECENTLY_DEAD tuple will be removed by a later VACUUM.\n\nMy patch splits the tuples into HOT and non-HOT while gathering their\nvisibility information and first calls heap_prune_chain() on the\nnon-HOT tuples and then processes the yet unmarked HOT tuples in a\nseparate loop afterward. This will follow all of the chains and\nprocess them completely as well as processing all HOT tuples which may\nnot be reachable from a valid chain. The fast path contains a special\ncheck to ensure that line pointers for DEAD not HOT-updated HOT tuples\n(dead orphaned tuples from aborted HOT updates) are still marked\nLP_UNUSED even though they are not reachable from a valid HOT chain.\nBy doing this later, we don't preclude ourselves from following all\nchains.\n\n- Melanie\n\n\n",
"msg_date": "Sat, 30 Mar 2024 12:10:12 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 30/03/2024 07:57, Melanie Plageman wrote:\n> On Fri, Mar 29, 2024 at 12:32:21PM -0400, Melanie Plageman wrote:\n>> On Fri, Mar 29, 2024 at 12:00 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>>> Here's another idea: In the first loop through the offsets, where we\n>>> gather the HTSV status of each item, also collect the offsets of all HOT\n>>> and non-HOT items to two separate arrays. Call heap_prune_chain() for\n>>> all the non-HOT items first, and then process any remaining HOT tuples\n>>> that haven't been marked yet.\n>>\n>> That's an interesting idea. I'll try it out and see how it works.\n> \n> Attached v10 implements this method of dividing tuples into HOT and\n> non-HOT and processing the potential HOT chains first then processing\n> tuples not marked by calling heap_prune_chain().\n> \n> I have applied the refactoring of heap_prune_chain() to master and then\n> built the other patches on top of that.\n\nCommitted some of the changes. Continuing to reviewing the rest.\n\n> I discovered while writing this that LP_DEAD item offsets must be in\n> order in the deadoffsets array (the one that is used to populate\n> LVRelState->dead_items).\n> \n> When I changed heap_page_prune_and_freeze() to partition the offsets\n> into HOT and non-HOT during the first loop through the item pointers\n> array (where we get tuple visibility information), we add dead item\n> offsets as they are encountered. So, they are no longer in order. I've\n> added a quicksort of the deadoffsets array to satisfy vacuum.\n\nGood catch.\n\n> I think that we are actually successfully removing more RECENTLY_DEAD\n> HOT tuples than in master with heap_page_prune()'s new approach, and I\n> think it is correct; but let me know if I am missing something.\n\nYep. In the case of a two-item chain, RECENTLY_DEAD -> DEAD, the new \ncode can always remove both items. On 'master', it depends on which item \nit happens to process first. If it processes the RECENTLY_DEAD item \nfirst, then it follows the chain and removes both. But if it processes \nthe DEAD item first, the RECENTLY_DEAD item is left behind. It will be \nremoved by the next VACUUM, so it's not a correctness issue, and \nprobably doesn't make any practical performance difference either as \nit's a rare corner case, but I feel better that it's more deterministic now.\n\n> The early patches in the set include some additional comment cleanup as\n> well. 0001 is fairly polished. 0004 could use some variable renaming\n> (this patch partitions the tuples into HOT and not HOT and then\n> processes them). I was struggling with some of the names here\n> (chainmembers and chaincandidates is confusing).\n\nI didn't understand why you wanted to juggle both partitions in the same \narray. So I separated them into two arrays, and called them 'root_items' \nand 'heaponly_items'.\n\nIn some micro-benchmarks, the order that the items were processed made a \nmeasurable difference. So I'm processing the items in the reverse order. \nThat roughly matches the order the items are processed in master, as it \niterates the offsets from high-to-low in the first loop, and low-to-high \nin the second loop.\n\n> The bulk of the combining of pruning and freezing is lumped into 0010.\n> \n> I had planned to separate 0010 into 4 separate patches: 1 to execute\n> freezing in heap_prune_chain(), 1 for the freeze heuristic approximating\n> what is on master, and 1 for emitting a single record containing both\n> the pruning and freezing page modifications.\n> \n> I ended up not doing this because I felt like the grouping of changes in\n> 0007-0009 is off. As long as I still execute freezing in\n> lazy_scan_prune(), I have to share lots of state between\n> lazy_scan_prune() and heap_page_prune(). This meant I added a lot of\n> parameters to heap_page_prune() that later commits removed -- making the\n> later patches noisy and not so easy to understand.\n> \n> I'm actually not sure what should go in what commit (either for review\n> clarity or for the actual final version).\n> \n> But, I think we should probably focus on review of the code and not as\n> much how it is split up yet.\n\nYeah, that's fine, 0010 is manageable-sized now.\n\n> The final state of the code could definitely use more cleanup. I've been\n> staring at it for awhile, so I could use some thoughts/ideas about what\n> part to focus on improving.\n\nCommitted some of the changes. I plan to commit at least the first of \nthese remaining patches later today. I'm happy with it now, but I'll \ngive it a final glance over after dinner.\n\nI'll continue to review the rest after that, but attached is what I have \nnow.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)",
"msg_date": "Mon, 1 Apr 2024 17:17:51 +0300",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Mon, Apr 01, 2024 at 05:17:51PM +0300, Heikki Linnakangas wrote:\n> On 30/03/2024 07:57, Melanie Plageman wrote:\n> > On Fri, Mar 29, 2024 at 12:32:21PM -0400, Melanie Plageman wrote:\n> > > On Fri, Mar 29, 2024 at 12:00 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> > > > Here's another idea: In the first loop through the offsets, where we\n> > > > gather the HTSV status of each item, also collect the offsets of all HOT\n> > > > and non-HOT items to two separate arrays. Call heap_prune_chain() for\n> > > > all the non-HOT items first, and then process any remaining HOT tuples\n> > > > that haven't been marked yet.\n> > > \n> > > That's an interesting idea. I'll try it out and see how it works.\n> > \n> > Attached v10 implements this method of dividing tuples into HOT and\n> > non-HOT and processing the potential HOT chains first then processing\n> > tuples not marked by calling heap_prune_chain().\n> > \n> > I have applied the refactoring of heap_prune_chain() to master and then\n> > built the other patches on top of that.\n> \n> Committed some of the changes. Continuing to reviewing the rest.\n\nThanks!\n\n> > The early patches in the set include some additional comment cleanup as\n> > well. 0001 is fairly polished. 0004 could use some variable renaming\n> > (this patch partitions the tuples into HOT and not HOT and then\n> > processes them). I was struggling with some of the names here\n> > (chainmembers and chaincandidates is confusing).\n> \n> I didn't understand why you wanted to juggle both partitions in the same\n> array. So I separated them into two arrays, and called them 'root_items' and\n> 'heaponly_items'.\n\nI thought it was worth it to save the space. And the algorithm for doing\nit seemed pretty straightforward. But looking at your patch, it is a lot\neasier to understand with two arrays (since, for example, they can each\nhave a name).\n\n> In some micro-benchmarks, the order that the items were processed made a\n> measurable difference. So I'm processing the items in the reverse order.\n> That roughly matches the order the items are processed in master, as it\n> iterates the offsets from high-to-low in the first loop, and low-to-high in\n> the second loop.\n\nThis makes sense. I noticed you didn't there isn't a comment about this\nabove the loop. It might be worth it to mention it.\n\nBelow is a review of only 0001. I'll look at the others shortly.\n\n> From a6ab891779876e7cc1b4fb6fddb09f52f0094646 Mon Sep 17 00:00:00 2001\n> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> Date: Mon, 1 Apr 2024 16:59:38 +0300\n> Subject: [PATCH v11 1/7] Handle non-chain tuples outside of heap_prune_chain()\n> ---\n> src/backend/access/heap/pruneheap.c | 264 +++++++++++++++++-----------\n> 1 file changed, 166 insertions(+), 98 deletions(-)\n> \n> diff --git a/src/backend/access/heap/pruneheap.c b/src/backend/access/heap/pruneheap.c\n> @@ -256,15 +270,16 @@ heap_page_prune(Relation relation, Buffer buffer,\n> \ttup.t_tableOid = RelationGetRelid(relation);\n> \n> \t/*\n> -\t * Determine HTSV for all tuples.\n> +\t * Determine HTSV for all tuples, and queue them up for processing as HOT\n> +\t * chain roots or as a heap-only items.\n\nReading this comment now as a whole, I would add something like\n\"Determining HTSV for all tuples once is required for correctness\" to\nthe start of the second paragraph. The new conjunction on the first\nparagraph sentence followed by the next paragraph is a bit confusing\nbecause it sounds like queuing them up for processing is required for\ncorrectness (which, I suppose it is on some level). Basically, I'm just\nsaying that it is now less clear what is required for correctness.\n\n> \t * This is required for correctness to deal with cases where running HTSV\n> \t * twice could result in different results (e.g. RECENTLY_DEAD can turn to\n> \t * DEAD if another checked item causes GlobalVisTestIsRemovableFullXid()\n> \t * to update the horizon, INSERT_IN_PROGRESS can change to DEAD if the\n> -\t * inserting transaction aborts, ...). That in turn could cause\n> -\t * heap_prune_chain() to behave incorrectly if a tuple is reached twice,\n> -\t * once directly via a heap_prune_chain() and once following a HOT chain.\n> +\t * inserting transaction aborts, ...). VACUUM assumes that there are no\n> +\t * normal DEAD tuples left on the page after pruning, so it needs to have\n> +\t * the same understanding of what is DEAD and what is not.\n> \t *\n> \t * It's also good for performance. Most commonly tuples within a page are\n> \t * stored at decreasing offsets (while the items are stored at increasing\n> @@ -282,52 +297,140 @@ heap_page_prune(Relation relation, Buffer buffer,\n\n> +\t/*\n> +\t * Process any heap-only tuples that were not already processed as part of\n> +\t * a HOT chain.\n> +\t */\n\nWhile I recognize this is a matter of style and not important, I\npersonally prefer this for reverse looping:\n\n\tfor (int i = prstate.nheaponly_items; i --> 0;)\n\nI do think a comment about the reverse order would be nice. I know it\nsays something above the first loop to this effect:\n\n* Processing the items in reverse order (and thus the tuples in\n* increasing order) increases prefetching efficiency significantly /\n* decreases the number of cache misses.\n\nSo perhaps we could just say \"as above, process the items in reverse\norder\"\n\n- Melanie\n\n\n",
"msg_date": "Mon, 1 Apr 2024 12:08:56 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Mon, Apr 01, 2024 at 05:17:51PM +0300, Heikki Linnakangas wrote:\n> On 30/03/2024 07:57, Melanie Plageman wrote:\n> \n> > The final state of the code could definitely use more cleanup. I've been\n> > staring at it for awhile, so I could use some thoughts/ideas about what\n> > part to focus on improving.\n> \n> Committed some of the changes. I plan to commit at least the first of these\n> remaining patches later today. I'm happy with it now, but I'll give it a\n> final glance over after dinner.\n> \n> I'll continue to review the rest after that, but attached is what I have\n> now.\n\nReview for 0003-0006 (I didn't have any new thoughts on 0002). I know\nyou didn't modify them much/at all, but I noticed some things in my code\nthat could be better.\n\n> From 17e183835a968e81daf7b74a4164b243e2de35aa Mon Sep 17 00:00:00 2001\n> From: Melanie Plageman <melanieplageman@gmail.com>\n> Date: Fri, 29 Mar 2024 19:43:09 -0400\n> Subject: [PATCH v11 3/7] Introduce PRUNE_DO_* actions\n> \n> We will eventually take additional actions in heap_page_prune() at the\n> discretion of the caller. For now, introduce these PRUNE_DO_* macros and\n> turn mark_unused_now, a paramter to heap_page_prune(), into a PRUNE_DO_\n\nparamter -> parameter\n\n> action.\n> ---\n> src/backend/access/heap/pruneheap.c | 51 ++++++++++++++--------------\n> src/backend/access/heap/vacuumlazy.c | 11 ++++--\n> src/include/access/heapam.h | 13 ++++++-\n> 3 files changed, 46 insertions(+), 29 deletions(-)\n> \n> diff --git a/src/backend/access/heap/pruneheap.c b/src/backend/access/heap/pruneheap.c\n> index fb0ad834f1b..30965c3c5a1 100644\n> --- a/src/backend/access/heap/pruneheap.c\n> +++ b/src/backend/access/heap/pruneheap.c\n> @@ -29,10 +29,11 @@\n> /* Working data for heap_page_prune and subroutines */\n> typedef struct\n> {\n> +\t/* PRUNE_DO_* arguments */\n> +\tuint8\t\tactions;\n\nI wasn't sure if actions is a good name. What do you think?\n\n> +\n> \t/* tuple visibility test, initialized for the relation */\n> \tGlobalVisState *vistest;\n> -\t/* whether or not dead items can be set LP_UNUSED during pruning */\n> -\tbool\t\tmark_unused_now;\n> \n> \tTransactionId new_prune_xid;\t/* new prune hint value for page */\n> \tTransactionId snapshotConflictHorizon;\t/* latest xid removed */\n\n> diff --git a/src/include/access/heapam.h b/src/include/access/heapam.h\n> index 32a3fbce961..35b8486c34a 100644\n> --- a/src/include/access/heapam.h\n> +++ b/src/include/access/heapam.h\n> @@ -191,6 +191,17 @@ typedef struct HeapPageFreeze\n> \n> } HeapPageFreeze;\n> \n> +/*\n> + * Actions that can be taken during pruning and freezing. By default, we will\n> + * at least attempt regular pruning.\n> + */\n> +\n> +/*\n> + * PRUNE_DO_MARK_UNUSED_NOW indicates whether or not dead items can be set\n> + * LP_UNUSED during pruning.\n> + */\n> +#define\t\tPRUNE_DO_MARK_UNUSED_NOW (1 << 1)\n\n\nNo reason for me to waste the zeroth bit here. I just realized that I\ndid this with XLHP_IS_CATALOG_REL too.\n\n#define\t\tXLHP_IS_CATALOG_REL\t\t\t(1 << 1)\n\n> From 083690b946e19ab5e536a9f2689772e7b91d2a70 Mon Sep 17 00:00:00 2001\n> From: Melanie Plageman <melanieplageman@gmail.com>\n> Date: Fri, 29 Mar 2024 21:22:14 -0400\n> Subject: [PATCH v11 4/7] Prepare freeze tuples in heap_page_prune()\n> \n> diff --git a/src/include/access/heapam.h b/src/include/access/heapam.h\n> index 35b8486c34a..ac129692c13 100644\n> --- a/src/include/access/heapam.h\n> +++ b/src/include/access/heapam.h\n> \n> +/*\n> + * Prepare to freeze if advantageous or required and try to advance\n> + * relfrozenxid and relminmxid. To attempt freezing, we will need to determine\n> + * if the page is all frozen. So, if this action is set, we will also inform\n> + * the caller if the page is all-visible and/or all-frozen and calculate a\n\nI guess we don't inform the caller if the page is all-visible, so this\nis not quite right.\n\n> + * snapshot conflict horizon for updating the visibility map.\n> + */\n> +#define\t\tPRUNE_DO_TRY_FREEZE (1 << 2)\n\n> From ef8cb2c089ad9474a6da309593029c08f71b0bb9 Mon Sep 17 00:00:00 2001\n> From: Melanie Plageman <melanieplageman@gmail.com>\n> Date: Fri, 29 Mar 2024 21:36:37 -0400\n> Subject: [PATCH v11 5/7] Set hastup in heap_page_prune\n> \n> diff --git a/src/backend/access/heap/pruneheap.c b/src/backend/access/heap/pruneheap.c\n> index 8bdd6389b25..65b0ed185ff 100644\n> --- a/src/backend/access/heap/pruneheap.c\n> +++ b/src/backend/access/heap/pruneheap.c\n> @@ -66,6 +66,9 @@ typedef struct\n> \tbool\t\tprocessed[MaxHeapTuplesPerPage + 1];\n> \n> \tint\t\t\tndeleted;\t\t/* Number of tuples deleted from the page */\n> +\n> +\t/* Whether or not the page makes rel truncation unsafe */\n> +\tbool\t\thastup;\n> } PruneState;\n> \n> /* Local functions */\n> @@ -271,6 +274,7 @@ heap_page_prune(Relation relation, Buffer buffer,\n> \tprstate.ndeleted = 0;\n> \tprstate.nroot_items = 0;\n> \tprstate.nheaponly_items = 0;\n> +\tprstate.hastup = false;\n> \n> \t/*\n> \t * If we will prepare to freeze tuples, consider that it might be possible\n> @@ -280,7 +284,7 @@ heap_page_prune(Relation relation, Buffer buffer,\n> \t\tpresult->all_frozen = true;\n> \telse\n> \t\tpresult->all_frozen = false;\n> -\n> +\tpresult->hastup = prstate.hastup;\n> \n> \t/*\n> \t * presult->htsv is not initialized here because all ntuple spots in the\n> @@ -819,6 +823,8 @@ heap_prune_record_redirect(PruneState *prstate,\n> \t */\n> \tif (was_normal)\n> \t\tprstate->ndeleted++;\n> +\n> +\tprstate->hastup = true;\n> }\n> \n> /* Record line pointer to be marked dead */\n> @@ -901,11 +907,15 @@ static void\n> heap_prune_record_unchanged_lp_normal(Page page, int8 *htsv, PruneState *prstate,\n> \t\t\t\t\t\t\t\t\t PruneResult *presult, OffsetNumber offnum)\n> {\n> -\tHeapTupleHeader htup = (HeapTupleHeader) PageGetItem(page, PageGetItemId(page, offnum));\n> +\tHeapTupleHeader htup;\n> \n> \tAssert(!prstate->processed[offnum]);\n> \tprstate->processed[offnum] = true;\n> \n> +\tpresult->hastup = true;\t\t/* the page is not empty */\n\nMy fault, but hastup being set sometimes in PruneState and sometimes in\nPruneResult is quite unpalatable.\n\n\n> From dffa90d0bd8e972cfe26da96860051dc8c2a8576 Mon Sep 17 00:00:00 2001\n> From: Melanie Plageman <melanieplageman@gmail.com>\n> Date: Sat, 30 Mar 2024 01:27:08 -0400\n> Subject: [PATCH v11 6/7] Save dead tuple offsets during heap_page_prune\n> ---\n> diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c\n> index 212d76045ef..7f1e4db55c0 100644\n> --- a/src/backend/access/heap/vacuumlazy.c\n> +++ b/src/backend/access/heap/vacuumlazy.c\n> @@ -1373,6 +1373,15 @@ lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,\n> \treturn false;\n> }\n> \n> +static int\n> +OffsetNumber_cmp(const void *a, const void *b)\n> +{\n> +\tOffsetNumber na = *(const OffsetNumber *) a,\n> +\t\t\t\tnb = *(const OffsetNumber *) b;\n> +\n> +\treturn na < nb ? -1 : na > nb;\n> +}\n\nThis probably doesn't belong here. I noticed spgdoinsert.c had a static\nfunction for sorting OffsetNumbers, but I didn't see anything general\npurpose anywhere else.\n\n- Melanie\n\n\n",
"msg_date": "Mon, 1 Apr 2024 13:22:19 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 01/04/2024 19:08, Melanie Plageman wrote:\n> On Mon, Apr 01, 2024 at 05:17:51PM +0300, Heikki Linnakangas wrote:\n>> diff --git a/src/backend/access/heap/pruneheap.c b/src/backend/access/heap/pruneheap.c\n>> @@ -256,15 +270,16 @@ heap_page_prune(Relation relation, Buffer buffer,\n>> \ttup.t_tableOid = RelationGetRelid(relation);\n>> \n>> \t/*\n>> -\t * Determine HTSV for all tuples.\n>> +\t * Determine HTSV for all tuples, and queue them up for processing as HOT\n>> +\t * chain roots or as a heap-only items.\n> \n> Reading this comment now as a whole, I would add something like\n> \"Determining HTSV for all tuples once is required for correctness\" to\n> the start of the second paragraph. The new conjunction on the first\n> paragraph sentence followed by the next paragraph is a bit confusing\n> because it sounds like queuing them up for processing is required for\n> correctness (which, I suppose it is on some level). Basically, I'm just\n> saying that it is now less clear what is required for correctness.\n\nFixed.\n\n> While I recognize this is a matter of style and not important, I\n> personally prefer this for reverse looping:\n> \n> \tfor (int i = prstate.nheaponly_items; i --> 0;)\n\nI don't think we use that style anywhere in the Postgres source tree \ncurrently. (And I don't like it ;-) )\n\n> I do think a comment about the reverse order would be nice. I know it\n> says something above the first loop to this effect:\n> \n> * Processing the items in reverse order (and thus the tuples in\n> * increasing order) increases prefetching efficiency significantly /\n> * decreases the number of cache misses.\n> \n> So perhaps we could just say \"as above, process the items in reverse\n> order\"\n\nI'm actually not sure why it makes a difference. I would assume all the \ndata to already be in CPU cache at this point, since the first loop \nalready accessed it, so I think there's something else going on. But I \ndidn't investigate it deeper. Anyway, added a comment.\n\nCommitted the first of the remaining patches with those changes. And \nalso this, which is worth calling out:\n\n> \t\tif (prstate.htsv[offnum] == HEAPTUPLE_DEAD)\n> \t\t{\n> \t\t\tItemId\t\titemid = PageGetItemId(page, offnum);\n> \t\t\tHeapTupleHeader htup = (HeapTupleHeader) PageGetItem(page, itemid);\n> \n> \t\t\tif (likely(!HeapTupleHeaderIsHotUpdated(htup)))\n> \t\t\t{\n> \t\t\t\tHeapTupleHeaderAdvanceConflictHorizon(htup,\n> \t\t\t\t\t\t\t\t\t\t\t\t\t &prstate.latest_xid_removed);\n> \t\t\t\theap_prune_record_unused(&prstate, offnum, true);\n> \t\t\t}\n> \t\t\telse\n> \t\t\t{\n> \t\t\t\t/*\n> \t\t\t\t * This tuple should've been processed and removed as part of\n> \t\t\t\t * a HOT chain, so something's wrong. To preserve evidence,\n> \t\t\t\t * we don't dare to remove it. We cannot leave behind a DEAD\n> \t\t\t\t * tuple either, because that will cause VACUUM to error out.\n> \t\t\t\t * Throwing an error with a distinct error message seems like\n> \t\t\t\t * the least bad option.\n> \t\t\t\t */\n> \t\t\t\telog(ERROR, \"dead heap-only tuple (%u, %d) is not linked to from any HOT chain\",\n> \t\t\t\t\t blockno, offnum);\n> \t\t\t}\n> \t\t}\n> \t\telse\n> \t\t\theap_prune_record_unchanged_lp_normal(page, &prstate, offnum);\n\nAs you can see, I turned that into a hard error. Previously, that code \nwas at the top of heap_prune_chain(), and it was normal to see DEAD \nheap-only tuples there, because they would presumably get processed \nlater as part of a HOT chain. But now this is done after all the HOT \nchains have already been processed.\n\nPreviously if there was a dead heap-only tuple like that on the page for \nsome reason, it was silently not processed by heap_prune_chain() \n(because it was assumed that it would be processed later as part of a \nHOT chain), and was left behind as a HEAPTUPLE_DEAD tuple. If the \npruning was done as part of VACUUM, VACUUM would fail with \"ERROR: \nunexpected HeapTupleSatisfiesVacuum result\". Or am I missing something?\n\nNow you get that above error also on on-access pruning, which is not \nideal. But I don't remember hearing about corruption like that, and \nyou'd get the error on VACUUM anyway.\n\nWith the next patches, heap_prune_record_unchanged() will do more, and \nwill also throw an error on a HEAPTUPLE_LIVE tuple, so even though in \nthe first patch we could print just a WARNING and move on, it gets more \nawkward with the rest of the patches.\n\n(Continuing with the remaining patches..)\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Mon, 1 Apr 2024 20:37:46 +0300",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Mon, Apr 1, 2024 at 1:37 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> Committed the first of the remaining patches with those changes. And\n> also this, which is worth calling out:\n>\n> > if (prstate.htsv[offnum] == HEAPTUPLE_DEAD)\n> > {\n> > ItemId itemid = PageGetItemId(page, offnum);\n> > HeapTupleHeader htup = (HeapTupleHeader) PageGetItem(page, itemid);\n> >\n> > if (likely(!HeapTupleHeaderIsHotUpdated(htup)))\n> > {\n> > HeapTupleHeaderAdvanceConflictHorizon(htup,\n> > &prstate.latest_xid_removed);\n> > heap_prune_record_unused(&prstate, offnum, true);\n> > }\n> > else\n> > {\n> > /*\n> > * This tuple should've been processed and removed as part of\n> > * a HOT chain, so something's wrong. To preserve evidence,\n> > * we don't dare to remove it. We cannot leave behind a DEAD\n> > * tuple either, because that will cause VACUUM to error out.\n> > * Throwing an error with a distinct error message seems like\n> > * the least bad option.\n> > */\n> > elog(ERROR, \"dead heap-only tuple (%u, %d) is not linked to from any HOT chain\",\n> > blockno, offnum);\n> > }\n> > }\n> > else\n> > heap_prune_record_unchanged_lp_normal(page, &prstate, offnum);\n>\n> As you can see, I turned that into a hard error. Previously, that code\n> was at the top of heap_prune_chain(), and it was normal to see DEAD\n> heap-only tuples there, because they would presumably get processed\n> later as part of a HOT chain. But now this is done after all the HOT\n> chains have already been processed.\n>\n> Previously if there was a dead heap-only tuple like that on the page for\n> some reason, it was silently not processed by heap_prune_chain()\n> (because it was assumed that it would be processed later as part of a\n> HOT chain), and was left behind as a HEAPTUPLE_DEAD tuple. If the\n> pruning was done as part of VACUUM, VACUUM would fail with \"ERROR:\n> unexpected HeapTupleSatisfiesVacuum result\". Or am I missing something?\n\nI think you are right. I wasn't sure if there was some way for a HOT,\nDEAD tuple to be not HOT-updated, but that doesn't make much sense.\n\n> Now you get that above error also on on-access pruning, which is not\n> ideal. But I don't remember hearing about corruption like that, and\n> you'd get the error on VACUUM anyway.\n\nYea, that makes sense. One thing I don't really understand is why\nvacuum has its own system for saving and restoring error information\nfor context messages (LVSavedErrInfo and\nupdate/restore_vacuum_err_info()). I'll confess I don't know much\nabout how error cleanup works in any sub-system. But it stuck out to\nme that vacuum has its own. I assume it is okay to add new error\nmessages and they somehow will work with the existing system?\n\n- Melanie\n\n\n",
"msg_date": "Mon, 1 Apr 2024 14:47:36 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 01/04/2024 20:22, Melanie Plageman wrote:\n>> From 17e183835a968e81daf7b74a4164b243e2de35aa Mon Sep 17 00:00:00 2001\n>> From: Melanie Plageman <melanieplageman@gmail.com>\n>> Date: Fri, 29 Mar 2024 19:43:09 -0400\n>> Subject: [PATCH v11 3/7] Introduce PRUNE_DO_* actions\n>>\n>> We will eventually take additional actions in heap_page_prune() at the\n>> discretion of the caller. For now, introduce these PRUNE_DO_* macros and\n>> turn mark_unused_now, a paramter to heap_page_prune(), into a PRUNE_DO_\n> \n> paramter -> parameter\n> \n>> action.\n>> ---\n>> src/backend/access/heap/pruneheap.c | 51 ++++++++++++++--------------\n>> src/backend/access/heap/vacuumlazy.c | 11 ++++--\n>> src/include/access/heapam.h | 13 ++++++-\n>> 3 files changed, 46 insertions(+), 29 deletions(-)\n>>\n>> diff --git a/src/backend/access/heap/pruneheap.c b/src/backend/access/heap/pruneheap.c\n>> index fb0ad834f1b..30965c3c5a1 100644\n>> --- a/src/backend/access/heap/pruneheap.c\n>> +++ b/src/backend/access/heap/pruneheap.c\n>> @@ -29,10 +29,11 @@\n>> /* Working data for heap_page_prune and subroutines */\n>> typedef struct\n>> {\n>> +\t/* PRUNE_DO_* arguments */\n>> +\tuint8\t\tactions;\n> \n> I wasn't sure if actions is a good name. What do you think?\n\nCommitted this part, with the name 'options'. There's some precedent for \nthat in heap_insert().\n\nI decided to keep it a separate bool field here in the PruneState \nstruct, though, and only changed it in the heap_page_prune() function \nsignature. It didn't feel worth the code churn here, and \n'prstate.mark_unused_now' is a shorter than \"(prstate.options & \nHEAP_PRUNE_PAGE_MARK_UNUSED_NOW) != 0\" anyway.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Tue, 2 Apr 2024 00:57:27 +0300",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 01/04/2024 20:22, Melanie Plageman wrote:\n> Review for 0003-0006 (I didn't have any new thoughts on 0002). I know\n> you didn't modify them much/at all, but I noticed some things in my code\n> that could be better.\n\nOk, here's what I have now. I made a lot of small comment changes here \nand there, and some minor local refactorings, but nothing major. I lost \ntrack of all the individual changes I'm afraid, so I'm afraid you'll \nhave to just diff against the previous version if you want to see what's \nchanged. I hope I didn't break anything.\n\nI'm pretty happy with this now. I will skim through it one more time \nlater today or tomorrow, and commit. Please review once more if you have \na chance.\n\n> This probably doesn't belong here. I noticed spgdoinsert.c had a static\n> function for sorting OffsetNumbers, but I didn't see anything general\n> purpose anywhere else.\n\nI copied the spgdoinsert.c implementation to vacuumlazy.c as is. Would \nbe nice to have just one copy of this in some common place, but I also \nwasn't sure where to put it.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)",
"msg_date": "Tue, 2 Apr 2024 16:11:49 +0300",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Tue, Apr 2, 2024 at 9:11 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> On 01/04/2024 20:22, Melanie Plageman wrote:\n> > Review for 0003-0006 (I didn't have any new thoughts on 0002). I know\n> > you didn't modify them much/at all, but I noticed some things in my code\n> > that could be better.\n>\n> Ok, here's what I have now. I made a lot of small comment changes here\n> and there, and some minor local refactorings, but nothing major. I lost\n> track of all the individual changes I'm afraid, so I'm afraid you'll\n> have to just diff against the previous version if you want to see what's\n> changed. I hope I didn't break anything.\n>\n> I'm pretty happy with this now. I will skim through it one more time\n> later today or tomorrow, and commit. Please review once more if you have\n> a chance.\n\nThanks!\n\n0001 looks good. Attached are some comment updates and such on top of\n0001 and 0002.\n\nI started some performance testing of 0002 but haven't finished yet. I\nwanted to provide my other review first.\n\n> > This probably doesn't belong here. I noticed spgdoinsert.c had a static\n> > function for sorting OffsetNumbers, but I didn't see anything general\n> > purpose anywhere else.\n>\n> I copied the spgdoinsert.c implementation to vacuumlazy.c as is. Would\n> be nice to have just one copy of this in some common place, but I also\n> wasn't sure where to put it.\n\nI looked a bit through utils and common and didn't see anywhere\nobvious to put it. We could make a new file? 0003 fixes where you\nforgot to change the name of the qsort function, though.\n\n- Melanie",
"msg_date": "Tue, 2 Apr 2024 13:24:27 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Tue, Apr 02, 2024 at 01:24:27PM -0400, Melanie Plageman wrote:\n> On Tue, Apr 2, 2024 at 9:11 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> >\n> > On 01/04/2024 20:22, Melanie Plageman wrote:\n> > > Review for 0003-0006 (I didn't have any new thoughts on 0002). I know\n> > > you didn't modify them much/at all, but I noticed some things in my code\n> > > that could be better.\n> >\n> > Ok, here's what I have now. I made a lot of small comment changes here\n> > and there, and some minor local refactorings, but nothing major. I lost\n> > track of all the individual changes I'm afraid, so I'm afraid you'll\n> > have to just diff against the previous version if you want to see what's\n> > changed. I hope I didn't break anything.\n> >\n> > I'm pretty happy with this now. I will skim through it one more time\n> > later today or tomorrow, and commit. Please review once more if you have\n> > a chance.\n> \n> Thanks!\n> \n> 0001 looks good. Attached are some comment updates and such on top of\n> 0001 and 0002.\n> \n> I started some performance testing of 0002 but haven't finished yet. I\n> wanted to provide my other review first.\n\nI tried to do some performance tests of just on-access HOT pruning with\nthe patches in this thread applied. I'm not sure if I succeeded in being\ntargeted enough to have usable results.\n\nOff-list Andres gave me some suggestions of how to improve my test case\nand setup and this is what I ended up doing:\n\n----------------------------------------\nOn-access pruning during a SELECT query:\n----------------------------------------\n\n# Make a table with a single not NULL column of a small datatype to fit\n# as many tuples as possible on the page so each page we prune exercises\n# those loops in heap_page_prune_and_freeze() and heap_prune_chain() as\n# much as possible\n\npsql -c \"create table small(col smallint not null)\"\n\n# Insert data that is the same except for ~1 row per page with a different value\n\nfor i in $(seq 1000)\ndo\n psql -c \"INSERT INTO small VALUES(2);\" -c \"INSERT INTO small SELECT 1 FROM (SELECT generate_series(1,220));\"\ndone\n\n# COPY this data to a file\npsql -c \"COPY small TO '/tmp/small.data';\"\n\n# Start postgres bound to a single CPU core\n\n# Run the following script with pgbench\n\n\t# Make the table unlogged table so we don't see the effects of WAL writes in\n\t# results\n\t#\n\t# Make sure autovacuum doesn't run on the table\n drop table if exists small;\n create unlogged table small(col smallint not null) with (autovacuum_enabled = false);\n copy small from '/tmp/small.data';\n update small set col = 9 where col = 2;\n select * from small where col = 0;\n\npgbench -n -f query.sql -t 100 -M prepared -r\n\n# (I made sure that HOT pruning was actually happening for the SELECT\n# query before running this with pgbench)\n\n# There seemed to be no meaningful difference for this example with the\n# patches:\n\non current master:\nstatement latencies in milliseconds and failures:\n 12.387 0 drop table if exists small;\n 1.914 0 create unlogged table small(col smallint not null) with (autovacuum_enabled = false);\n 100.152 0 copy small from '/tmp/small.data';\n 49.480 0 update small set col = 9 where col = 2;\n 46.835 0 select * from small where col = 0;\n\nwith the patches applied:\nstatement latencies in milliseconds and failures:\n 13.281 0 drop table if exists small;\n 1.952 0 create unlogged table small(col smallint not null) with (autovacuum_enabled = false);\n 99.418 0 copy small from '/tmp/small.data';\n 47.397 0 update small set col = 9 where col = 2;\n 46.887 0 select * from small where col = 0;\n\n--------------------------------\nOn-access pruning during UPDATE:\n--------------------------------\n\n# The idea is to test a query which would be calling the new\n# heap_prune_record_unchanged_lp_normal() function a lot\n\n# I made the same table but filled entirely with the same value\n\npsql -c \"create table small(col smallint not null)\" \\\n\t\t-c \"INSERT INTO small SELECT 1 FROM (SELECT generate_series(1, 221000));\"\n\n# COPY this data to a file\npsql -c \"COPY small TO '/tmp/small_univalue.data';\"\n\n# Start postgres bound to a single CPU core\n\n# Run the following script with pgbench\n\n\t# Pick a low fillfactor so we have room for the HOT updates\n drop table if exists small;\n create unlogged table small(col smallint not null) with (autovacuum_enabled = false, fillfactor=25);\n copy small from '/tmp/small_univalue.data';\n update small set col = 3;\n update small set col = 4;\n update small set col = 5;\n update small set col = 6;\n\npgbench -n -f update.sql -t 20 -M prepared -r\n\n# There again seems to be no meaningful difference with the patches\n# applied\n\non master:\nstatement latencies in milliseconds and failures:\n 19.880 0 drop table if exists small;\n 2.099 0 create unlogged table small(col smallint not null) with (autovacuum_enabled = false, fillfactor=25);\n 130.793 0 copy small from '/tmp/small_univalue.data';\n 377.707 0 update small set col = 3;\n 417.644 0 update small set col = 4;\n 483.974 0 update small set col = 5;\n 422.956 0 update small set col = 6;\n\nwith patches applied:\nstatement latencies in milliseconds and failures:\n 19.995 0 drop table if exists small;\n 2.034 0 create unlogged table small(col smallint not null) with (autovacuum_enabled = false, fillfactor=25);\n 124.270 0 copy small from '/tmp/small_univalue.data';\n 375.327 0 update small set col = 3;\n 419.336 0 update small set col = 4;\n 483.750 0 update small set col = 5;\n 420.451 0 update small set col = 6;\n\n- Melanie\n\n\n",
"msg_date": "Tue, 2 Apr 2024 16:54:28 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 02/04/2024 16:11, Heikki Linnakangas wrote:\n> On 01/04/2024 20:22, Melanie Plageman wrote:\n>> Review for 0003-0006 (I didn't have any new thoughts on 0002). I know\n>> you didn't modify them much/at all, but I noticed some things in my code\n>> that could be better.\n> \n> Ok, here's what I have now. I made a lot of small comment changes here\n> and there, and some minor local refactorings, but nothing major. I lost\n> track of all the individual changes I'm afraid, so I'm afraid you'll\n> have to just diff against the previous version if you want to see what's\n> changed. I hope I didn't break anything.\n> \n> I'm pretty happy with this now. I will skim through it one more time\n> later today or tomorrow, and commit. Please review once more if you have\n> a chance.\n> \n>> This probably doesn't belong here. I noticed spgdoinsert.c had a static\n>> function for sorting OffsetNumbers, but I didn't see anything general\n>> purpose anywhere else.\n> \n> I copied the spgdoinsert.c implementation to vacuumlazy.c as is. Would\n> be nice to have just one copy of this in some common place, but I also\n> wasn't sure where to put it.\n\nOne more version, with two small fixes:\n\n1. I fumbled the offsetnumber-cmp function at the last minute so that it \ndidn't compile. Fixed. that\n\n2. On VACUUM on an unlogged or temp table, the logic always thought that \nwe would be generating an FPI, causing it to always freeze when it \ncould. But of course, you never generate FPIs on an unlogged table. \nFixed that. (Perhaps we should indeed freeze more aggressively on an \nunlogged table, but changing the heuristic is out of scope for this patch.)\n\nOff-list, Melanie reported that there is a small regression with the \nbenchmark script she posted yesterday, after all, but I'm not able to \nreproduce that.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)",
"msg_date": "Wed, 3 Apr 2024 15:39:55 +0300",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Wed, Apr 3, 2024 at 8:39 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> On 02/04/2024 16:11, Heikki Linnakangas wrote:\n> > On 01/04/2024 20:22, Melanie Plageman wrote:\n> >> Review for 0003-0006 (I didn't have any new thoughts on 0002). I know\n> >> you didn't modify them much/at all, but I noticed some things in my code\n> >> that could be better.\n> >\n> > Ok, here's what I have now. I made a lot of small comment changes here\n> > and there, and some minor local refactorings, but nothing major. I lost\n> > track of all the individual changes I'm afraid, so I'm afraid you'll\n> > have to just diff against the previous version if you want to see what's\n> > changed. I hope I didn't break anything.\n> >\n> > I'm pretty happy with this now. I will skim through it one more time\n> > later today or tomorrow, and commit. Please review once more if you have\n> > a chance.\n> >\n> >> This probably doesn't belong here. I noticed spgdoinsert.c had a static\n> >> function for sorting OffsetNumbers, but I didn't see anything general\n> >> purpose anywhere else.\n> >\n> > I copied the spgdoinsert.c implementation to vacuumlazy.c as is. Would\n> > be nice to have just one copy of this in some common place, but I also\n> > wasn't sure where to put it.\n>\n> One more version, with two small fixes:\n>\n> 1. I fumbled the offsetnumber-cmp function at the last minute so that it\n> didn't compile. Fixed. that\n\nI noticed you didn't make the comment updates I suggested in my\nversion 13 here [1]. A few of them are outdated references to\nheap_page_prune() and one to a now deleted variable name\n(all_visible_except_removable).\n\nI applied them to your v13 and attached the diff.\n\n> Off-list, Melanie reported that there is a small regression with the\n> benchmark script she posted yesterday, after all, but I'm not able to\n> reproduce that.\n\nActually, I think it was noise.\n\n- Melanie\n\n[1] https://www.postgresql.org/message-id/CAAKRu_aPqZkThyfr0USaHp-3cN_ruEdAHBKtNQJqXDTjWUz0rw%40mail.gmail.com",
"msg_date": "Wed, 3 Apr 2024 10:18:13 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On 03/04/2024 17:18, Melanie Plageman wrote:\n> I noticed you didn't make the comment updates I suggested in my\n> version 13 here [1]. A few of them are outdated references to\n> heap_page_prune() and one to a now deleted variable name\n> (all_visible_except_removable).\n> \n> I applied them to your v13 and attached the diff.\n\nApplied those changes, and committed. Thank you!\n\n>> Off-list, Melanie reported that there is a small regression with the\n>> benchmark script she posted yesterday, after all, but I'm not able to\n>> reproduce that.\n> \n> Actually, I think it was noise.\n\nOk, phew.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Wed, 3 Apr 2024 19:34:40 +0300",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Wed, Apr 3, 2024 at 12:34 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> On 03/04/2024 17:18, Melanie Plageman wrote:\n> > I noticed you didn't make the comment updates I suggested in my\n> > version 13 here [1]. A few of them are outdated references to\n> > heap_page_prune() and one to a now deleted variable name\n> > (all_visible_except_removable).\n> >\n> > I applied them to your v13 and attached the diff.\n>\n> Applied those changes, and committed. Thank you!\n\nThanks! And thanks for updating the commitfest entry!\n\n- Melanie\n\n\n",
"msg_date": "Wed, 3 Apr 2024 13:04:07 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
},
{
"msg_contents": "On Wed, Apr 3, 2024 at 1:04 PM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n> Thanks! And thanks for updating the commitfest entry!\n\nNice work!\n\n-- \nPeter Geoghegan\n\n\n",
"msg_date": "Wed, 3 Apr 2024 14:58:57 -0400",
"msg_from": "Peter Geoghegan <pg@bowt.ie>",
"msg_from_op": false,
"msg_subject": "Re: Combine Prune and Freeze records emitted by vacuum"
}
] |
[
{
"msg_contents": "I came across a warning when building master (a044e61f1b) on old GCC\n(4.8.5).\n\njsonfuncs.c: In function ‘jsonb_populate_record_valid’:\n../../../../src/include/nodes/miscnodes.h:53:15: warning: the comparison\nwill always evaluate as ‘true’ for the address of ‘escontext’ will never be\nNULL [-Waddress]\n ((escontext) != NULL && IsA(escontext, ErrorSaveContext) && \\\n ^\njsonfuncs.c:2481:23: note: in expansion of macro ‘SOFT_ERROR_OCCURRED’\n return BoolGetDatum(!SOFT_ERROR_OCCURRED(&escontext));\n\nThis was introduced in commit 1edb3b491b, and can be observed on several\nsystems in the buildfarm too, such as:\nhttps://buildfarm.postgresql.org/cgi-bin/show_stage_log.pl?nm=arowana&dt=2024-01-25%2004%3A54%3A38&stg=build\n\nThanks\nRichard\n\nI came across a warning when building master (a044e61f1b) on old GCC(4.8.5).jsonfuncs.c: In function ‘jsonb_populate_record_valid’:../../../../src/include/nodes/miscnodes.h:53:15: warning: the comparison will always evaluate as ‘true’ for the address of ‘escontext’ will never be NULL [-Waddress] ((escontext) != NULL && IsA(escontext, ErrorSaveContext) && \\ ^jsonfuncs.c:2481:23: note: in expansion of macro ‘SOFT_ERROR_OCCURRED’ return BoolGetDatum(!SOFT_ERROR_OCCURRED(&escontext));This was introduced in commit 1edb3b491b, and can be observed on severalsystems in the buildfarm too, such as:https://buildfarm.postgresql.org/cgi-bin/show_stage_log.pl?nm=arowana&dt=2024-01-25%2004%3A54%3A38&stg=buildThanksRichard",
"msg_date": "Thu, 25 Jan 2024 13:59:20 +0800",
"msg_from": "Richard Guo <guofenglinux@gmail.com>",
"msg_from_op": true,
"msg_subject": "A compiling warning in jsonb_populate_record_valid"
},
{
"msg_contents": "Hi,\n\nOn Thu, Jan 25, 2024 at 2:59 PM Richard Guo <guofenglinux@gmail.com> wrote:\n>\n> I came across a warning when building master (a044e61f1b) on old GCC\n> (4.8.5).\n>\n> jsonfuncs.c: In function ‘jsonb_populate_record_valid’:\n> ../../../../src/include/nodes/miscnodes.h:53:15: warning: the comparison will always evaluate as ‘true’ for the address of ‘escontext’ will never be NULL [-Waddress]\n> ((escontext) != NULL && IsA(escontext, ErrorSaveContext) && \\\n> ^\n> jsonfuncs.c:2481:23: note: in expansion of macro ‘SOFT_ERROR_OCCURRED’\n> return BoolGetDatum(!SOFT_ERROR_OCCURRED(&escontext));\n>\n> This was introduced in commit 1edb3b491b, and can be observed on several\n> systems in the buildfarm too, such as:\n> https://buildfarm.postgresql.org/cgi-bin/show_stage_log.pl?nm=arowana&dt=2024-01-25%2004%3A54%3A38&stg=build\n\nThanks for the report.\n\nWill apply the attached, which does this:\n\n- return BoolGetDatum(!SOFT_ERROR_OCCURRED(&escontext));\n+ return BoolGetDatum(!escontext.error_occurred);\n\n-- \nThanks, Amit Langote\nEDB: http://www.enterprisedb.com",
"msg_date": "Thu, 25 Jan 2024 15:28:09 +0900",
"msg_from": "Amit Langote <amitlangote09@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: A compiling warning in jsonb_populate_record_valid"
},
{
"msg_contents": "On Thu, Jan 25, 2024 at 2:28 PM Amit Langote <amitlangote09@gmail.com>\nwrote:\n\n> On Thu, Jan 25, 2024 at 2:59 PM Richard Guo <guofenglinux@gmail.com>\n> wrote:\n> > I came across a warning when building master (a044e61f1b) on old GCC\n> > (4.8.5).\n> >\n> > jsonfuncs.c: In function ‘jsonb_populate_record_valid’:\n> > ../../../../src/include/nodes/miscnodes.h:53:15: warning: the comparison\n> will always evaluate as ‘true’ for the address of ‘escontext’ will never be\n> NULL [-Waddress]\n> > ((escontext) != NULL && IsA(escontext, ErrorSaveContext) && \\\n> > ^\n> > jsonfuncs.c:2481:23: note: in expansion of macro ‘SOFT_ERROR_OCCURRED’\n> > return BoolGetDatum(!SOFT_ERROR_OCCURRED(&escontext));\n> >\n> > This was introduced in commit 1edb3b491b, and can be observed on several\n> > systems in the buildfarm too, such as:\n> >\n> https://buildfarm.postgresql.org/cgi-bin/show_stage_log.pl?nm=arowana&dt=2024-01-25%2004%3A54%3A38&stg=build\n>\n> Thanks for the report.\n>\n> Will apply the attached, which does this:\n>\n> - return BoolGetDatum(!SOFT_ERROR_OCCURRED(&escontext));\n> + return BoolGetDatum(!escontext.error_occurred);\n\n\nLooks good to me.\n\nThanks\nRichard\n\nOn Thu, Jan 25, 2024 at 2:28 PM Amit Langote <amitlangote09@gmail.com> wrote:\nOn Thu, Jan 25, 2024 at 2:59 PM Richard Guo <guofenglinux@gmail.com> wrote:\n> I came across a warning when building master (a044e61f1b) on old GCC\n> (4.8.5).\n>\n> jsonfuncs.c: In function ‘jsonb_populate_record_valid’:\n> ../../../../src/include/nodes/miscnodes.h:53:15: warning: the comparison will always evaluate as ‘true’ for the address of ‘escontext’ will never be NULL [-Waddress]\n> ((escontext) != NULL && IsA(escontext, ErrorSaveContext) && \\\n> ^\n> jsonfuncs.c:2481:23: note: in expansion of macro ‘SOFT_ERROR_OCCURRED’\n> return BoolGetDatum(!SOFT_ERROR_OCCURRED(&escontext));\n>\n> This was introduced in commit 1edb3b491b, and can be observed on several\n> systems in the buildfarm too, such as:\n> https://buildfarm.postgresql.org/cgi-bin/show_stage_log.pl?nm=arowana&dt=2024-01-25%2004%3A54%3A38&stg=build\n\nThanks for the report.\n\nWill apply the attached, which does this:\n\n- return BoolGetDatum(!SOFT_ERROR_OCCURRED(&escontext));\n+ return BoolGetDatum(!escontext.error_occurred);Looks good to me.ThanksRichard",
"msg_date": "Thu, 25 Jan 2024 15:47:04 +0800",
"msg_from": "Richard Guo <guofenglinux@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: A compiling warning in jsonb_populate_record_valid"
},
{
"msg_contents": "On Thu, Jan 25, 2024 at 4:47 PM Richard Guo <guofenglinux@gmail.com> wrote:\n> On Thu, Jan 25, 2024 at 2:28 PM Amit Langote <amitlangote09@gmail.com> wrote:\n>>\n>> On Thu, Jan 25, 2024 at 2:59 PM Richard Guo <guofenglinux@gmail.com> wrote:\n>> > I came across a warning when building master (a044e61f1b) on old GCC\n>> > (4.8.5).\n>> >\n>> > jsonfuncs.c: In function ‘jsonb_populate_record_valid’:\n>> > ../../../../src/include/nodes/miscnodes.h:53:15: warning: the comparison will always evaluate as ‘true’ for the address of ‘escontext’ will never be NULL [-Waddress]\n>> > ((escontext) != NULL && IsA(escontext, ErrorSaveContext) && \\\n>> > ^\n>> > jsonfuncs.c:2481:23: note: in expansion of macro ‘SOFT_ERROR_OCCURRED’\n>> > return BoolGetDatum(!SOFT_ERROR_OCCURRED(&escontext));\n>> >\n>> > This was introduced in commit 1edb3b491b, and can be observed on several\n>> > systems in the buildfarm too, such as:\n>> > https://buildfarm.postgresql.org/cgi-bin/show_stage_log.pl?nm=arowana&dt=2024-01-25%2004%3A54%3A38&stg=build\n>>\n>> Thanks for the report.\n>>\n>> Will apply the attached, which does this:\n>>\n>> - return BoolGetDatum(!SOFT_ERROR_OCCURRED(&escontext));\n>> + return BoolGetDatum(!escontext.error_occurred);\n>\n> Looks good to me.\n\nThanks for checking, pushed.\n\n-- \nThanks, Amit Langote\nEDB: http://www.enterprisedb.com\n\n\n",
"msg_date": "Thu, 25 Jan 2024 17:14:22 +0900",
"msg_from": "Amit Langote <amitlangote09@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: A compiling warning in jsonb_populate_record_valid"
},
{
"msg_contents": "Amit Langote <amitlangote09@gmail.com> writes:\n> On Thu, Jan 25, 2024 at 2:59 PM Richard Guo <guofenglinux@gmail.com> wrote:\n>> I came across a warning when building master (a044e61f1b) on old GCC\n>> (4.8.5).\n\n> Will apply the attached, which does this:\n\n> - return BoolGetDatum(!SOFT_ERROR_OCCURRED(&escontext));\n> + return BoolGetDatum(!escontext.error_occurred);\n\n-1 please. We should not break that abstraction for the sake\nof ignorable warnings on ancient compilers.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Thu, 25 Jan 2024 09:57:32 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: A compiling warning in jsonb_populate_record_valid"
},
{
"msg_contents": "On Thu, Jan 25, 2024 at 23:57 Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Amit Langote <amitlangote09@gmail.com> writes:\n> > On Thu, Jan 25, 2024 at 2:59 PM Richard Guo <guofenglinux@gmail.com>\n> wrote:\n> >> I came across a warning when building master (a044e61f1b) on old GCC\n> >> (4.8.5).\n>\n> > Will apply the attached, which does this:\n>\n> > - return BoolGetDatum(!SOFT_ERROR_OCCURRED(&escontext));\n> > + return BoolGetDatum(!escontext.error_occurred);\n>\n> -1 please. We should not break that abstraction for the sake\n> of ignorable warnings on ancient compilers.\n\n\nIgnoring the warning was my 1st thought too, because an old discussion I\nfound about the warning was too old (2011). The style I adopted in my\n“fix” is used in a few other places too, so I thought I might as well\ngo for it.\n\nAnyway, I’m fine with reverting.\n\n>\n\n On Thu, Jan 25, 2024 at 23:57 Tom Lane <tgl@sss.pgh.pa.us> wrote:Amit Langote <amitlangote09@gmail.com> writes:\n> On Thu, Jan 25, 2024 at 2:59 PM Richard Guo <guofenglinux@gmail.com> wrote:\n>> I came across a warning when building master (a044e61f1b) on old GCC\n>> (4.8.5).\n\n> Will apply the attached, which does this:\n\n> - return BoolGetDatum(!SOFT_ERROR_OCCURRED(&escontext));\n> + return BoolGetDatum(!escontext.error_occurred);\n\n-1 please. We should not break that abstraction for the sake\nof ignorable warnings on ancient compilers.Ignoring the warning was my 1st thought too, because an old discussion I found about the warning was too old (2011). The style I adopted in my “fix” is used in a few other places too, so I thought I might as well go for it.Anyway, I’m fine with reverting.",
"msg_date": "Fri, 26 Jan 2024 00:12:58 +0900",
"msg_from": "Amit Langote <amitlangote09@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: A compiling warning in jsonb_populate_record_valid"
},
{
"msg_contents": "Amit Langote <amitlangote09@gmail.com> writes:\n> On Thu, Jan 25, 2024 at 23:57 Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> -1 please. We should not break that abstraction for the sake\n>> of ignorable warnings on ancient compilers.\n\n> Ignoring the warning was my 1st thought too, because an old discussion I\n> found about the warning was too old (2011). The style I adopted in my\n> “fix” is used in a few other places too, so I thought I might as well\n> go for it.\n\nOh, well maybe I'm missing some context. What comparable places did\nyou see?\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Thu, 25 Jan 2024 10:15:34 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: A compiling warning in jsonb_populate_record_valid"
},
{
"msg_contents": "On Fri, Jan 26, 2024 at 0:15 Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Amit Langote <amitlangote09@gmail.com> writes:\n> > On Thu, Jan 25, 2024 at 23:57 Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >> -1 please. We should not break that abstraction for the sake\n> >> of ignorable warnings on ancient compilers.\n>\n> > Ignoring the warning was my 1st thought too, because an old discussion I\n> > found about the warning was too old (2011). The style I adopted in my\n> > “fix” is used in a few other places too, so I thought I might as well\n> > go for it.\n>\n> Oh, well maybe I'm missing some context. What comparable places did\n> you see?\n\n\nSorry, not on my computer right now so can’t paste any code, but I was able\nto find a couple of functions (using Google ;) that refer to error_occurred\ndirectly for one reason or another:\n\nprocess_integer_literal(),\nxml_is_document()\n\nOn Fri, Jan 26, 2024 at 0:15 Tom Lane <tgl@sss.pgh.pa.us> wrote:Amit Langote <amitlangote09@gmail.com> writes:\n> On Thu, Jan 25, 2024 at 23:57 Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> -1 please. We should not break that abstraction for the sake\n>> of ignorable warnings on ancient compilers.\n\n> Ignoring the warning was my 1st thought too, because an old discussion I\n> found about the warning was too old (2011). The style I adopted in my\n> “fix” is used in a few other places too, so I thought I might as well\n> go for it.\n\nOh, well maybe I'm missing some context. What comparable places did\nyou see?Sorry, not on my computer right now so can’t paste any code, but I was able to find a couple of functions (using Google ;) that refer to error_occurred directly for one reason or another:process_integer_literal(),xml_is_document()",
"msg_date": "Fri, 26 Jan 2024 00:28:06 +0900",
"msg_from": "Amit Langote <amitlangote09@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: A compiling warning in jsonb_populate_record_valid"
},
{
"msg_contents": "Amit Langote <amitlangote09@gmail.com> writes:\n> On Fri, Jan 26, 2024 at 0:15 Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Amit Langote <amitlangote09@gmail.com> writes:\n>>> Ignoring the warning was my 1st thought too, because an old discussion I\n>>> found about the warning was too old (2011). The style I adopted in my\n>>> “fix” is used in a few other places too, so I thought I might as well\n>>> go for it.\n\n>> Oh, well maybe I'm missing some context. What comparable places did\n>> you see?\n\n> Sorry, not on my computer right now so can’t paste any code, but I was able\n> to find a couple of functions (using Google ;) that refer to error_occurred\n> directly for one reason or another:\n\nOK, looking around, it seems like our pattern is that direct access\nto escontext.error_occurred is okay in the same function that sets up\nthe escontext (so that there's no possibility of a NULL pointer).\nSo this change is fine and I withdraw my objection. Sorry for\nthe noise.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Thu, 25 Jan 2024 10:48:25 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: A compiling warning in jsonb_populate_record_valid"
}
] |
[
{
"msg_contents": "Hi,\n\nIn the function ReplicationSlotAcquire(), I found there is a missing in the\nbelow comments:\n\n```\n\t/*\n\t * Search for the slot with the specified name if the slot to acquire is\n\t * not given. If the slot is not found, we either return -1 or error out.\n\t */\n\ts = SearchNamedReplicationSlot(name, false);\n\tif (s == NULL || !s->in_use)\n\t{\n\t\tLWLockRelease(ReplicationSlotControlLock);\n\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_UNDEFINED_OBJECT),\n\t\t\t\t errmsg(\"replication slot \\\"%s\\\" does not exist\",\n\t\t\t\t\t\tname)));\n\t}\n```\n\nIt seems that when the slot is not found, we will only error out and will not\nreturn -1. Attach the patch to remove the inappropriate description of return\nvalue.\n\nRegards,\nWang Wei",
"msg_date": "Thu, 25 Jan 2024 09:26:42 +0000",
"msg_from": "\"Wei Wang (Fujitsu)\" <wangw.fnst@fujitsu.com>",
"msg_from_op": true,
"msg_subject": "Fix inappropriate comments in function ReplicationSlotAcquire"
},
{
"msg_contents": "On Thu, Jan 25, 2024 at 2:57 PM Wei Wang (Fujitsu)\n<wangw.fnst@fujitsu.com> wrote:\n>\n> In the function ReplicationSlotAcquire(), I found there is a missing in the\n> below comments:\n>\n> ```\n> /*\n> * Search for the slot with the specified name if the slot to acquire is\n> * not given. If the slot is not found, we either return -1 or error out.\n> */\n> s = SearchNamedReplicationSlot(name, false);\n> if (s == NULL || !s->in_use)\n> {\n> LWLockRelease(ReplicationSlotControlLock);\n>\n> ereport(ERROR,\n> (errcode(ERRCODE_UNDEFINED_OBJECT),\n> errmsg(\"replication slot \\\"%s\\\" does not exist\",\n> name)));\n> }\n> ```\n>\n> It seems that when the slot is not found, we will only error out and will not\n> return -1.\n>\n\nYou seem to be correct. However, isn't the first part of the comment\nalso slightly confusing? In particular, \"... if the slot to acquire is\nnot given.\" In this function, I don't see the case where a slot to\nacquire is given.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Thu, 25 Jan 2024 15:09:11 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix inappropriate comments in function ReplicationSlotAcquire"
},
{
"msg_contents": "On Thu, Jan 25, 2024 at 18:39 Amit Kapila <amit.kapila16@gmail.com> wrote:\r\n>\r\n\r\nThanks for your review.\r\n\r\n> On Thu, Jan 25, 2024 at 2:57 PM Wei Wang (Fujitsu)\r\n> <wangw.fnst@fujitsu.com> wrote:\r\n> >\r\n> > In the function ReplicationSlotAcquire(), I found there is a missing in the\r\n> > below comments:\r\n> >\r\n> > ```\r\n> > /*\r\n> > * Search for the slot with the specified name if the slot to acquire is\r\n> > * not given. If the slot is not found, we either return -1 or error out.\r\n> > */\r\n> > s = SearchNamedReplicationSlot(name, false);\r\n> > if (s == NULL || !s->in_use)\r\n> > {\r\n> > LWLockRelease(ReplicationSlotControlLock);\r\n> >\r\n> > ereport(ERROR,\r\n> > (errcode(ERRCODE_UNDEFINED_OBJECT),\r\n> > errmsg(\"replication slot \\\"%s\\\" does not\r\n> exist\",\r\n> > name)));\r\n> > }\r\n> > ```\r\n> >\r\n> > It seems that when the slot is not found, we will only error out and will not\r\n> > return -1.\r\n> >\r\n> \r\n> You seem to be correct. However, isn't the first part of the comment\r\n> also slightly confusing? In particular, \"... if the slot to acquire is\r\n> not given.\" In this function, I don't see the case where a slot to\r\n> acquire is given.\r\n\r\nYes, agree. I think these two parts have become slightly outdated after the\r\ncommit 1632ea4. So also tried to fix the first part of the comment.\r\nAttach the new patch.\r\n\r\nRegards,\r\nWang Wei",
"msg_date": "Thu, 25 Jan 2024 10:30:55 +0000",
"msg_from": "\"Wei Wang (Fujitsu)\" <wangw.fnst@fujitsu.com>",
"msg_from_op": true,
"msg_subject": "RE: Fix inappropriate comments in function ReplicationSlotAcquire"
},
{
"msg_contents": "On Thu, Jan 25, 2024 at 4:01 PM Wei Wang (Fujitsu)\n<wangw.fnst@fujitsu.com> wrote:\n>\n>\n> Yes, agree. I think these two parts have become slightly outdated after the\n> commit 1632ea4. So also tried to fix the first part of the comment.\n> Attach the new patch.\n>\n\nHow about changing it to something simple like:\ndiff --git a/src/backend/replication/slot.c b/src/backend/replication/slot.c\nindex f2781d0455..84c257a7aa 100644\n--- a/src/backend/replication/slot.c\n+++ b/src/backend/replication/slot.c\n@@ -465,10 +465,7 @@ retry:\n\n LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);\n\n- /*\n- * Search for the slot with the specified name if the slot to acquire is\n- * not given. If the slot is not found, we either return -1 or\nerror out.\n- */\n+ /* Check if the slot exits with the given name. */\n s = SearchNamedReplicationSlot(name, false);\n if (s == NULL || !s->in_use)\n {\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Thu, 25 Jan 2024 17:02:34 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix inappropriate comments in function ReplicationSlotAcquire"
},
{
"msg_contents": "On Thu, Jan 25, 2024 at 20:33 Amit Kapila <amit.kapila16@gmail.com> wrote:\r\n> On Thu, Jan 25, 2024 at 4:01 PM Wei Wang (Fujitsu)\r\n> <wangw.fnst@fujitsu.com> wrote:\r\n> >\r\n> >\r\n> > Yes, agree. I think these two parts have become slightly outdated after the\r\n> > commit 1632ea4. So also tried to fix the first part of the comment.\r\n> > Attach the new patch.\r\n> >\r\n> \r\n> How about changing it to something simple like:\r\n> diff --git a/src/backend/replication/slot.c b/src/backend/replication/slot.c\r\n> index f2781d0455..84c257a7aa 100644\r\n> --- a/src/backend/replication/slot.c\r\n> +++ b/src/backend/replication/slot.c\r\n> @@ -465,10 +465,7 @@ retry:\r\n> \r\n> LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);\r\n> \r\n> - /*\r\n> - * Search for the slot with the specified name if the slot to acquire is\r\n> - * not given. If the slot is not found, we either return -1 or\r\n> error out.\r\n> - */\r\n> + /* Check if the slot exits with the given name. */\r\n> s = SearchNamedReplicationSlot(name, false);\r\n> if (s == NULL || !s->in_use)\r\n> {\r\n\r\nIt looks good to me. So, I updated the patch as suggested.\r\n\r\nRegards,\r\nWang Wei",
"msg_date": "Fri, 26 Jan 2024 01:17:06 +0000",
"msg_from": "\"Wei Wang (Fujitsu)\" <wangw.fnst@fujitsu.com>",
"msg_from_op": true,
"msg_subject": "RE: Fix inappropriate comments in function ReplicationSlotAcquire"
},
{
"msg_contents": "On Fri, Jan 26, 2024 at 6:47 AM Wei Wang (Fujitsu)\n<wangw.fnst@fujitsu.com> wrote:\n>\n> It looks good to me. So, I updated the patch as suggested.\n>\n\nPushed!\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Mon, 29 Jan 2024 11:19:51 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix inappropriate comments in function ReplicationSlotAcquire"
},
{
"msg_contents": "On Mon, Jan 29, 2024 at 14:50 Amit Kapila <amit.kapila16@gmail.com> wrote:\r\n> Pushed!\r\n\r\nThanks for pushing.\r\n\r\nRegards,\r\nWang Wei\r\n",
"msg_date": "Mon, 29 Jan 2024 07:35:35 +0000",
"msg_from": "\"Wei Wang (Fujitsu)\" <wangw.fnst@fujitsu.com>",
"msg_from_op": true,
"msg_subject": "RE: Fix inappropriate comments in function ReplicationSlotAcquire"
}
] |
[
{
"msg_contents": "Hi,\n\nAs described in 9e2d870119, COPY ON_EEOR is expected to have more \n\"error_action\".\n(Note that option name was changed by b725b7eec)\n\nI'd like to have a new option \"log\", which skips soft errors and logs \ninformation that should have resulted in errors to PostgreSQL log.\n\nI think this option has some advantages like below:\n\n1) We can know which number of line input data was not loaded and \nreason.\n\n Example:\n\n =# copy t1 from stdin with (on_error log);\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 \nsignal.\n >> 1\n >> 2\n >> 3\n >> z\n >> \\.\n LOG: invalid input syntax for type integer: \"z\"\n NOTICE: 1 row was skipped due to data type incompatibility\n COPY 3\n\n =# \\! tail data/log/postgresql*.log\n LOG: 22P02: invalid input syntax for type integer: \"z\"\n CONTEXT: COPY t1, line 4, column i: \"z\"\n LOCATION: pg_strtoint32_safe, numutils.c:620\n STATEMENT: copy t1 from stdin with (on_error log);\n\n\n2) Easier maintenance than storing error information in tables or \nproprietary log files.\nFor example, in case a large number of soft errors occur, some \nmechanisms are needed to prevent an infinite increase in the size of the \ndestination data, but we can left it to PostgreSQL's log rotation.\n\n\nAttached a patch.\nThis basically comes from previous discussion[1] which did both \"ignore\" \nand \"log\" soft error.\n\nAs shown in the example above, the log output to the client does not \ncontain CONTEXT, so I'm a little concerned that client cannot see what \nline of the input data had a problem without looking at the server log.\n\n\nWhat do you think?\n\n[1] \nhttps://www.postgresql.org/message-id/c0fb57b82b150953f26a5c7e340412e8%40oss.nttdata.com\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation",
"msg_date": "Fri, 26 Jan 2024 01:42:14 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Fri, Jan 26, 2024 at 12:42 AM torikoshia <torikoshia@oss.nttdata.com> wrote:\n>\n> Hi,\n>\n> As described in 9e2d870119, COPY ON_EEOR is expected to have more\n> \"error_action\".\n> (Note that option name was changed by b725b7eec)\n>\n> I'd like to have a new option \"log\", which skips soft errors and logs\n> information that should have resulted in errors to PostgreSQL log.\n>\n> I think this option has some advantages like below:\n>\n> 1) We can know which number of line input data was not loaded and\n> reason.\n>\n> Example:\n>\n> =# copy t1 from stdin with (on_error log);\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\n> signal.\n> >> 1\n> >> 2\n> >> 3\n> >> z\n> >> \\.\n> LOG: invalid input syntax for type integer: \"z\"\n> NOTICE: 1 row was skipped due to data type incompatibility\n> COPY 3\n>\n> =# \\! tail data/log/postgresql*.log\n> LOG: 22P02: invalid input syntax for type integer: \"z\"\n> CONTEXT: COPY t1, line 4, column i: \"z\"\n> LOCATION: pg_strtoint32_safe, numutils.c:620\n> STATEMENT: copy t1 from stdin with (on_error log);\n>\n>\n> 2) Easier maintenance than storing error information in tables or\n> proprietary log files.\n> For example, in case a large number of soft errors occur, some\n> mechanisms are needed to prevent an infinite increase in the size of the\n> destination data, but we can left it to PostgreSQL's log rotation.\n>\n>\n> Attached a patch.\n> This basically comes from previous discussion[1] which did both \"ignore\"\n> and \"log\" soft error.\n>\n> As shown in the example above, the log output to the client does not\n> contain CONTEXT, so I'm a little concerned that client cannot see what\n> line of the input data had a problem without looking at the server log.\n>\n>\n> What do you think?\n>\n\nI doubt the following part:\n If the <literal>log</literal> value is specified,\n <command>COPY</command> behaves the same as\n<literal>ignore</literal>, exept that\n it logs information that should have resulted in errors to\nPostgreSQL log at\n <literal>INFO</literal> level.\n\nI think it does something like:\nWhen an error happens, cstate->escontext->error_data->elevel will be ERROR\nyou manually change the cstate->escontext->error_data->elevel to LOG,\nthen you call ThrowErrorData.\n\nbut it's not related to `<literal>INFO</literal> level`?\nmy log_min_messages is default, warning.\n\n\n",
"msg_date": "Fri, 26 Jan 2024 21:44:34 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Thu, Jan 25, 2024 at 9:42 AM torikoshia <torikoshia@oss.nttdata.com>\nwrote:\n\n> Hi,\n>\n> As described in 9e2d870119, COPY ON_EEOR is expected to have more\n> \"error_action\".\n> (Note that option name was changed by b725b7eec)\n>\n> I'd like to have a new option \"log\", which skips soft errors and logs\n> information that should have resulted in errors to PostgreSQL log.\n>\n>\nSeems like an easy win but largely unhelpful in the typical case. I\nsuppose ETL routines using this feature may be running on their machine\nunder root or \"postgres\" but in a system where they are not this very\nuseful information is inaccessible to them. I suppose the DBA could set up\nan extractor to send these specific log lines elsewhere but that seems like\nenough hassle to disfavor this approach and favor one that can place the\nsoft error data and feedback into user-specified tables in the same\ndatabase. Setting up temporary tables or unlogged tables probably is going\nto be a more acceptable methodology than trying to get to the log files.\n\nDavid J.\n\nOn Thu, Jan 25, 2024 at 9:42 AM torikoshia <torikoshia@oss.nttdata.com> wrote:Hi,\n\nAs described in 9e2d870119, COPY ON_EEOR is expected to have more \n\"error_action\".\n(Note that option name was changed by b725b7eec)\n\nI'd like to have a new option \"log\", which skips soft errors and logs \ninformation that should have resulted in errors to PostgreSQL log.Seems like an easy win but largely unhelpful in the typical case. I suppose ETL routines using this feature may be running on their machine under root or \"postgres\" but in a system where they are not this very useful information is inaccessible to them. I suppose the DBA could set up an extractor to send these specific log lines elsewhere but that seems like enough hassle to disfavor this approach and favor one that can place the soft error data and feedback into user-specified tables in the same database. Setting up temporary tables or unlogged tables probably is going to be a more acceptable methodology than trying to get to the log files.David J.",
"msg_date": "Fri, 26 Jan 2024 08:43:13 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Fri, Jan 26, 2024 at 10:44 PM jian he <jian.universality@gmail.com> \nwrote:\n\n> I doubt the following part:\n> If the <literal>log</literal> value is specified,\n> <command>COPY</command> behaves the same as\n> <literal>ignore</literal>, exept that\n> it logs information that should have resulted in errors to\n> PostgreSQL log at\n> <literal>INFO</literal> level.\n> \n> I think it does something like:\n> When an error happens, cstate->escontext->error_data->elevel will be \n> ERROR\n> you manually change the cstate->escontext->error_data->elevel to LOG,\n> then you call ThrowErrorData.\n> \n> but it's not related to `<literal>INFO</literal> level`?\n> my log_min_messages is default, warning.\n\nThanks!\n\nModified them to NOTICE in accordance with the following summary \nmessage:\n> NOTICE: x row was skipped due to data type incompatibility\n\n\nOn 2024-01-27 00:43, David G. Johnston wrote:\n> On Thu, Jan 25, 2024 at 9:42 AM torikoshia\n> <torikoshia@oss.nttdata.com> wrote:\n> \n>> Hi,\n>> \n>> As described in 9e2d870119, COPY ON_EEOR is expected to have more\n>> \"error_action\".\n>> (Note that option name was changed by b725b7eec)\n>> \n>> I'd like to have a new option \"log\", which skips soft errors and\n>> logs\n>> information that should have resulted in errors to PostgreSQL log.\n> \n> Seems like an easy win but largely unhelpful in the typical case. I\n> suppose ETL routines using this feature may be running on their\n> machine under root or \"postgres\" but in a system where they are not\n> this very useful information is inaccessible to them. I suppose the\n> DBA could set up an extractor to send these specific log lines\n> elsewhere but that seems like enough hassle to disfavor this approach\n> and favor one that can place the soft error data and feedback into\n> user-specified tables in the same database. Setting up temporary\n> tables or unlogged tables probably is going to be a more acceptable\n> methodology than trying to get to the log files.\n> \n> David J.\n\nI agree that not a few people would prefer to store error information in \ntables and there have already been suggestions[1].\n\nOTOH not everyone thinks saving table information is the best idea[2].\n\nI think it would be desirable for ON_ERROR to be in a form that allows \nthe user to choose where to store error information from among some \noptions, such as table, log and file.\n\n\"ON_ERROR log\" would be useful at least in the case of 'running on their \nmachine under root or \"postgres\"' as you pointed out.\n\n\n[1] \nhttps://www.postgresql.org/message-id/CACJufxEkkqnozdnvNMGxVAA94KZaCPkYw_Cx4JKG9ueNaZma_A%40mail.gmail.com\n\n[2] \nhttps://www.postgresql.org/message-id/20231109002600.fuihn34bjqqgmbjm@awork3.anarazel.de\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation",
"msg_date": "Mon, 29 Jan 2024 12:11:34 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Mon, Jan 29, 2024 at 8:41 AM torikoshia <torikoshia@oss.nttdata.com> wrote:\n>\n> On 2024-01-27 00:43, David G. Johnston wrote:\n>\n> >> I'd like to have a new option \"log\", which skips soft errors and\n> >> logs\n> >> information that should have resulted in errors to PostgreSQL log.\n> >\n> > user-specified tables in the same database. Setting up temporary\n> > tables or unlogged tables probably is going to be a more acceptable\n> > methodology than trying to get to the log files.\n>\n> OTOH not everyone thinks saving table information is the best idea[2].\n\nThe added NOTICE message gives a summary of how many rows were\nskipped, but not the line numbers. It's hard for the users to find the\nmalformed data, especially when they are bulk-inserting from data\nfiles of multiple GBs in size (hard to open such files in any editor\ntoo).\n\nI understand the value of writing the info to server log or tables of\nusers' choice as being discussed in a couple of other threads.\nHowever, I'd prefer we do the simplest thing first before we go debate\nserver log or table - let the users know what line numbers are\ncontaining the errors that COPY ignored something like [1] with a\nsimple change like [2]. It not only helps users figure out which rows\nand attributes were malformed, but also helps them redirect them to\nserver logs with setting log_min_messages = notice [3]. In the worst\ncase scenario, a problem with this one NOTICE per malformed row is\nthat it can overload the psql session if all the rows are malformed.\nI'm not sure if this is a big problem, but IMO better than a single\nsummary NOTICE message and simpler than writing to tables of users'\nchoice.\n\nThoughts?\n\nFWIW, I presented the new COPY ... ON_ERROR option feature at\nHyderabad PostgreSQL User Group meetup and it was well-received by the\naudience. The audience felt it's going to be extremely helpful for\nbulk-loading tasks. Thank you all for working on this feature.\n\n[1]\npostgres=# CREATE TABLE check_ign_err (n int, m int[], k int);\nCREATE TABLE\npostgres=# COPY check_ign_err FROM STDIN WITH (on_error ignore);\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>> 1 {1} 1\na {2} 2\n3 {3} 3333333333\n4 {a, 4} 4\n\n5 {5}>> >> >> >> >> 5\n\\.>>\nNOTICE: detected data type incompatibility at line number 2 for\ncolumn check_ign_err, COPY n\nNOTICE: detected data type incompatibility at line number 3 for\ncolumn check_ign_err, COPY k\nNOTICE: detected data type incompatibility at line number 4 for\ncolumn check_ign_err, COPY m\nNOTICE: detected data type incompatibility at line number 5 for\ncolumn check_ign_err, COPY n\nNOTICE: 4 rows were skipped due to data type incompatibility\nCOPY 2\n\n[2]\ndiff --git a/src/backend/commands/copyfromparse.c\nb/src/backend/commands/copyfromparse.c\nindex 906756362e..93ab5d4ebb 100644\n--- a/src/backend/commands/copyfromparse.c\n+++ b/src/backend/commands/copyfromparse.c\n@@ -961,7 +961,16 @@ NextCopyFrom(CopyFromState cstate, ExprContext *econtext,\n\n &values[m]))\n {\n cstate->num_errors++;\n- return true;\n+\n+ if (cstate->opts.on_error != COPY_ON_ERROR_STOP)\n+ {\n+ ereport(NOTICE,\n+\nerrmsg(\"detected data type incompatibility at line number %llu for\ncolumn %s, COPY %s\",\n+\n(unsigned long long) cstate->cur_lineno,\n+\ncstate->cur_relname,\n+\ncstate->cur_attname));\n+ return true;\n+ }\n }\n\n cstate->cur_attname = NULL;\n\n[3]\n2024-02-12 06:20:29.363 UTC [427892] NOTICE: detected data type\nincompatibility at line number 2 for column check_ign_err, COPY n\n2024-02-12 06:20:29.363 UTC [427892] CONTEXT: COPY check_ign_err,\nline 2, column n: \"a\"\n2024-02-12 06:20:29.363 UTC [427892] NOTICE: detected data type\nincompatibility at line number 3 for column check_ign_err, COPY k\n2024-02-12 06:20:29.363 UTC [427892] CONTEXT: COPY check_ign_err,\nline 3, column k: \"3333333333\"\n2024-02-12 06:20:29.363 UTC [427892] NOTICE: detected data type\nincompatibility at line number 4 for column check_ign_err, COPY m\n2024-02-12 06:20:29.363 UTC [427892] CONTEXT: COPY check_ign_err,\nline 4, column m: \"{a, 4}\"\n2024-02-12 06:20:29.363 UTC [427892] NOTICE: detected data type\nincompatibility at line number 5 for column check_ign_err, COPY n\n2024-02-12 06:20:29.363 UTC [427892] CONTEXT: COPY check_ign_err,\nline 5, column n: \"\"\n2024-02-12 06:20:29.363 UTC [427892] NOTICE: 4 rows were skipped due\nto data type incompatibility\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Mon, 12 Feb 2024 12:16:41 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On 2024-02-12 15:46, Bharath Rupireddy wrote:\n\nThanks for your comments.\n\n> On Mon, Jan 29, 2024 at 8:41 AM torikoshia <torikoshia@oss.nttdata.com> \n> wrote:\n>> \n>> On 2024-01-27 00:43, David G. Johnston wrote:\n>> \n>> >> I'd like to have a new option \"log\", which skips soft errors and\n>> >> logs\n>> >> information that should have resulted in errors to PostgreSQL log.\n>> >\n>> > user-specified tables in the same database. Setting up temporary\n>> > tables or unlogged tables probably is going to be a more acceptable\n>> > methodology than trying to get to the log files.\n>> \n>> OTOH not everyone thinks saving table information is the best idea[2].\n> \n> The added NOTICE message gives a summary of how many rows were\n> skipped, but not the line numbers. It's hard for the users to find the\n> malformed data, especially when they are bulk-inserting from data\n> files of multiple GBs in size (hard to open such files in any editor\n> too).\n> \n> I understand the value of writing the info to server log or tables of\n> users' choice as being discussed in a couple of other threads.\n> However, I'd prefer we do the simplest thing first before we go debate\n> server log or table - let the users know what line numbers are\n> containing the errors that COPY ignored something like [1] with a\n> simple change like [2].\n\nAgreed.\nUnlike my patch, it hides the error information(i.e. 22P02: invalid \ninput syntax for type integer: ), but I feel that it's usually \nsufficient to know the row number and column where the error occurred.\n\n> It not only helps users figure out which rows\n> and attributes were malformed, but also helps them redirect them to\n> server logs with setting log_min_messages = notice [3]. In the worst\n> case scenario, a problem with this one NOTICE per malformed row is\n> that it can overload the psql session if all the rows are malformed.\n> I'm not sure if this is a big problem, but IMO better than a single\n> summary NOTICE message and simpler than writing to tables of users'\n> choice.\n\nMaybe could we do what you suggested for the behavior when 'log' is set \nto on_error?\n\n> Thoughts?\n> \n> FWIW, I presented the new COPY ... ON_ERROR option feature at\n> Hyderabad PostgreSQL User Group meetup and it was well-received by the\n> audience. The audience felt it's going to be extremely helpful for\n> bulk-loading tasks. Thank you all for working on this feature.\n\nThanks for informing it!\nI hope it will not be reverted as the audience:)\n\n> [1]\n> postgres=# CREATE TABLE check_ign_err (n int, m int[], k int);\n> CREATE TABLE\n> postgres=# COPY check_ign_err FROM STDIN WITH (on_error ignore);\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 \n> signal.\n>>> 1 {1} 1\n> a {2} 2\n> 3 {3} 3333333333\n> 4 {a, 4} 4\n> \n> 5 {5}>> >> >> >> >> 5\n> \\.>>\n> NOTICE: detected data type incompatibility at line number 2 for\n> column check_ign_err, COPY n\n> NOTICE: detected data type incompatibility at line number 3 for\n> column check_ign_err, COPY k\n> NOTICE: detected data type incompatibility at line number 4 for\n> column check_ign_err, COPY m\n> NOTICE: detected data type incompatibility at line number 5 for\n> column check_ign_err, COPY n\n> NOTICE: 4 rows were skipped due to data type incompatibility\n> COPY 2\n> \n> [2]\n> diff --git a/src/backend/commands/copyfromparse.c\n> b/src/backend/commands/copyfromparse.c\n> index 906756362e..93ab5d4ebb 100644\n> --- a/src/backend/commands/copyfromparse.c\n> +++ b/src/backend/commands/copyfromparse.c\n> @@ -961,7 +961,16 @@ NextCopyFrom(CopyFromState cstate, ExprContext \n> *econtext,\n> \n> &values[m]))\n> {\n> cstate->num_errors++;\n> - return true;\n> +\n> + if (cstate->opts.on_error != \n> COPY_ON_ERROR_STOP)\n> + {\n> + ereport(NOTICE,\n> +\n> errmsg(\"detected data type incompatibility at line number %llu for\n> column %s, COPY %s\",\n> +\n> (unsigned long long) cstate->cur_lineno,\n> +\n> cstate->cur_relname,\n> +\n> cstate->cur_attname));\n> + return true;\n> + }\n> }\n> \n> cstate->cur_attname = NULL;\n> \n> [3]\n> 2024-02-12 06:20:29.363 UTC [427892] NOTICE: detected data type\n> incompatibility at line number 2 for column check_ign_err, COPY n\n> 2024-02-12 06:20:29.363 UTC [427892] CONTEXT: COPY check_ign_err,\n> line 2, column n: \"a\"\n> 2024-02-12 06:20:29.363 UTC [427892] NOTICE: detected data type\n> incompatibility at line number 3 for column check_ign_err, COPY k\n> 2024-02-12 06:20:29.363 UTC [427892] CONTEXT: COPY check_ign_err,\n> line 3, column k: \"3333333333\"\n> 2024-02-12 06:20:29.363 UTC [427892] NOTICE: detected data type\n> incompatibility at line number 4 for column check_ign_err, COPY m\n> 2024-02-12 06:20:29.363 UTC [427892] CONTEXT: COPY check_ign_err,\n> line 4, column m: \"{a, 4}\"\n> 2024-02-12 06:20:29.363 UTC [427892] NOTICE: detected data type\n> incompatibility at line number 5 for column check_ign_err, COPY n\n> 2024-02-12 06:20:29.363 UTC [427892] CONTEXT: COPY check_ign_err,\n> line 5, column n: \"\"\n> 2024-02-12 06:20:29.363 UTC [427892] NOTICE: 4 rows were skipped due\n> to data type incompatibility\n> \n> --\n> Bharath Rupireddy\n> PostgreSQL Contributors Team\n> RDS Open Source Databases\n> Amazon Web Services: https://aws.amazon.com\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Wed, 14 Feb 2024 20:34:01 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Wed, Feb 14, 2024 at 5:04 PM torikoshia <torikoshia@oss.nttdata.com> wrote:\n>\n> [....] let the users know what line numbers are\n> > containing the errors that COPY ignored something like [1] with a\n> > simple change like [2].\n>\n> Agreed.\n> Unlike my patch, it hides the error information(i.e. 22P02: invalid\n> input syntax for type integer: ), but I feel that it's usually\n> sufficient to know the row number and column where the error occurred.\n\nRight.\n\n> > It not only helps users figure out which rows\n> > and attributes were malformed, but also helps them redirect them to\n> > server logs with setting log_min_messages = notice [3]. In the worst\n> > case scenario, a problem with this one NOTICE per malformed row is\n> > that it can overload the psql session if all the rows are malformed.\n> > I'm not sure if this is a big problem, but IMO better than a single\n> > summary NOTICE message and simpler than writing to tables of users'\n> > choice.\n>\n> Maybe could we do what you suggested for the behavior when 'log' is set\n> to on_error?\n\n My point is that why someone wants just the summary of failures\nwithout row and column info especially for bulk loading tasks. I'd\nsuggest doing it independently of 'log' or 'table'. I think we can\nkeep things simple just like the attached patch, and see how this\nfeature will be adopted. I'm sure we can come back and do things like\nsaving to 'log' or 'table' or 'separate_error_file' etc., if we\nreceive any firsthand feedback.\n\nThoughts?\n\n-- \nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Fri, 16 Feb 2024 13:45:00 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On 2024-02-16 17:15, Bharath Rupireddy wrote:\n> On Wed, Feb 14, 2024 at 5:04 PM torikoshia <torikoshia@oss.nttdata.com> \n> wrote:\n>> \n>> [....] let the users know what line numbers are\n>> > containing the errors that COPY ignored something like [1] with a\n>> > simple change like [2].\n>> \n>> Agreed.\n>> Unlike my patch, it hides the error information(i.e. 22P02: invalid\n>> input syntax for type integer: ), but I feel that it's usually\n>> sufficient to know the row number and column where the error occurred.\n> \n> Right.\n> \n>> > It not only helps users figure out which rows\n>> > and attributes were malformed, but also helps them redirect them to\n>> > server logs with setting log_min_messages = notice [3]. In the worst\n>> > case scenario, a problem with this one NOTICE per malformed row is\n>> > that it can overload the psql session if all the rows are malformed.\n>> > I'm not sure if this is a big problem, but IMO better than a single\n>> > summary NOTICE message and simpler than writing to tables of users'\n>> > choice.\n>> \n>> Maybe could we do what you suggested for the behavior when 'log' is \n>> set\n>> to on_error?\n> \n> My point is that why someone wants just the summary of failures\n> without row and column info especially for bulk loading tasks. I'd\n> suggest doing it independently of 'log' or 'table'. I think we can\n> keep things simple just like the attached patch, and see how this\n> feature will be adopted. I'm sure we can come back and do things like\n> saving to 'log' or 'table' or 'separate_error_file' etc., if we\n> receive any firsthand feedback.\n> \n> Thoughts?\n\nI may be wrong since I seldom do data loading tasks, but I greed with \nyou.\n\nI also a little concerned about the case where there are many malformed \ndata and it causes lots of messages, but the information is usually \nvaluable and if users don't need it, they can suppress it by changing \nclient_min_messages.\n\nCurrently both summary of failures and individual information is logged \nin NOTICE level.\nIf we should assume that there are cases where only summary information \nis required, it'd be useful to set lower log level, i.e. LOG to the \nindividual information.\n\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Fri, 16 Feb 2024 23:47:43 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Fri, Feb 16, 2024 at 8:17 PM torikoshia <torikoshia@oss.nttdata.com> wrote:\n>\n> I may be wrong since I seldom do data loading tasks, but I greed with\n> you.\n>\n> I also a little concerned about the case where there are many malformed\n> data and it causes lots of messages, but the information is usually\n> valuable and if users don't need it, they can suppress it by changing\n> client_min_messages.\n>\n> Currently both summary of failures and individual information is logged\n> in NOTICE level.\n> If we should assume that there are cases where only summary information\n> is required, it'd be useful to set lower log level, i.e. LOG to the\n> individual information.\n\nHow about we emit the summary at INFO level and individual information\nat NOTICE level? With this, the summary is given a different priority\nthan the individual info. With SET client_min_messages = WARNING; one\ncan still get the summary but not the individual info. Also, to get\nall of these into server log, one can SET log_min_messages = INFO; or\nSET log_min_messages = NOTICE;.\n\nThoughts?\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Sat, 17 Feb 2024 11:30:00 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On 2024-02-17 15:00, Bharath Rupireddy wrote:\n> On Fri, Feb 16, 2024 at 8:17 PM torikoshia <torikoshia@oss.nttdata.com> \n> wrote:\n>> \n>> I may be wrong since I seldom do data loading tasks, but I greed with\n>> you.\n>> \n>> I also a little concerned about the case where there are many \n>> malformed\n>> data and it causes lots of messages, but the information is usually\n>> valuable and if users don't need it, they can suppress it by changing\n>> client_min_messages.\n>> \n>> Currently both summary of failures and individual information is \n>> logged\n>> in NOTICE level.\n>> If we should assume that there are cases where only summary \n>> information\n>> is required, it'd be useful to set lower log level, i.e. LOG to the\n>> individual information.\n> \n> How about we emit the summary at INFO level and individual information\n> at NOTICE level? With this, the summary is given a different priority\n> than the individual info. With SET client_min_messages = WARNING; one\n> can still get the summary but not the individual info. Also, to get\n> all of these into server log, one can SET log_min_messages = INFO; or\n> SET log_min_messages = NOTICE;.\n> \n> Thoughts?\n\nIt looks good to me.\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Tue, 20 Feb 2024 17:22:58 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On 2024-02-20 17:22, torikoshia wrote:\n> On 2024-02-17 15:00, Bharath Rupireddy wrote:\n>> On Fri, Feb 16, 2024 at 8:17 PM torikoshia \n>> <torikoshia@oss.nttdata.com> wrote:\n>>> \n>>> I may be wrong since I seldom do data loading tasks, but I greed with\n>>> you.\n>>> \n>>> I also a little concerned about the case where there are many \n>>> malformed\n>>> data and it causes lots of messages, but the information is usually\n>>> valuable and if users don't need it, they can suppress it by changing\n>>> client_min_messages.\n>>> \n>>> Currently both summary of failures and individual information is \n>>> logged\n>>> in NOTICE level.\n>>> If we should assume that there are cases where only summary \n>>> information\n>>> is required, it'd be useful to set lower log level, i.e. LOG to the\n>>> individual information.\n>> \n>> How about we emit the summary at INFO level and individual information\n>> at NOTICE level? With this, the summary is given a different priority\n>> than the individual info. With SET client_min_messages = WARNING; one\n>> can still get the summary but not the individual info. Also, to get\n>> all of these into server log, one can SET log_min_messages = INFO; or\n>> SET log_min_messages = NOTICE;.\n>> \n>> Thoughts?\n> \n> It looks good to me.\n\nHere are comments on the v2 patch.\n\n+ if (cstate->opts.on_error != COPY_ON_ERROR_STOP)\n+ {\n+ ereport(NOTICE,\n\nI think cstate->opts.on_error is not COPY_ON_ERROR_STOP here, since if \nit is COPY_ON_ERROR_STOP, InputFunctionCallSafe() should already have \nerrored out.\n\nShould it be something like \"Assert(cstate->opts.on_error != \nCOPY_ON_ERROR_STOP)\"?\n\n\nShould below manual also be updated?\n\n> A NOTICE message containing the ignored row count is emitted at the end \n> of the COPY FROM if at least one row was discarded.\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Mon, 26 Feb 2024 21:17:36 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Mon, Feb 26, 2024 at 5:47 PM torikoshia <torikoshia@oss.nttdata.com> wrote:\n>\n> >\n> > It looks good to me.\n>\n> Here are comments on the v2 patch.\n\nThanks for looking at it.\n\n> + if (cstate->opts.on_error != COPY_ON_ERROR_STOP)\n> + {\n> + ereport(NOTICE,\n>\n> I think cstate->opts.on_error is not COPY_ON_ERROR_STOP here, since if\n> it is COPY_ON_ERROR_STOP, InputFunctionCallSafe() should already have\n> errored out.\n>\n> Should it be something like \"Assert(cstate->opts.on_error !=\n> COPY_ON_ERROR_STOP)\"?\n\nNice catch. When COPY_ON_ERROR_STOP is specified, we use ereport's\nsoft error mechanism. An assertion seems a good choice to validate the\nstate is what we expect. Done that way.\n\n> Should below manual also be updated?\n>\n> > A NOTICE message containing the ignored row count is emitted at the end\n> > of the COPY FROM if at least one row was discarded.\n\nChanged.\n\nPSA v3 patch with the above review comments addressed.\n\n-- \nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Wed, 28 Feb 2024 12:10:00 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Wed, Feb 28, 2024 at 12:10:00PM +0530, Bharath Rupireddy wrote:\n> On Mon, Feb 26, 2024 at 5:47 PM torikoshia <torikoshia@oss.nttdata.com> wrote:\n>> + if (cstate->opts.on_error != COPY_ON_ERROR_STOP)\n>> + {\n>> + ereport(NOTICE,\n>>\n>> I think cstate->opts.on_error is not COPY_ON_ERROR_STOP here, since if\n>> it is COPY_ON_ERROR_STOP, InputFunctionCallSafe() should already have\n>> errored out.\n>>\n>> Should it be something like \"Assert(cstate->opts.on_error !=\n>> COPY_ON_ERROR_STOP)\"?\n> \n> Nice catch. When COPY_ON_ERROR_STOP is specified, we use ereport's\n> soft error mechanism. An assertion seems a good choice to validate the\n> state is what we expect. Done that way.\n\nHmm. I am not really on board with this patch, that would generate\none NOTICE message each time a row is incompatible in the soft error\nmode. If you have a couple of billion rows to bulk-load into the\nbackend and even 0.01% of them are corrupted, you could finish with a\nmore than 100k log entries, and all systems should be careful about\nthe log quantity generated, especially if we use the syslogger which\ncould become easily a bottleneck.\n\nThe existing ON_ERROR controls what to do on error. I think that we'd\nbetter control the amount of information reported with a completely \nseparate option, an option even different than where to redirect\nerrors (if required, which would be either the logs, the client, a\npipe, a combination of these or even all of them).\n--\nMichael",
"msg_date": "Fri, 1 Mar 2024 13:51:55 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Fri, Mar 1, 2024 at 10:22 AM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> > Nice catch. When COPY_ON_ERROR_STOP is specified, we use ereport's\n> > soft error mechanism. An assertion seems a good choice to validate the\n> > state is what we expect. Done that way.\n>\n> Hmm. I am not really on board with this patch, that would generate\n> one NOTICE message each time a row is incompatible in the soft error\n> mode. If you have a couple of billion rows to bulk-load into the\n> backend and even 0.01% of them are corrupted, you could finish with a\n> more than 100k log entries, and all systems should be careful about\n> the log quantity generated, especially if we use the syslogger which\n> could become easily a bottleneck.\n\nHm. I was having some concerns about it as mentioned upthread. But,\nthanks a lot for illustrating it.\n\n> The existing ON_ERROR controls what to do on error. I think that we'd\n> better control the amount of information reported with a completely\n> separate option, an option even different than where to redirect\n> errors (if required, which would be either the logs, the client, a\n> pipe, a combination of these or even all of them).\n\nHow about an extra option to error_action ignore-with-verbose which is\nsimilar to ignore but when specified emits one NOTICE per malformed\nrow? With this, one can say COPY x FROM stdin (ON_ERROR\nignore-with-verbose);.\n\nAlternatively, we can think of adding a new option verbose altogether\nwhich can be used for not only this but for reporting some other COPY\nrelated info/errors etc. With this, one can say COPY x FROM stdin\n(VERBOSE on, ON_ERROR ignore);.\n\nThere's also another way of having a separate GUC, but -100 from me\nfor it. Because, it not only increases the total number of GUCs by 1,\nbut also might set a wrong precedent to have a new GUC for controlling\ncommand level outputs.\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Mon, 4 Mar 2024 05:00:00 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Mon, Mar 04, 2024 at 05:00:00AM +0530, Bharath Rupireddy wrote:\n> How about an extra option to error_action ignore-with-verbose which is\n> similar to ignore but when specified emits one NOTICE per malformed\n> row? With this, one can say COPY x FROM stdin (ON_ERROR\n> ignore-with-verbose);.\n> \n> Alternatively, we can think of adding a new option verbose altogether\n> which can be used for not only this but for reporting some other COPY\n> related info/errors etc. With this, one can say COPY x FROM stdin\n> (VERBOSE on, ON_ERROR ignore);.\n\nI would suggest a completely separate option, because that offers more\nflexibility as each option has a separate meaning. My main concern in\nusing one option to control them all is that one may want in the \nfuture to be able to specify more combinations of actions at query\nlevel, especially if more modes are added to the ON_ERROR mode. One\noption would prevent that.\n\nPerhaps ERROR_VERBOSE or ERROR_VERBOSITY would be better names, but\nI'm never wedded to my naming suggestions. Bad history with the\nmatter.\n\n> There's also another way of having a separate GUC, but -100 from me\n> for it. Because, it not only increases the total number of GUCs by 1,\n> but also might set a wrong precedent to have a new GUC for controlling\n> command level outputs.\n\nWhat does this have to do with GUCs? The ON_ERROR option does not\nhave one.\n--\nMichael",
"msg_date": "Tue, 5 Mar 2024 08:18:29 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Tue, Mar 5, 2024 at 4:48 AM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> On Mon, Mar 04, 2024 at 05:00:00AM +0530, Bharath Rupireddy wrote:\n> > How about an extra option to error_action ignore-with-verbose which is\n> > similar to ignore but when specified emits one NOTICE per malformed\n> > row? With this, one can say COPY x FROM stdin (ON_ERROR\n> > ignore-with-verbose);.\n> >\n> > Alternatively, we can think of adding a new option verbose altogether\n> > which can be used for not only this but for reporting some other COPY\n> > related info/errors etc. With this, one can say COPY x FROM stdin\n> > (VERBOSE on, ON_ERROR ignore);.\n>\n> I would suggest a completely separate option, because that offers more\n> flexibility as each option has a separate meaning. My main concern in\n> using one option to control them all is that one may want in the\n> future to be able to specify more combinations of actions at query\n> level, especially if more modes are added to the ON_ERROR mode. One\n> option would prevent that.\n>\n> Perhaps ERROR_VERBOSE or ERROR_VERBOSITY would be better names, but\n> I'm never wedded to my naming suggestions. Bad history with the\n> matter.\n\n+1 for a separate option and LOG_VERBOSITY seemed a better and generic\nnaming choice. Because, the ON_ERROR ignore isn't actually an error\nper se IMO.\n\n> > There's also another way of having a separate GUC, but -100 from me\n> > for it. Because, it not only increases the total number of GUCs by 1,\n> > but also might set a wrong precedent to have a new GUC for controlling\n> > command level outputs.\n>\n> What does this have to do with GUCs? The ON_ERROR option does not\n> have one.\n\nMy thought was to have a separate GUC for deciding log level for COPY\ncommand messages/errors similar to log_replication_commands. But\nthat's a no-go for sure when compared with a separate option.\n\nPlease see the attached v4 patch. If it looks good, I can pull\nLOG_VERBOSITY changes out into 0001 and with 0002 containing the\ndetailed messages for discarded rows.\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Wed, 6 Mar 2024 19:32:28 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Wed, Mar 06, 2024 at 07:32:28PM +0530, Bharath Rupireddy wrote:\n> Please see the attached v4 patch. If it looks good, I can pull\n> LOG_VERBOSITY changes out into 0001 and with 0002 containing the\n> detailed messages for discarded rows.\n\nThe approach looks sensible seen from here.\n\n+ LOG_VERBOSITY [ <replaceable class=\"parameter\">boolean</replaceable> ]\n[...]\n+ <term><literal>LOG_VERBOSITY</literal></term>\n+ <listitem>\n+ <para>\n+ Sets the verbosity of logged messages by <command>COPY</command>\n+ command. As an example, see its usage for\n+ <command>COPY FROM</command> command's <literal>ON_ERROR</literal>\n+ clause with <literal>ignore</literal> option.\n+ </para>\n+ </listitem>\n\nIs a boolean the best interface for the end-user, though? Maybe\nsomething like a \"mode\" value would speak more than a yes/no from the\nstart, say a \"default\" mode to emit only the last LOG and a \"verbose\"\nfor the whole set in the case of ON_ERROR? That could use an enum\nfrom the start internally, but that's an implementation detail.\n\nDescribing what gets logged in the paragraph of ON_ERROR sounds fine,\nespecially if in the future more logs are added depending on other\noptions. That's an assumption at this stage, of course.\n\nI am adding Alexander Korotkov in CC, as the original committer of\n9e2d8701194f, as I assume that he may want to chime in this\ndiscussion.\n\nTorikoshi-san or others, if you have any comments about the interface,\nfeel free.\n--\nMichael",
"msg_date": "Thu, 7 Mar 2024 13:00:12 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On 2024-03-07 13:00, Michael Paquier wrote:\n> On Wed, Mar 06, 2024 at 07:32:28PM +0530, Bharath Rupireddy wrote:\n>> Please see the attached v4 patch. If it looks good, I can pull\n>> LOG_VERBOSITY changes out into 0001 and with 0002 containing the\n>> detailed messages for discarded rows.\n> \n> The approach looks sensible seen from here.\n> \n> + LOG_VERBOSITY [ <replaceable \n> class=\"parameter\">boolean</replaceable> ]\n> [...]\n> + <term><literal>LOG_VERBOSITY</literal></term>\n> + <listitem>\n> + <para>\n> + Sets the verbosity of logged messages by <command>COPY</command>\n> + command. As an example, see its usage for\n> + <command>COPY FROM</command> command's \n> <literal>ON_ERROR</literal>\n> + clause with <literal>ignore</literal> option.\n> + </para>\n> + </listitem>\n> \n> Is a boolean the best interface for the end-user, though? Maybe\n> something like a \"mode\" value would speak more than a yes/no from the\n> start, say a \"default\" mode to emit only the last LOG and a \"verbose\"\n> for the whole set in the case of ON_ERROR? That could use an enum\n> from the start internally, but that's an implementation detail.\n> \n> Describing what gets logged in the paragraph of ON_ERROR sounds fine,\n> especially if in the future more logs are added depending on other\n> options. That's an assumption at this stage, of course.\n> \n> I am adding Alexander Korotkov in CC, as the original committer of\n> 9e2d8701194f, as I assume that he may want to chime in this\n> discussion.\n> \n> Torikoshi-san or others, if you have any comments about the interface,\n> feel free.\n\nThanks.\n\nMaybe I'm overly concerned, but I'm a little concerned about whether the \ncontents of this output can really be called verbose, since it does not \noutput the actual soft error message that occurred, but only the row and \ncolumn where the error occurred.\n\nSince the soft error mechanism can at least output the contents of soft \nerrors in the server log [1], it might be a good idea to use something \nlike a 'mode' value instead of boolean as Michael-san suggested, so that \nthe log output contents can be adjusted at multiple levels.\n\n[1] \nhttps://www.postgresql.org/message-id/20230322175000.qbdctk7bnmifh5an%40awork3.anarazel.de\n\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Thu, 07 Mar 2024 14:21:13 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Thu, Mar 7, 2024 at 1:00 PM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> On Wed, Mar 06, 2024 at 07:32:28PM +0530, Bharath Rupireddy wrote:\n> > Please see the attached v4 patch. If it looks good, I can pull\n> > LOG_VERBOSITY changes out into 0001 and with 0002 containing the\n> > detailed messages for discarded rows.\n>\n> The approach looks sensible seen from here.\n\nLooks like a good approach to me.\n\n>\n> + LOG_VERBOSITY [ <replaceable class=\"parameter\">boolean</replaceable> ]\n> [...]\n> + <term><literal>LOG_VERBOSITY</literal></term>\n> + <listitem>\n> + <para>\n> + Sets the verbosity of logged messages by <command>COPY</command>\n> + command. As an example, see its usage for\n> + <command>COPY FROM</command> command's <literal>ON_ERROR</literal>\n> + clause with <literal>ignore</literal> option.\n> + </para>\n> + </listitem>\n>\n> Is a boolean the best interface for the end-user, though? Maybe\n> something like a \"mode\" value would speak more than a yes/no from the\n> start, say a \"default\" mode to emit only the last LOG and a \"verbose\"\n> for the whole set in the case of ON_ERROR? That could use an enum\n> from the start internally, but that's an implementation detail.\n\n+1 for making it an enum, so that we will be able to have multiple\nlevels for example to get actual soft error contents.\n\nOne question I have is; do we want to write multiple NOTICE messages\nfor one row if the row has malformed data on some columns?\n\nRegards,\n\n--\nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Thu, 7 Mar 2024 15:52:41 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Thu, Mar 07, 2024 at 03:52:41PM +0900, Masahiko Sawada wrote:\n> One question I have is; do we want to write multiple NOTICE messages\n> for one row if the row has malformed data on some columns?\n\nGood idea. We can do that as the field strings are already parsed.\n--\nMichael",
"msg_date": "Thu, 7 Mar 2024 16:07:17 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Thu, Mar 7, 2024 at 9:30 AM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> Is a boolean the best interface for the end-user, though? Maybe\n> something like a \"mode\" value would speak more than a yes/no from the\n> start, say a \"default\" mode to emit only the last LOG and a \"verbose\"\n> for the whole set in the case of ON_ERROR? That could use an enum\n> from the start internally, but that's an implementation detail.\n\nI'm okay with it. But, help me understand it better. We want the\n'log_verbosity' clause to have options 'default' and 'verbose', right?\nAnd, later it can also be extended to contain all the LOG levels like\n'notice', 'error', 'info' , 'debugX' etc. depending on the need,\nright?\n\nOne more thing, how does it sound using both verbosity and verbose in\nlog_verbosity verbose something like below? Is this okay?\n\nCOPY check_ign_err FROM STDIN WITH (on_error ignore, log_verbosity verbose);\n\n-- \nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Thu, 7 Mar 2024 12:48:12 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Thu, Mar 7, 2024 at 12:37 PM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> On Thu, Mar 07, 2024 at 03:52:41PM +0900, Masahiko Sawada wrote:\n> > One question I have is; do we want to write multiple NOTICE messages\n> > for one row if the row has malformed data on some columns?\n>\n> Good idea. We can do that as the field strings are already parsed.\n\nNice catch. So, are you suggesting to log one NOTICE message per row\neven if multiple columns in the single row fail to parse or are\nmalformed?\n\n-- \nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Thu, 7 Mar 2024 12:50:33 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Thu, Mar 07, 2024 at 12:48:12PM +0530, Bharath Rupireddy wrote:\n> I'm okay with it. But, help me understand it better. We want the\n> 'log_verbosity' clause to have options 'default' and 'verbose', right?\n> And, later it can also be extended to contain all the LOG levels like\n> 'notice', 'error', 'info' , 'debugX' etc. depending on the need,\n> right?\n\nYou could, or names that have some status like row_details, etc.\n\n> One more thing, how does it sound using both verbosity and verbose in\n> log_verbosity verbose something like below? Is this okay?\n\nThere's some history with this pattern in psql at least with \\set\nVERBOSITY verbose. For the patch, I would tend to choose these two,\nbut that's as far as my opinion goes and I am OK other ideas gather\nmore votes.\n--\nMichael",
"msg_date": "Thu, 7 Mar 2024 16:24:26 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Thu, Mar 07, 2024 at 12:50:33PM +0530, Bharath Rupireddy wrote:\n> Nice catch. So, are you suggesting to log one NOTICE message per row\n> even if multiple columns in the single row fail to parse or are\n> malformed?\n\nOne NOTICE per malformed value, I guess, which would be easier to\nparse particularly if the values are long (like, JSON-long).\n--\nMichael",
"msg_date": "Thu, 7 Mar 2024 16:26:44 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Thu, Mar 7, 2024 at 12:54 PM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> On Thu, Mar 07, 2024 at 12:48:12PM +0530, Bharath Rupireddy wrote:\n> > I'm okay with it. But, help me understand it better. We want the\n> > 'log_verbosity' clause to have options 'default' and 'verbose', right?\n> > And, later it can also be extended to contain all the LOG levels like\n> > 'notice', 'error', 'info' , 'debugX' etc. depending on the need,\n> > right?\n>\n> You could, or names that have some status like row_details, etc.\n>\n> > One more thing, how does it sound using both verbosity and verbose in\n> > log_verbosity verbose something like below? Is this okay?\n>\n> There's some history with this pattern in psql at least with \\set\n> VERBOSITY verbose. For the patch, I would tend to choose these two,\n> but that's as far as my opinion goes and I am OK other ideas gather\n> more votes.\n\nPlease see the attached v5-0001 patch implementing LOG_VERBOSITY with\noptions 'default' and 'verbose'. v5-0002 adds the detailed info to\nON_ERROR 'ignore' option.\n\nWe have a CF entry https://commitfest.postgresql.org/47/4798/ for the\noriginal idea proposed in this thread, that is, to have the ON_ERROR\n'log' option. I'll probably start a new thread and add a new CF entry\nin the next commitfest if there's no objection from anyone.\n\n-- \nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Fri, 8 Mar 2024 15:36:30 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Fri, Mar 08, 2024 at 03:36:30PM +0530, Bharath Rupireddy wrote:\n> Please see the attached v5-0001 patch implementing LOG_VERBOSITY with\n> options 'default' and 'verbose'. v5-0002 adds the detailed info to\n> ON_ERROR 'ignore' option.\n\nI may be reading this patch set incorrectly, but why doesn't this\npatch generate one NOTICE per attribute, as suggested by Sawada-san,\nincrementing num_errors once per row when the last attribute has been\nprocessed? Also, why not have a test that checks that multiple rows\nspawn more than more messages in some distributed fashion? Did you\nlook at this idea?\n\n> We have a CF entry https://commitfest.postgresql.org/47/4798/ for the\n> original idea proposed in this thread, that is, to have the ON_ERROR\n> 'log' option. I'll probably start a new thread and add a new CF entry\n> in the next commitfest if there's no objection from anyone.\n\nHmm. You are referring to the part where you'd want to control where\nthe errors are sent, right? At least, what you have here would\naddress point 1) mentioned in the first message of this thread.\n--\nMichael",
"msg_date": "Fri, 8 Mar 2024 20:12:39 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Fri, Mar 8, 2024 at 4:42 PM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> On Fri, Mar 08, 2024 at 03:36:30PM +0530, Bharath Rupireddy wrote:\n> > Please see the attached v5-0001 patch implementing LOG_VERBOSITY with\n> > options 'default' and 'verbose'. v5-0002 adds the detailed info to\n> > ON_ERROR 'ignore' option.\n>\n> I may be reading this patch set incorrectly, but why doesn't this\n> patch generate one NOTICE per attribute, as suggested by Sawada-san,\n> incrementing num_errors once per row when the last attribute has been\n> processed? Also, why not have a test that checks that multiple rows\n> spawn more than more messages in some distributed fashion? Did you\n> look at this idea?\n\nIf NOTICE per attribute and incrementing num_errors per row is\nimplemented, it ends up erroring out with ERROR: missing data for\ncolumn \"m\" for all-column-empty-row. Shall we treat this ERROR softly\ntoo if on_error ignore is specified? Or shall we discuss this idea\nseparately?\n\n-- tests for options on_error and log_verbosity\nCOPY check_ign_err FROM STDIN WITH (on_error ignore, log_verbosity 'verbose');\n1 {1} 1\na {2} 2\n3 {3} 3333333333\n4 {a, 4} 4\n\n5 {5} 5\n\\.\n\nNOTICE: detected data type incompatibility at line number 2 for\ncolumn n; COPY check_ign_err\nNOTICE: detected data type incompatibility at line number 2 for\ncolumn m; COPY check_ign_err\nNOTICE: detected data type incompatibility at line number 2 for\ncolumn k; COPY check_ign_err\nNOTICE: detected data type incompatibility at line number 3 for\ncolumn k; COPY check_ign_err\nNOTICE: detected data type incompatibility at line number 4 for\ncolumn m; COPY check_ign_err\nNOTICE: detected data type incompatibility at line number 4 for\ncolumn k; COPY check_ign_err\nNOTICE: detected data type incompatibility at line number 5 for\ncolumn n; COPY check_ign_err\nERROR: missing data for column \"m\"\nCONTEXT: COPY check_ign_err, line 5: \"\"\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Sat, 9 Mar 2024 00:01:49 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Sat, Mar 09, 2024 at 12:01:49AM +0530, Bharath Rupireddy wrote:\n> If NOTICE per attribute and incrementing num_errors per row is\n> implemented, it ends up erroring out with ERROR: missing data for\n> column \"m\" for all-column-empty-row. Shall we treat this ERROR softly\n> too if on_error ignore is specified? Or shall we discuss this idea\n> separately?\n>\n> ERROR: missing data for column \"m\"\n> CONTEXT: COPY check_ign_err, line 5: \"\"\n\nHmm. I have spent some time looking at the bevahior of ON_ERROR, and\nthere are two tests in copy2.sql, one for the case where there is more\ndata than attributes and a second where there is not enough data in a\nrow that checks for errors.\n\nFor example, take this table:\n=# create table tab (a int, b int, c int);\nCREATE TABLE\n\nThis case works, even if the row has clearly not enough attributes.\nThe first attribute can be parsed, not the second one and this causes\nthe remaining data of the row to be skipped:\n=# copy tab from stdin (delimiter ',', on_error ignore);\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>> 1,\n>> \\.\nNOTICE: 00000: 1 row was skipped due to data type incompatibility\nLOCATION: CopyFrom, copyfrom.c:1314\nCOPY 0\n\nThis case fails. The first and the second attributes can be parsed, \nand the line fails because we are missing the last attribute as of a\nlack of delimiter:\n=# copy tab from stdin (delimiter ',', on_error ignore);\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>> 1,1\n>> \\.\nERROR: 22P04: missing data for column \"c\"\nCONTEXT: COPY tab, line 1: \"1,1\"\n\nThis brings a weird edge case for the all-column-empty-row case you\nare mentioning once if we try to get information about all the rows we\nshould expect, but this has as side effect to break a case that's\nintended ro work with ON_ERROR, as far as I understand, which is to\nskip entirely a raw on the first conversion error we find, even if\nthere is no data afterwards. I was a bit confused by that first, but\nI can also see why it is useful as-is on HEAD.\n\nAt the end of the day, this comes down to what is more helpful to the\nuser. And I'd agree on the side what ON_ERROR does currently, which\nis what your patch relies on: on the first conversion failure, give up\nand skip the rest of the row because we cannot trust its contents.\nThat's my way of saying that I am fine with the proposal of your\npatch, and that we cannot provide the full state of a row without\nmaking the error stack of COPY more invasive.\n\nPerhaps we could discuss this idea of ensuring that all the attributes\nare on a row in a different thread, as you say, but I am not really\nconvinced that there's a strong need for it at this stage as ON_ERROR\nis new to v17. So it does not sound like a bad thing to let it brew\nmore before implementing more options and make the COPY paths more\ncomplicated than they already are. I suspect that this may trigger\nsome discussion during the beta/stability phase depending on the\ninitial feedback. Perhaps I'm wrong, though.\n\n+ <literal>verbose</literal>, a <literal>NOTICE</literal> message\n+ containing the line number and column name for each discarded row is\n+ emitted.\n\nThis should clarify that the column name refers to the attribute where\nthe input conversion has failed, I guess. Specifying only \"column\nname\" without more context is a bit confusing.\n--\nMichael",
"msg_date": "Mon, 11 Mar 2024 14:46:17 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Mon, Mar 11, 2024 at 11:16 AM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> At the end of the day, this comes down to what is more helpful to the\n> user. And I'd agree on the side what ON_ERROR does currently, which\n> is what your patch relies on: on the first conversion failure, give up\n> and skip the rest of the row because we cannot trust its contents.\n> That's my way of saying that I am fine with the proposal of your\n> patch, and that we cannot provide the full state of a row without\n> making the error stack of COPY more invasive.\n\n+1.\n\n> + <literal>verbose</literal>, a <literal>NOTICE</literal> message\n> + containing the line number and column name for each discarded row is\n> + emitted.\n>\n> This should clarify that the column name refers to the attribute where\n> the input conversion has failed, I guess. Specifying only \"column\n> name\" without more context is a bit confusing.\n\nDone.\n\nPlease see the attached v6 patch set.\n\n-- \nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Mon, 11 Mar 2024 18:00:00 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Mon, Mar 11, 2024 at 06:00:00PM +0530, Bharath Rupireddy wrote:\n> Please see the attached v6 patch set.\n\nI am tempted to tweak a few things in the docs, the comments and the\ntests (particularly adding more patterns for tuples that fail on\nconversion while it's clear that there are not enough attributes after\nthe incorrect values), but that looks roughly OK.\n\nWouldn't it be better to squash the patches together, by the way?\n--\nMichael",
"msg_date": "Tue, 12 Mar 2024 15:52:01 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Tue, Mar 12, 2024 at 12:22 PM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> On Mon, Mar 11, 2024 at 06:00:00PM +0530, Bharath Rupireddy wrote:\n> > Please see the attached v6 patch set.\n>\n> I am tempted to tweak a few things in the docs, the comments and the\n> tests (particularly adding more patterns for tuples that fail on\n> conversion while it's clear that there are not enough attributes after\n> the incorrect values), but that looks roughly OK.\n\n+1. But, do you want to add them now or later as a separate\npatch/discussion altogether?\n\n> Wouldn't it be better to squash the patches together, by the way?\n\nI guess not. They are two different things IMV.\n\n-- \nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 12 Mar 2024 12:54:29 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Tue, Mar 12, 2024 at 12:54:29PM +0530, Bharath Rupireddy wrote:\n> +1. But, do you want to add them now or later as a separate\n> patch/discussion altogether?\n\nThe attached 0003 is what I had in mind:\n- Simplification of the LOG generated with quotes applied around the\ncolumn name, don't see much need to add the relation name, either, for\nconsistency and because the knowledge is known in the query.\n- A few more tests.\n- Some doc changes.\n\n>> Wouldn't it be better to squash the patches together, by the way?\n> \n> I guess not. They are two different things IMV.\n\nWell, 0001 is sitting doing nothing because the COPY code does not\nmake use of it internally.\n--\nMichael",
"msg_date": "Wed, 13 Mar 2024 08:46:29 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Wed, Mar 13, 2024 at 5:16 AM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> On Tue, Mar 12, 2024 at 12:54:29PM +0530, Bharath Rupireddy wrote:\n> > +1. But, do you want to add them now or later as a separate\n> > patch/discussion altogether?\n>\n> The attached 0003 is what I had in mind:\n> - Simplification of the LOG generated with quotes applied around the\n> column name, don't see much need to add the relation name, either, for\n> consistency and because the knowledge is known in the query.\n> - A few more tests.\n> - Some doc changes.\n\nLGMT. So, I've merged those changes into 0001 and 0002.\n\n> >> Wouldn't it be better to squash the patches together, by the way?\n> >\n> > I guess not. They are two different things IMV.\n>\n> Well, 0001 is sitting doing nothing because the COPY code does not\n> make use of it internally.\n\nYes. That's why I left a note in the commit message that a future\ncommit will use it.\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Wed, 13 Mar 2024 08:08:42 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Wed, Mar 13, 2024 at 08:08:42AM +0530, Bharath Rupireddy wrote:\n> On Wed, Mar 13, 2024 at 5:16 AM Michael Paquier <michael@paquier.xyz> wrote:\n>> The attached 0003 is what I had in mind:\n>> - Simplification of the LOG generated with quotes applied around the\n>> column name, don't see much need to add the relation name, either, for\n>> consistency and because the knowledge is known in the query.\n>> - A few more tests.\n>> - Some doc changes.\n> \n> LGMT. So, I've merged those changes into 0001 and 0002.\n\nI've applied the extra tests for now, as this was really confusing.\n\nHmm. This NOTICE is really bugging me. It is true that the clients\nwould get more information, but the information is duplicated on the\nserver side because the error context provides the same information as\nthe NOTICE itself:\nNOTICE: data type incompatibility at line 1 for column \"a\"\nCONTEXT: COPY aa, line 1, column a: \"a\"\nSTATEMENT: copy aa from stdin with (on_error ignore, log_verbosity verbose); \n--\nMichael",
"msg_date": "Wed, 13 Mar 2024 14:39:06 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Wed, Mar 13, 2024 at 11:09 AM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> Hmm. This NOTICE is really bugging me. It is true that the clients\n> would get more information, but the information is duplicated on the\n> server side because the error context provides the same information as\n> the NOTICE itself:\n> NOTICE: data type incompatibility at line 1 for column \"a\"\n> CONTEXT: COPY aa, line 1, column a: \"a\"\n> STATEMENT: copy aa from stdin with (on_error ignore, log_verbosity verbose);\n\nYes, if wanted, clients can also get the CONTEXT - for instance, using\n'\\set SHOW_CONTEXT always' in psql.\n\nI think we can enhance the NOTICE message to include the column value\n(just like CONTEXT message is showing) and leverage relname_only to\nemit only the relation name in the CONTEXT message.\n\n /*\n * We suppress error context information other than the relation name,\n * if one of the operations below fails.\n */\n Assert(!cstate->relname_only);\n cstate->relname_only = true;\n\nI'm attaching the v8 patch set implementing the above idea. With this,\n[1] is sent to the client, [2] is sent to the server log. This\napproach not only reduces the duplicate info in the NOTICE and CONTEXT\nmessages, but also makes it easy for users to get all the necessary\ninfo in the NOTICE message without having to set extra parameters to\nget CONTEXT message.\n\nAnother idea is to move even the table name to NOTICE message and hide\nthe context with errhidecontext when we emit the new NOTICE messages.\n\nThoughts?\n\n[1]\nNOTICE: data type incompatibility at line 2 for column n: \"a\"\nNOTICE: data type incompatibility at line 3 for column k: \"3333333333\"\nNOTICE: data type incompatibility at line 4 for column m: \"{a, 4}\"\nNOTICE: data type incompatibility at line 5 for column n: \"\"\nNOTICE: data type incompatibility at line 7 for column m: \"a\"\nNOTICE: data type incompatibility at line 8 for column k: \"a\"\nNOTICE: 6 rows were skipped due to data type incompatibility\nCOPY 3\n\n[2]\n2024-03-13 13:49:14.138 UTC [1330270] NOTICE: data type\nincompatibility at line 2 for column n: \"a\"\n2024-03-13 13:49:14.138 UTC [1330270] CONTEXT: COPY check_ign_err\n2024-03-13 13:49:14.138 UTC [1330270] NOTICE: data type\nincompatibility at line 3 for column k: \"3333333333\"\n2024-03-13 13:49:14.138 UTC [1330270] CONTEXT: COPY check_ign_err\n2024-03-13 13:49:14.138 UTC [1330270] NOTICE: data type\nincompatibility at line 4 for column m: \"{a, 4}\"\n2024-03-13 13:49:14.138 UTC [1330270] CONTEXT: COPY check_ign_err\n2024-03-13 13:49:14.138 UTC [1330270] NOTICE: data type\nincompatibility at line 5 for column n: \"\"\n2024-03-13 13:49:14.138 UTC [1330270] CONTEXT: COPY check_ign_err\n2024-03-13 13:49:14.138 UTC [1330270] NOTICE: data type\nincompatibility at line 7 for column m: \"a\"\n2024-03-13 13:49:14.138 UTC [1330270] CONTEXT: COPY check_ign_err\n2024-03-13 13:49:14.138 UTC [1330270] NOTICE: data type\nincompatibility at line 8 for column k: \"a\"\n2024-03-13 13:49:14.138 UTC [1330270] CONTEXT: COPY check_ign_err\n2024-03-13 13:49:14.138 UTC [1330270] NOTICE: 6 rows were skipped due\nto data type incompatibility\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Wed, 13 Mar 2024 19:32:37 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Wed, Mar 13, 2024 at 07:32:37PM +0530, Bharath Rupireddy wrote:\n> I'm attaching the v8 patch set implementing the above idea. With this,\n> [1] is sent to the client, [2] is sent to the server log. This\n> approach not only reduces the duplicate info in the NOTICE and CONTEXT\n> messages, but also makes it easy for users to get all the necessary\n> info in the NOTICE message without having to set extra parameters to\n> get CONTEXT message.\n\nIn terms of eliminating the information duplication while allowing\nclients to know the value, the attribute and the line involved in the\nconversion failure, the approach of tweaking the context information\nhas merits, I guess.\n\nHow do others feel about this kind of tuning?\n--\nMichael",
"msg_date": "Fri, 15 Mar 2024 16:57:25 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "At Fri, 15 Mar 2024 16:57:25 +0900, Michael Paquier <michael@paquier.xyz> wrote in \n> On Wed, Mar 13, 2024 at 07:32:37PM +0530, Bharath Rupireddy wrote:\n> > I'm attaching the v8 patch set implementing the above idea. With this,\n> > [1] is sent to the client, [2] is sent to the server log. This\n> > approach not only reduces the duplicate info in the NOTICE and CONTEXT\n> > messages, but also makes it easy for users to get all the necessary\n> > info in the NOTICE message without having to set extra parameters to\n> > get CONTEXT message.\n> \n> In terms of eliminating the information duplication while allowing\n> clients to know the value, the attribute and the line involved in the\n> conversion failure, the approach of tweaking the context information\n> has merits, I guess.\n> \n> How do others feel about this kind of tuning?\n\nIf required, I think that we have already included the minimum\ninformation necessary for the primary diagnosis, including locations,\nwithin the primary messages. Here is an example:\n\n> LOG: 00000: invalid record length at 0/18049F8: expected at least 24, got 0\n\nAnd I believe that CONTEXT, if it exists, is augmentation information\nto the primary messages. The objective of the precedent for the use of\nrelname_only was somewhat different, but this use also seems legit.\n\nIn short, I think the distribution between message types (primary and\ncontext) is fine as it is in the latest patch.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n",
"msg_date": "Mon, 18 Mar 2024 12:05:17 +0900 (JST)",
"msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Mon, Mar 18, 2024 at 12:05:17PM +0900, Kyotaro Horiguchi wrote:\n> And I believe that CONTEXT, if it exists, is augmentation information\n> to the primary messages. The objective of the precedent for the use of\n> relname_only was somewhat different, but this use also seems legit.\n> \n> In short, I think the distribution between message types (primary and\n> context) is fine as it is in the latest patch.\n\nOkay, thanks for the feedback.\n--\nMichael",
"msg_date": "Mon, 18 Mar 2024 14:13:51 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Wed, Mar 13, 2024 at 11:02 PM Bharath Rupireddy\n<bharath.rupireddyforpostgres@gmail.com> wrote:\n>\n> On Wed, Mar 13, 2024 at 11:09 AM Michael Paquier <michael@paquier.xyz> wrote:\n> >\n> > Hmm. This NOTICE is really bugging me. It is true that the clients\n> > would get more information, but the information is duplicated on the\n> > server side because the error context provides the same information as\n> > the NOTICE itself:\n> > NOTICE: data type incompatibility at line 1 for column \"a\"\n> > CONTEXT: COPY aa, line 1, column a: \"a\"\n> > STATEMENT: copy aa from stdin with (on_error ignore, log_verbosity verbose);\n>\n> Yes, if wanted, clients can also get the CONTEXT - for instance, using\n> '\\set SHOW_CONTEXT always' in psql.\n>\n> I think we can enhance the NOTICE message to include the column value\n> (just like CONTEXT message is showing) and leverage relname_only to\n> emit only the relation name in the CONTEXT message.\n>\n> /*\n> * We suppress error context information other than the relation name,\n> * if one of the operations below fails.\n> */\n> Assert(!cstate->relname_only);\n> cstate->relname_only = true;\n>\n> I'm attaching the v8 patch set implementing the above idea. With this,\n> [1] is sent to the client, [2] is sent to the server log. This\n> approach not only reduces the duplicate info in the NOTICE and CONTEXT\n> messages, but also makes it easy for users to get all the necessary\n> info in the NOTICE message without having to set extra parameters to\n> get CONTEXT message.\n>\n> Another idea is to move even the table name to NOTICE message and hide\n> the context with errhidecontext when we emit the new NOTICE messages.\n>\n> Thoughts?\n>\n\nThe current approach, eliminating the duplicated information in\nCONTEXT, seems good to me.\n\nOne question about the latest (v8) patch:\n\n+ else\n+ ereport(NOTICE,\n+ errmsg(\"data type incompatibility at\nline %llu for column %s: null input\",\n+ (unsigned long long) cstate->cur_lineno,\n+ cstate->cur_attname));\n+\n\nHow can we reach this path? It seems we don't cover this path by the tests.\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Mon, 25 Mar 2024 14:11:40 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Mon, Mar 25, 2024 at 10:42 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> The current approach, eliminating the duplicated information in\n> CONTEXT, seems good to me.\n\nThanks for looking into it.\n\n> One question about the latest (v8) patch:\n>\n> + else\n> + ereport(NOTICE,\n> + errmsg(\"data type incompatibility at\n> line %llu for column %s: null input\",\n> + (unsigned long long) cstate->cur_lineno,\n> + cstate->cur_attname));\n> +\n>\n> How can we reach this path? It seems we don't cover this path by the tests.\n\nTests don't cover that part, but it can be hit with something like\n[1]. I've added a test for this.\n\nNote the use of domain to provide an indirect way of providing null\nconstraint check. Otherwise, COPY FROM fails early in\nCopyFrom->ExecConstraints if the NOT NULL constraint is directly\nprovided next to the column in the table [2].\n\nPlease see the attached v9 patch set.\n\n[1]\ncreate domain dcheck_ign_err2 varchar(15) NOT NULL;\nCREATE TABLE check_ign_err2 (n int, m int[], k int, l dcheck_ign_err2);\nCOPY check_ign_err2 FROM STDIN WITH (on_error ignore, log_verbosity verbose);\n1 {1} 1 'foo'\n2 {2} 2 \\N\n\\.\n\n[2]\nCREATE TABLE check_ign_err3 (n int, m int[], k int, l varchar(15) NOT NULL);\npostgres=# COPY check_ign_err3 FROM STDIN WITH (on_error ignore,\nlog_verbosity verbose);\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>> 1 {1} 1 'foo'\n2 {2} 2 \\N>>\n>> \\.\nERROR: null value in column \"l\" of relation \"check_ign_err3\" violates\nnot-null constraint\nDETAIL: Failing row contains (2, {2}, 2, null).\nCONTEXT: COPY check_ign_err3, line 2: \"2 {2} 2 \\N\"\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Mon, 25 Mar 2024 16:51:39 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Mon, Mar 25, 2024 at 8:21 PM Bharath Rupireddy\n<bharath.rupireddyforpostgres@gmail.com> wrote:\n>\n> On Mon, Mar 25, 2024 at 10:42 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > The current approach, eliminating the duplicated information in\n> > CONTEXT, seems good to me.\n>\n> Thanks for looking into it.\n>\n> > One question about the latest (v8) patch:\n> >\n> > + else\n> > + ereport(NOTICE,\n> > + errmsg(\"data type incompatibility at\n> > line %llu for column %s: null input\",\n> > + (unsigned long long) cstate->cur_lineno,\n> > + cstate->cur_attname));\n> > +\n> >\n> > How can we reach this path? It seems we don't cover this path by the tests.\n>\n> Tests don't cover that part, but it can be hit with something like\n> [1]. I've added a test for this.\n>\n> Note the use of domain to provide an indirect way of providing null\n> constraint check. Otherwise, COPY FROM fails early in\n> CopyFrom->ExecConstraints if the NOT NULL constraint is directly\n> provided next to the column in the table [2].\n>\n> Please see the attached v9 patch set.\n>\n\nThank you for updating the patch! The patch mostly looks good to me.\nHere are some minor comments:\n\n---\n /* non-export function prototypes */\n-static char *limit_printout_length(const char *str);\n-\nstatic void ClosePipeFromProgram(CopyFromState cstate);\n\nNow that we have only one function we should replace \"prototypes\" with\n\"prototype\".\n\n---\n+ ereport(NOTICE,\n+\nerrmsg(\"data type incompatibility at line %llu for column %s: \\\"%s\\\"\",\n+\n (unsigned long long) cstate->cur_lineno,\n+\n cstate->cur_attname,\n+\n attval));\n\nI guess it would be better to make the log message clearer to convey\nwhat we did for the malformed row. For example, how about something\nlike \"skipping row due to data type incompatibility at line %llu for\ncolumn %s: \\\"s\\\"\"?\n\n---\n extern void CopyFromErrorCallback(void *arg);\n+extern char *limit_printout_length(const char *str);\n\nI don't disagree with exposing the limit_printout_length() function\nbut I think it's better to rename it for consistency with other\nexposed COPY command functions. Only this function is snake-case. How\nabout CopyLimitPrintoutLength() or similar?\n\nFWIW I'm going to merge two patches before the push.\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 26 Mar 2024 10:45:30 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Tue, Mar 26, 2024 at 7:16 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> > Please see the attached v9 patch set.\n>\n> Thank you for updating the patch! The patch mostly looks good to me.\n> Here are some minor comments:\n\nThanks for looking into this.\n\n> ---\n> /* non-export function prototypes */\n> -static char *limit_printout_length(const char *str);\n> -\n> static void ClosePipeFromProgram(CopyFromState cstate);\n>\n> Now that we have only one function we should replace \"prototypes\" with\n> \"prototype\".\n\nWell no. We might add a few more (never know). A quick look around the\nGUCs under /* GUCs */ tells me that plural form there is being used\neven just one GUC is defined (xlogprefetcher.c for instance).\n\n> ---\n> + ereport(NOTICE,\n> +\n> errmsg(\"data type incompatibility at line %llu for column %s: \\\"%s\\\"\",\n> +\n> (unsigned long long) cstate->cur_lineno,\n> +\n> cstate->cur_attname,\n> +\n> attval));\n>\n> I guess it would be better to make the log message clearer to convey\n> what we did for the malformed row. For example, how about something\n> like \"skipping row due to data type incompatibility at line %llu for\n> column %s: \\\"s\\\"\"?\n\nThe summary message which gets printed at the end says that \"NOTICE:\n6 rows were skipped due to data type incompatibility\". Isn't this\nenough? If someone is using ON_ERROR 'ignore', it's quite natural that\nsuch rows get skipped softly and the summary message can help them,\nno?\n\n> ---\n> extern void CopyFromErrorCallback(void *arg);\n> +extern char *limit_printout_length(const char *str);\n>\n> I don't disagree with exposing the limit_printout_length() function\n> but I think it's better to rename it for consistency with other\n> exposed COPY command functions. Only this function is snake-case. How\n> about CopyLimitPrintoutLength() or similar?\n\nWFM. Although its implementation is not related to COPY code, COPY is\nthe sole user of it right now, so I'm fine with it. Done that.\n\n> FWIW I'm going to merge two patches before the push.\n\nDone that.\n\nPlease see the attached v10 patch.\n\n-- \nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Tue, 26 Mar 2024 08:53:33 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Tue, Mar 26, 2024 at 12:23 PM Bharath Rupireddy\n<bharath.rupireddyforpostgres@gmail.com> wrote:\n>\n> On Tue, Mar 26, 2024 at 7:16 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > > Please see the attached v9 patch set.\n> >\n> > Thank you for updating the patch! The patch mostly looks good to me.\n> > Here are some minor comments:\n>\n> Thanks for looking into this.\n>\n> > ---\n> > /* non-export function prototypes */\n> > -static char *limit_printout_length(const char *str);\n> > -\n> > static void ClosePipeFromProgram(CopyFromState cstate);\n> >\n> > Now that we have only one function we should replace \"prototypes\" with\n> > \"prototype\".\n>\n> Well no. We might add a few more (never know). A quick look around the\n> GUCs under /* GUCs */ tells me that plural form there is being used\n> even just one GUC is defined (xlogprefetcher.c for instance).\n\nUnderstood.\n\n>\n> > ---\n> > + ereport(NOTICE,\n> > +\n> > errmsg(\"data type incompatibility at line %llu for column %s: \\\"%s\\\"\",\n> > +\n> > (unsigned long long) cstate->cur_lineno,\n> > +\n> > cstate->cur_attname,\n> > +\n> > attval));\n> >\n> > I guess it would be better to make the log message clearer to convey\n> > what we did for the malformed row. For example, how about something\n> > like \"skipping row due to data type incompatibility at line %llu for\n> > column %s: \\\"s\\\"\"?\n>\n> The summary message which gets printed at the end says that \"NOTICE:\n> 6 rows were skipped due to data type incompatibility\". Isn't this\n> enough? If someone is using ON_ERROR 'ignore', it's quite natural that\n> such rows get skipped softly and the summary message can help them,\n> no?\n\nI think that in the main log message we should mention what happened\n(or is happening) or what we did (or are doing). If the message \"data\ntype incompatibility ...\" was in the DETAIL message with the main\nmessage saying something like \"skipping row at line %llu for column\n%s: ...\", it would make sense to me. But the current message seems not\nto be clear to me and consistent with other NOTICE messages. Also, the\nlast summary line would not be written if the user cancelled, and\nsomeone other than person who used ON_ERROR 'ignore' might check the\nserver logs later.\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 26 Mar 2024 13:25:31 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Tue, Mar 26, 2024 at 9:56 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> > > errmsg(\"data type incompatibility at line %llu for column %s: \\\"%s\\\"\",\n>\n> > > I guess it would be better to make the log message clearer to convey\n> > > what we did for the malformed row. For example, how about something\n> > > like \"skipping row due to data type incompatibility at line %llu for\n> > > column %s: \\\"s\\\"\"?\n> >\n> > The summary message which gets printed at the end says that \"NOTICE:\n> > 6 rows were skipped due to data type incompatibility\". Isn't this\n> > enough? If someone is using ON_ERROR 'ignore', it's quite natural that\n> > such rows get skipped softly and the summary message can help them,\n> > no?\n>\n> I think that in the main log message we should mention what happened\n> (or is happening) or what we did (or are doing). If the message \"data\n> type incompatibility ...\" was in the DETAIL message with the main\n> message saying something like \"skipping row at line %llu for column\n> %s: ...\", it would make sense to me. But the current message seems not\n> to be clear to me and consistent with other NOTICE messages. Also, the\n> last summary line would not be written if the user cancelled, and\n> someone other than person who used ON_ERROR 'ignore' might check the\n> server logs later.\n\nAgree. I changed the NOTICE message to what you've suggested. Thanks.\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Tue, 26 Mar 2024 11:34:11 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Tue, Mar 26, 2024 at 3:04 PM Bharath Rupireddy\n<bharath.rupireddyforpostgres@gmail.com> wrote:\n>\n> On Tue, Mar 26, 2024 at 9:56 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > > > errmsg(\"data type incompatibility at line %llu for column %s: \\\"%s\\\"\",\n> >\n> > > > I guess it would be better to make the log message clearer to convey\n> > > > what we did for the malformed row. For example, how about something\n> > > > like \"skipping row due to data type incompatibility at line %llu for\n> > > > column %s: \\\"s\\\"\"?\n> > >\n> > > The summary message which gets printed at the end says that \"NOTICE:\n> > > 6 rows were skipped due to data type incompatibility\". Isn't this\n> > > enough? If someone is using ON_ERROR 'ignore', it's quite natural that\n> > > such rows get skipped softly and the summary message can help them,\n> > > no?\n> >\n> > I think that in the main log message we should mention what happened\n> > (or is happening) or what we did (or are doing). If the message \"data\n> > type incompatibility ...\" was in the DETAIL message with the main\n> > message saying something like \"skipping row at line %llu for column\n> > %s: ...\", it would make sense to me. But the current message seems not\n> > to be clear to me and consistent with other NOTICE messages. Also, the\n> > last summary line would not be written if the user cancelled, and\n> > someone other than person who used ON_ERROR 'ignore' might check the\n> > server logs later.\n>\n> Agree. I changed the NOTICE message to what you've suggested. Thanks.\n>\n\nThank you for updating the patch! Looks good to me.\n\nPlease find the attached patch. I've made some changes for the\ndocumentation and the commit message. I'll push it, barring any\nobjections.\n\nRegards,\n\n--\nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Tue, 26 Mar 2024 17:16:10 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Tue, Mar 26, 2024 at 1:46 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> Thank you for updating the patch! Looks good to me.\n>\n> Please find the attached patch. I've made some changes for the\n> documentation and the commit message. I'll push it, barring any\n> objections.\n\nThanks. v12 patch LGTM.\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 26 Mar 2024 15:06:12 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Tue, Mar 26, 2024 at 6:36 PM Bharath Rupireddy\n<bharath.rupireddyforpostgres@gmail.com> wrote:\n>\n> On Tue, Mar 26, 2024 at 1:46 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > Thank you for updating the patch! Looks good to me.\n> >\n> > Please find the attached patch. I've made some changes for the\n> > documentation and the commit message. I'll push it, barring any\n> > objections.\n>\n> Thanks. v12 patch LGTM.\n>\n\nWhile testing the new option, I realized that the tab-completion\ncomplements DEFAULT value, but it doesn't work without single-quotes:\n\npostgres(1:2179134)=# copy test from '/tmp/dump.data' with\n(log_verbosity default );\nERROR: syntax error at or near \"default\"\nLINE 1: ...py test from '/tmp/dump.data' with (log_verbosity default );\n ^\npostgres(1:2179134)=# copy test from '/tmp/dump.data' with\n(log_verbosity 'default' );\nCOPY 0\n\nWhereas VERBOSE works even without single-quotes:\n\npostgres(1:2179134)=# copy test from '/tmp/dump.data' with\n(log_verbosity verbose );\nCOPY 0\n\npostgres(1:2179134)=# copy test from '/tmp/dump.data' with\n(log_verbosity 'verbose' );\nCOPY 0\n\nWhich could confuse users. This is because DEFAULT is a reserved\nkeyword and the COPY option doesn't accept them as an option value.\n\nI think that there are two options to handle it:\n\n1. change COPY grammar to accept DEFAULT as an option value.\n2. change tab-completion to complement 'DEFAULT' instead of DEFAULT,\nand update the doc too.\n\nAs for the documentation, we can add single-quotes as follows:\n\n ENCODING '<replaceable class=\"parameter\">encoding_name</replaceable>'\n+ LOG_VERBOSITY [ '<replaceable class=\"parameter\">mode</replaceable>' ]\n\nI thought the option (2) is better but there seems no precedent of\ncomplementing a single-quoted string other than file names. So the\noption (1) could be clearer.\n\nWhat do you think?\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Wed, 27 Mar 2024 11:11:58 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Wed, Mar 27, 2024 at 7:42 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> I think that there are two options to handle it:\n>\n> 1. change COPY grammar to accept DEFAULT as an option value.\n> 2. change tab-completion to complement 'DEFAULT' instead of DEFAULT,\n> and update the doc too.\n>\n> As for the documentation, we can add single-quotes as follows:\n>\n> ENCODING '<replaceable class=\"parameter\">encoding_name</replaceable>'\n> + LOG_VERBOSITY [ '<replaceable class=\"parameter\">mode</replaceable>' ]\n>\n> I thought the option (2) is better but there seems no precedent of\n> complementing a single-quoted string other than file names. So the\n> option (1) could be clearer.\n>\n> What do you think?\n\nThere is another option to change log_verbosity to {none, verbose} or\n{none, skip_row_info} (discuseed here\nhttps://www.postgresql.org/message-id/Zelrqq-pkfkvsjPn%40paquier.xyz\nthat we might extend this option to other use-cases in future). I tend\nto agree with you to support log_verbose to be set to default without\nquotes just to be consistent with other commands that allow that [1].\nAnd, thanks for quickly identifying where to change in the gram.y.\nWith that change, now I have changed all the new tests added to use\nlog_verbosity default without quotes.\n\nFWIW, a recent commit [2] did the same. Therefore, I don't see a\nproblem supporting it that way for COPY log_verbosity.\n\nPlease find the attached v13 patch with the change.\n\n[1]\ncolumn_compression:\n COMPRESSION ColId { $$ = $2; }\n | COMPRESSION DEFAULT { $$ =\npstrdup(\"default\"); }\n ;\n\ncolumn_storage:\n STORAGE ColId { $$ = $2; }\n | STORAGE DEFAULT { $$ =\npstrdup(\"default\"); }\n ;\n\n[2]\ncommit b9424d014e195386a83b0f1fe9f5a8e5727e46ea\nAuthor: Tom Lane <tgl@sss.pgh.pa.us>\nDate: Thu Nov 10 18:20:49 2022 -0500\n\n Support writing \"CREATE/ALTER TABLE ... SET STORAGE DEFAULT\".\n\n--\nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Wed, 27 Mar 2024 23:19:21 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Thu, Mar 28, 2024 at 2:49 AM Bharath Rupireddy\n<bharath.rupireddyforpostgres@gmail.com> wrote:\n>\n> On Wed, Mar 27, 2024 at 7:42 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > I think that there are two options to handle it:\n> >\n> > 1. change COPY grammar to accept DEFAULT as an option value.\n> > 2. change tab-completion to complement 'DEFAULT' instead of DEFAULT,\n> > and update the doc too.\n> >\n> > As for the documentation, we can add single-quotes as follows:\n> >\n> > ENCODING '<replaceable class=\"parameter\">encoding_name</replaceable>'\n> > + LOG_VERBOSITY [ '<replaceable class=\"parameter\">mode</replaceable>' ]\n> >\n> > I thought the option (2) is better but there seems no precedent of\n> > complementing a single-quoted string other than file names. So the\n> > option (1) could be clearer.\n> >\n> > What do you think?\n>\n> There is another option to change log_verbosity to {none, verbose} or\n> {none, skip_row_info} (discuseed here\n> https://www.postgresql.org/message-id/Zelrqq-pkfkvsjPn%40paquier.xyz\n> that we might extend this option to other use-cases in future). I tend\n> to agree with you to support log_verbose to be set to default without\n> quotes just to be consistent with other commands that allow that [1].\n> And, thanks for quickly identifying where to change in the gram.y.\n> With that change, now I have changed all the new tests added to use\n> log_verbosity default without quotes.\n>\n> FWIW, a recent commit [2] did the same. Therefore, I don't see a\n> problem supporting it that way for COPY log_verbosity.\n>\n> Please find the attached v13 patch with the change.\n\nThank you for updating the patch quickly, and sharing the reference.\n\nI think {default, verbose} is a good start and more consistent with\nother similar features. We can add other modes later.\n\nRegarding the syntax change, since copy_generic_opt_arg rule is only\nfor COPY option syntax, the change doesn't affect other syntaxes. I've\nconfirmed the tab-completion works fine.\n\nI'll push the patch, barring any objections.\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Thu, 28 Mar 2024 09:48:05 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On 2024-03-26 17:16, Masahiko Sawada wrote:\n> On Tue, Mar 26, 2024 at 3:04 PM Bharath Rupireddy\n> <bharath.rupireddyforpostgres@gmail.com> wrote:\n>> \n>> On Tue, Mar 26, 2024 at 9:56 AM Masahiko Sawada \n>> <sawada.mshk@gmail.com> wrote:\n>> >\n>> > > > errmsg(\"data type incompatibility at line %llu for column %s: \\\"%s\\\"\",\n>> >\n>> > > > I guess it would be better to make the log message clearer to convey\n>> > > > what we did for the malformed row. For example, how about something\n>> > > > like \"skipping row due to data type incompatibility at line %llu for\n>> > > > column %s: \\\"s\\\"\"?\n>> > >\n>> > > The summary message which gets printed at the end says that \"NOTICE:\n>> > > 6 rows were skipped due to data type incompatibility\". Isn't this\n>> > > enough? If someone is using ON_ERROR 'ignore', it's quite natural that\n>> > > such rows get skipped softly and the summary message can help them,\n>> > > no?\n>> >\n>> > I think that in the main log message we should mention what happened\n>> > (or is happening) or what we did (or are doing). If the message \"data\n>> > type incompatibility ...\" was in the DETAIL message with the main\n>> > message saying something like \"skipping row at line %llu for column\n>> > %s: ...\", it would make sense to me. But the current message seems not\n>> > to be clear to me and consistent with other NOTICE messages. Also, the\n>> > last summary line would not be written if the user cancelled, and\n>> > someone other than person who used ON_ERROR 'ignore' might check the\n>> > server logs later.\n>> \n>> Agree. I changed the NOTICE message to what you've suggested. Thanks.\n>> \n> \n> Thank you for updating the patch! Looks good to me.\n> \n> Please find the attached patch. I've made some changes for the\n> documentation and the commit message. I'll push it, barring any\n> objections.\n> \n> Regards,\n> \n> --\n> Masahiko Sawada\n> Amazon Web Services: https://aws.amazon.com\n\nThanks!\n\nAttached patch fixes the doc, but I'm wondering perhaps it might be \nbetter to modify the codes to prohibit abbreviation of the value.\n\nWhen seeing the query which abbreviates ON_ERROR value, I feel it's not \nobvious what happens compared to other options which tolerates \nabbreviation of the value such as FREEZE or HEADER.\n\n COPY t1 FROM stdin WITH (ON_ERROR);\n\nWhat do you think?\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Thu, 28 Mar 2024 17:13:46 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Thu, Mar 28, 2024 at 1:43 PM torikoshia <torikoshia@oss.nttdata.com> wrote:\n>\n> Attached patch fixes the doc,\n\nMay I know which patch you are referring to? And, what do you mean by\n\"fixes the doc\"?\n\n> but I'm wondering perhaps it might be\n> better to modify the codes to prohibit abbreviation of the value.\n\nPlease help me understand the meaning here.\n\n> When seeing the query which abbreviates ON_ERROR value, I feel it's not\n> obvious what happens compared to other options which tolerates\n> abbreviation of the value such as FREEZE or HEADER.\n>\n> COPY t1 FROM stdin WITH (ON_ERROR);\n>\n> What do you think?\n\nSo, do you mean to prohibit ON_ERROR being specified without any value\nlike in COPY t1 FROM stdin WITH (ON_ERROR);? If yes, I think all the\nother options do allow that [1].\n\nEven if we were to do something like this, shall we discuss this separately?\n\nHaving said that, what do you think of the v13 patch posted upthread?\n\n[1]\npostgres=# COPY t1 FROM stdin WITH (\nDEFAULT ESCAPE FORCE_QUOTE HEADER QUOTE\nDELIMITER FORCE_NOT_NULL FORMAT NULL\nENCODING FORCE_NULL FREEZE ON_ERROR\n\npostgres=# COPY t1 FROM stdin WITH ( QUOTE );\nERROR: relation \"t1\" does not exist\npostgres=# COPY t1 FROM stdin WITH ( DEFAULT );\nERROR: relation \"t1\" does not exist\npostgres=# COPY t1 FROM stdin WITH ( ENCODING );\nERROR: relation \"t1\" does not exist\n\n-- \nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Thu, 28 Mar 2024 13:57:51 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On 2024-03-28 17:27, Bharath Rupireddy wrote:\n> On Thu, Mar 28, 2024 at 1:43 PM torikoshia <torikoshia@oss.nttdata.com> \n> wrote:\n>> \n>> Attached patch fixes the doc,\n> \n> May I know which patch you are referring to? And, what do you mean by\n> \"fixes the doc\"?\n\nUgh, I replied to the wrong thread.\nSorry for making you confused and please ignore it.\n\n>> but I'm wondering perhaps it might be\n>> better to modify the codes to prohibit abbreviation of the value.\n> \n> Please help me understand the meaning here.\n> \n>> When seeing the query which abbreviates ON_ERROR value, I feel it's \n>> not\n>> obvious what happens compared to other options which tolerates\n>> abbreviation of the value such as FREEZE or HEADER.\n>> \n>> COPY t1 FROM stdin WITH (ON_ERROR);\n>> \n>> What do you think?\n> \n> So, do you mean to prohibit ON_ERROR being specified without any value\n> like in COPY t1 FROM stdin WITH (ON_ERROR);? If yes, I think all the\n> other options do allow that [1].\n> \n> Even if we were to do something like this, shall we discuss this \n> separately?\n> \n> Having said that, what do you think of the v13 patch posted upthread?\n> \n> [1]\n> postgres=# COPY t1 FROM stdin WITH (\n> DEFAULT ESCAPE FORCE_QUOTE HEADER QUOTE\n> DELIMITER FORCE_NOT_NULL FORMAT NULL\n> ENCODING FORCE_NULL FREEZE ON_ERROR\n> \n> postgres=# COPY t1 FROM stdin WITH ( QUOTE );\n> ERROR: relation \"t1\" does not exist\n> postgres=# COPY t1 FROM stdin WITH ( DEFAULT );\n> ERROR: relation \"t1\" does not exist\n> postgres=# COPY t1 FROM stdin WITH ( ENCODING );\n> ERROR: relation \"t1\" does not exist\n\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Thu, 28 Mar 2024 21:36:26 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Thu, Mar 28, 2024 at 5:28 PM Bharath Rupireddy\n<bharath.rupireddyforpostgres@gmail.com> wrote:\n>\n> On Thu, Mar 28, 2024 at 1:43 PM torikoshia <torikoshia@oss.nttdata.com> wrote:\n> >\n> > Attached patch fixes the doc,\n>\n> May I know which patch you are referring to? And, what do you mean by\n> \"fixes the doc\"?\n>\n> > but I'm wondering perhaps it might be\n> > better to modify the codes to prohibit abbreviation of the value.\n>\n> Please help me understand the meaning here.\n>\n> > When seeing the query which abbreviates ON_ERROR value, I feel it's not\n> > obvious what happens compared to other options which tolerates\n> > abbreviation of the value such as FREEZE or HEADER.\n> >\n> > COPY t1 FROM stdin WITH (ON_ERROR);\n> >\n> > What do you think?\n>\n> So, do you mean to prohibit ON_ERROR being specified without any value\n> like in COPY t1 FROM stdin WITH (ON_ERROR);? If yes, I think all the\n> other options do allow that [1].\n>\n> Even if we were to do something like this, shall we discuss this separately?\n>\n> Having said that, what do you think of the v13 patch posted upthread?\n>\n\nThis topic accidentally jumped in this thread, but it made me think\nthat the same might be true for the LOG_VERBOSITY option. That is,\nsince the LOG_VERBOSITY option is an enum parameter, it might make\nmore sense to require the value, instead of making the value optional.\nFor example, the following command could not be obvious for users:\n\nCOPY test FROM stdin (ON_ERROR ignore, LOG_VERBOSITY);\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Thu, 28 Mar 2024 22:00:43 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On 2024-03-28 21:36, torikoshia wrote:\n> On 2024-03-28 17:27, Bharath Rupireddy wrote:\n>> On Thu, Mar 28, 2024 at 1:43 PM torikoshia \n>> <torikoshia@oss.nttdata.com> wrote:\n>>> \n>>> Attached patch fixes the doc,\n>> \n>> May I know which patch you are referring to? And, what do you mean by\n>> \"fixes the doc\"?\n> \n> Ugh, I replied to the wrong thread.\n> Sorry for making you confused and please ignore it.\n> \n>>> but I'm wondering perhaps it might be\n>>> better to modify the codes to prohibit abbreviation of the value.\n>> \n>> Please help me understand the meaning here.\n>> \n>>> When seeing the query which abbreviates ON_ERROR value, I feel it's \n>>> not\n>>> obvious what happens compared to other options which tolerates\n>>> abbreviation of the value such as FREEZE or HEADER.\n>>> \n>>> COPY t1 FROM stdin WITH (ON_ERROR);\n>>> \n>>> What do you think?\n>> \n>> So, do you mean to prohibit ON_ERROR being specified without any value\n>> like in COPY t1 FROM stdin WITH (ON_ERROR);? If yes, I think all the\n>> other options do allow that [1].\n>> \n>> Even if we were to do something like this, shall we discuss this \n>> separately?\n>> \n>> Having said that, what do you think of the v13 patch posted upthread?\n\nIt looks good to me other than what Sawada-san lastly pointed out.\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Fri, 29 Mar 2024 18:59:33 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Thu, Mar 28, 2024 at 6:31 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> That is,\n> since the LOG_VERBOSITY option is an enum parameter, it might make\n> more sense to require the value, instead of making the value optional.\n> For example, the following command could not be obvious for users:\n>\n> COPY test FROM stdin (ON_ERROR ignore, LOG_VERBOSITY);\n\nAgreed. Please see the attached v14 patch. The LOG_VERBOSITY now needs\na value to be specified. Note that I've not added any test for this\ncase as there seemed to be no such tests so far generating \"ERROR:\n<<option>> requires a parameter\". I don't mind adding one for\nLOG_VERBOSITY though.\n\n-- \nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Sat, 30 Mar 2024 19:35:13 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Sat, Mar 30, 2024 at 11:05 PM Bharath Rupireddy\n<bharath.rupireddyforpostgres@gmail.com> wrote:\n>\n> On Thu, Mar 28, 2024 at 6:31 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > That is,\n> > since the LOG_VERBOSITY option is an enum parameter, it might make\n> > more sense to require the value, instead of making the value optional.\n> > For example, the following command could not be obvious for users:\n> >\n> > COPY test FROM stdin (ON_ERROR ignore, LOG_VERBOSITY);\n>\n> Agreed. Please see the attached v14 patch.\n\nThank you for updating the patch!\n\n> The LOG_VERBOSITY now needs\n> a value to be specified. Note that I've not added any test for this\n> case as there seemed to be no such tests so far generating \"ERROR:\n> <<option>> requires a parameter\". I don't mind adding one for\n> LOG_VERBOSITY though.\n\n+1\n\nOne minor point:\n\n ENCODING '<replaceable class=\"parameter\">encoding_name</replaceable>'\n+ LOG_VERBOSITY [ <replaceable class=\"parameter\">mode</replaceable> ]\n </synopsis>\n\n'[' and ']' are not necessary because the value is no longer optional.\n\nI've attached the updated patch. I'll push it, barring any objections.\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Mon, 1 Apr 2024 10:03:22 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Mon, Apr 1, 2024 at 10:03 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Sat, Mar 30, 2024 at 11:05 PM Bharath Rupireddy\n> <bharath.rupireddyforpostgres@gmail.com> wrote:\n> >\n> > On Thu, Mar 28, 2024 at 6:31 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> > >\n> > > That is,\n> > > since the LOG_VERBOSITY option is an enum parameter, it might make\n> > > more sense to require the value, instead of making the value optional.\n> > > For example, the following command could not be obvious for users:\n> > >\n> > > COPY test FROM stdin (ON_ERROR ignore, LOG_VERBOSITY);\n> >\n> > Agreed. Please see the attached v14 patch.\n>\n> Thank you for updating the patch!\n>\n> > The LOG_VERBOSITY now needs\n> > a value to be specified. Note that I've not added any test for this\n> > case as there seemed to be no such tests so far generating \"ERROR:\n> > <<option>> requires a parameter\". I don't mind adding one for\n> > LOG_VERBOSITY though.\n>\n> +1\n>\n> One minor point:\n>\n> ENCODING '<replaceable class=\"parameter\">encoding_name</replaceable>'\n> + LOG_VERBOSITY [ <replaceable class=\"parameter\">mode</replaceable> ]\n> </synopsis>\n>\n> '[' and ']' are not necessary because the value is no longer optional.\n>\n> I've attached the updated patch. I'll push it, barring any objections.\n>\n\nPushed.\n\nRegards,\n\n--\nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 2 Apr 2024 09:53:57 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
},
{
"msg_contents": "On Tue, Apr 02, 2024 at 09:53:57AM +0900, Masahiko Sawada wrote:\n> Pushed.\n\nThanks for following up with this thread.\n--\nMichael",
"msg_date": "Thu, 4 Apr 2024 10:41:47 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Add new error_action COPY ON_ERROR \"log\""
}
] |
[
{
"msg_contents": "Hey,\n\nIn a nearby user complaint email [1] some missing information regarding\nownership reassignment came to light. I took that and went a bit further\nto add what I felt was further missing information and context for how the\nprivilege system is designed. I've tried to formalize and label existing\nconcepts a bit and updated the glossary accordingly.\n\nThe attached is a partial rewrite of the patch on the linked post after\nthose comments were taken into consideration.\n\nThe new glossary entry for privileges defines various qualifications of the\nterm that are used in the new prose. I've marked up each of the variants\nand point them all back to the main entry. I didn't try to incorporate\nthose terms, or even really look, anywhere else in the documentation. If\nthe general idea is accepted that kind of work can be done as a follow-up.\n\nDavid J.\n\n[1]\nhttps://www.postgresql.org/message-id/d294818d12280f6223ddf169ab5454927f5186b6.camel%40cybertec.at",
"msg_date": "Thu, 25 Jan 2024 13:59:22 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": true,
"msg_subject": "[Doc] Improvements to ddl.sgl Privileges Section and Glossary"
},
{
"msg_contents": "Any thoughts?\n\nOn Thu, Jan 25, 2024 at 1:59 PM David G. Johnston <\ndavid.g.johnston@gmail.com> wrote:\n\n> Hey,\n>\n> In a nearby user complaint email [1] some missing information regarding\n> ownership reassignment came to light. I took that and went a bit further\n> to add what I felt was further missing information and context for how the\n> privilege system is designed. I've tried to formalize and label existing\n> concepts a bit and updated the glossary accordingly.\n>\n> The attached is a partial rewrite of the patch on the linked post after\n> those comments were taken into consideration.\n>\n> The new glossary entry for privileges defines various qualifications of\n> the term that are used in the new prose. I've marked up each of the\n> variants and point them all back to the main entry. I didn't try to\n> incorporate those terms, or even really look, anywhere else in the\n> documentation. If the general idea is accepted that kind of work can be\n> done as a follow-up.\n>\n> David J.\n>\n> [1]\n> https://www.postgresql.org/message-id/d294818d12280f6223ddf169ab5454927f5186b6.camel%40cybertec.at\n>\n>\n\nAny thoughts?On Thu, Jan 25, 2024 at 1:59 PM David G. Johnston <david.g.johnston@gmail.com> wrote:Hey,In a nearby user complaint email [1] some missing information regarding ownership reassignment came to light. I took that and went a bit further to add what I felt was further missing information and context for how the privilege system is designed. I've tried to formalize and label existing concepts a bit and updated the glossary accordingly.The attached is a partial rewrite of the patch on the linked post after those comments were taken into consideration.The new glossary entry for privileges defines various qualifications of the term that are used in the new prose. I've marked up each of the variants and point them all back to the main entry. I didn't try to incorporate those terms, or even really look, anywhere else in the documentation. If the general idea is accepted that kind of work can be done as a follow-up.David J.[1] https://www.postgresql.org/message-id/d294818d12280f6223ddf169ab5454927f5186b6.camel%40cybertec.at",
"msg_date": "Mon, 22 Apr 2024 14:29:54 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: [Doc] Improvements to ddl.sgl Privileges Section and Glossary"
}
] |
[
{
"msg_contents": "Hi,\n\nAttached is a simple patch to rename setup_cancel_handler()\nin pg_dump/parallel.c. \n\nI am proposing it because there is a public function with\nthe same name in fe_utils/cancel.c. I know pg_dump/parallel.c\ndoes not include fe_utils/cancel.h, so there is no conflict,\nbut I think it is better to use different names to reduce\npossible confusion. \n\nI guess there was no concerns when setup_cancel_handler in\npg_dump/parallel.c was introduced because the same name\nfunction was not in fe_utils that could be used in common\nbetween client tools.. The public setup_cancel_handler in\nfe_utils was introduced in a4fd3aa719e, where this function\nwas moved from psql.\n\nRegards,\nYugo Nagata\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>",
"msg_date": "Fri, 26 Jan 2024 09:42:45 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Rename setup_cancel_handler in pg_dump"
},
{
"msg_contents": "> On 26 Jan 2024, at 01:42, Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n\n> I am proposing it because there is a public function with\n> the same name in fe_utils/cancel.c. I know pg_dump/parallel.c\n> does not include fe_utils/cancel.h, so there is no conflict,\n> but I think it is better to use different names to reduce\n> possible confusion. \n\nGiven that a \"git grep setup_cancel_hander\" returns hits in pg_dump along with\nother frontend utils, I can see the risk of confusion.\n\n-setup_cancel_handler(void)\n+pg_dump_setup_cancel_handler(void)\n\nWe don't have any other functions prefixed with pg_dump_, based on the naming\nof the surrounding code in the file I wonder if set_cancel_handler is a more\nappropriate name?\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Tue, 30 Jan 2024 13:44:28 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: Rename setup_cancel_handler in pg_dump"
},
{
"msg_contents": "On Tue, 30 Jan 2024 13:44:28 +0100\nDaniel Gustafsson <daniel@yesql.se> wrote:\n\n> > On 26 Jan 2024, at 01:42, Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> \n> > I am proposing it because there is a public function with\n> > the same name in fe_utils/cancel.c. I know pg_dump/parallel.c\n> > does not include fe_utils/cancel.h, so there is no conflict,\n> > but I think it is better to use different names to reduce\n> > possible confusion. \n> \n> Given that a \"git grep setup_cancel_hander\" returns hits in pg_dump along with\n> other frontend utils, I can see the risk of confusion.\n\nThank you for looking into it!\n \n> -setup_cancel_handler(void)\n> +pg_dump_setup_cancel_handler(void)\n> \n> We don't have any other functions prefixed with pg_dump_, based on the naming\n> of the surrounding code in the file I wonder if set_cancel_handler is a more\n> appropriate name?\n\nAgreed. Here is a updated patch.\n\nRegards,\nYugo Nagata\n\n> \n> --\n> Daniel Gustafsson\n> \n\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>",
"msg_date": "Thu, 1 Feb 2024 10:21:27 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: Rename setup_cancel_handler in pg_dump"
},
{
"msg_contents": "> On 1 Feb 2024, at 02:21, Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> On Tue, 30 Jan 2024 13:44:28 +0100\n> Daniel Gustafsson <daniel@yesql.se> wrote:\n\n>> -setup_cancel_handler(void)\n>> +pg_dump_setup_cancel_handler(void)\n>> \n>> We don't have any other functions prefixed with pg_dump_, based on the naming\n>> of the surrounding code in the file I wonder if set_cancel_handler is a more\n>> appropriate name?\n> \n> Agreed. Here is a updated patch.\n\nSleeping on it I still think this is a good idea, and hearing no objections I\nwent ahead with this. Thanks for the patch!\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Wed, 7 Feb 2024 22:59:48 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: Rename setup_cancel_handler in pg_dump"
},
{
"msg_contents": "On Wed, 7 Feb 2024 22:59:48 +0100\nDaniel Gustafsson <daniel@yesql.se> wrote:\n\n> > On 1 Feb 2024, at 02:21, Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> > On Tue, 30 Jan 2024 13:44:28 +0100\n> > Daniel Gustafsson <daniel@yesql.se> wrote:\n> \n> >> -setup_cancel_handler(void)\n> >> +pg_dump_setup_cancel_handler(void)\n> >> \n> >> We don't have any other functions prefixed with pg_dump_, based on the naming\n> >> of the surrounding code in the file I wonder if set_cancel_handler is a more\n> >> appropriate name?\n> > \n> > Agreed. Here is a updated patch.\n> \n> Sleeping on it I still think this is a good idea, and hearing no objections I\n> went ahead with this. Thanks for the patch!\n\nThank you!\n\nRegards,\nYugo Nagata\n\n> \n> --\n> Daniel Gustafsson\n> \n\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>\n\n\n",
"msg_date": "Thu, 8 Feb 2024 10:07:49 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: Rename setup_cancel_handler in pg_dump"
}
] |
[
{
"msg_contents": "Hi,\n\nI found that the documentation of COPY ON_ERROR said\nCOPY stops operation at the first error when \n\"ON_ERROR is not specified.\", but it also stop when\nON_ERROR is specified to the default value, \"stop\".\n\nI attached a very small patch to fix this just for\nmaking the description more accurate.\n\nRegards,\nYugo Nagata \n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>",
"msg_date": "Fri, 26 Jan 2024 11:28:29 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Fri, Jan 26, 2024 at 11:28 AM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n>\n> Hi,\n>\n> I found that the documentation of COPY ON_ERROR said\n> COPY stops operation at the first error when\n> \"ON_ERROR is not specified.\", but it also stop when\n> ON_ERROR is specified to the default value, \"stop\".\n>\n> I attached a very small patch to fix this just for\n> making the description more accurate.\n\nThank you for the patch!\n\n+1 to fix it.\n\n- <literal>ON_ERROR</literal> is not specified. This\n- should not lead to problems in the event of a <command>COPY\n+ <literal>ON_ERROR</literal> is not specified or <literal>stop</literal>.\n+ This should not lead to problems in the event of a <command>COPY\n\nHow about the followings for consistency with the description of the\nON_ERROR option?\n\nCOPY stops operation at the first error if the stop value is specified\nto the ON_ERROR option. This should not lead to ...\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Fri, 26 Jan 2024 13:59:09 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Fri, 26 Jan 2024 13:59:09 +0900\nMasahiko Sawada <sawada.mshk@gmail.com> wrote:\n\n> On Fri, Jan 26, 2024 at 11:28 AM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> >\n> > Hi,\n> >\n> > I found that the documentation of COPY ON_ERROR said\n> > COPY stops operation at the first error when\n> > \"ON_ERROR is not specified.\", but it also stop when\n> > ON_ERROR is specified to the default value, \"stop\".\n> >\n> > I attached a very small patch to fix this just for\n> > making the description more accurate.\n> \n> Thank you for the patch!\n> \n> +1 to fix it.\n> \n> - <literal>ON_ERROR</literal> is not specified. This\n> - should not lead to problems in the event of a <command>COPY\n> + <literal>ON_ERROR</literal> is not specified or <literal>stop</literal>.\n> + This should not lead to problems in the event of a <command>COPY\n> \n> How about the followings for consistency with the description of the\n> ON_ERROR option?\n> \n> COPY stops operation at the first error if the stop value is specified\n> to the ON_ERROR option. This should not lead to ...\n\nThank you for you review. However, after posting the previous patch, \nI noticed that I overlooked ON_ERROR works only for errors due to data\ntype incompatibility (that is mentioned as \"malformed data\" in the \nON_ERROR description, though). \n\nSo, how about rewriting this like:\n\n COPY stops operation at the first error unless the error is due to data\n type incompatibility and a value other than stop is specified to the\n ON_ERROR option.\n\nI attached the updated patch.\n\nRegards,\nYugo Nagata\n\n> \n> Regards,\n> \n> -- \n> Masahiko Sawada\n> Amazon Web Services: https://aws.amazon.com\n\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>",
"msg_date": "Fri, 26 Jan 2024 14:40:11 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Fri, Jan 26, 2024 at 2:40 PM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n>\n> On Fri, 26 Jan 2024 13:59:09 +0900\n> Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> > On Fri, Jan 26, 2024 at 11:28 AM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> > >\n> > > Hi,\n> > >\n> > > I found that the documentation of COPY ON_ERROR said\n> > > COPY stops operation at the first error when\n> > > \"ON_ERROR is not specified.\", but it also stop when\n> > > ON_ERROR is specified to the default value, \"stop\".\n> > >\n> > > I attached a very small patch to fix this just for\n> > > making the description more accurate.\n> >\n> > Thank you for the patch!\n> >\n> > +1 to fix it.\n> >\n> > - <literal>ON_ERROR</literal> is not specified. This\n> > - should not lead to problems in the event of a <command>COPY\n> > + <literal>ON_ERROR</literal> is not specified or <literal>stop</literal>.\n> > + This should not lead to problems in the event of a <command>COPY\n> >\n> > How about the followings for consistency with the description of the\n> > ON_ERROR option?\n> >\n> > COPY stops operation at the first error if the stop value is specified\n> > to the ON_ERROR option. This should not lead to ...\n>\n> Thank you for you review. However, after posting the previous patch,\n> I noticed that I overlooked ON_ERROR works only for errors due to data\n> type incompatibility (that is mentioned as \"malformed data\" in the\n> ON_ERROR description, though).\n\nRight.\n\n>\n> So, how about rewriting this like:\n>\n> COPY stops operation at the first error unless the error is due to data\n> type incompatibility and a value other than stop is specified to the\n> ON_ERROR option.\n\nHmm, this sentence seems not very readable to me, especially the \"COPY\nstops ... unless ... a value other than stop is specified ...\" part. I\nthink we can simplify it:\n\nCOPY stops operation at the first data type incompatibility error if\nthe stop value is specified to the ON_ERROR option.\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Fri, 26 Jan 2024 15:26:55 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Thu, Jan 25, 2024 at 10:40 PM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n\n> On Fri, 26 Jan 2024 13:59:09 +0900\n> Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> > On Fri, Jan 26, 2024 at 11:28 AM Yugo NAGATA <nagata@sraoss.co.jp>\n> wrote:\n> > >\n> > > Hi,\n> > >\n> > > I found that the documentation of COPY ON_ERROR said\n> > > COPY stops operation at the first error when\n> > > \"ON_ERROR is not specified.\", but it also stop when\n> > > ON_ERROR is specified to the default value, \"stop\".\n> > >\n>\n>\nI'm finding the current wording surrounding ON_ERROR to not fit in with the\nrest of the page. I've tried to improve things by being a bit more\ninvasive.\n\nThis first hunk updates the description of the COPY command to include\ndescribing the purpose of the ON_ERROR clause.\n\nI too am concerned about the word \"parsed\" here, and \"malformed\" in the\nmore detailed descriptions; this would need to be modified to better\nreflect the circumstances under which ignore happens.\n\ndiff --git a/doc/src/sgml/ref/copy.sgml b/doc/src/sgml/ref/copy.sgml\nindex 21a5c4a052..5fe4c9f747 100644\n--- a/doc/src/sgml/ref/copy.sgml\n+++ b/doc/src/sgml/ref/copy.sgml\n@@ -90,6 +90,14 @@ COPY { <replaceable\nclass=\"parameter\">table_name</replaceable> [ ( <replaceable\n in the <structname>pg_stat_progress_copy</structname> view. See\n <xref linkend=\"copy-progress-reporting\"/> for details.\n </para>\n+\n+ <para>\n+ By default, <command>COPY</command> will abort if it encounters errors.\n+ For non-binary format <command>COPY FROM</command> the user can specify\n+ to instead ignore input rows that cannot be parsed by specifying\n+ the <literal>ignore</literal> option to the <literal>ON_ERROR</literal>\n+ clause.\n+ </para>\n </refsect1>\n\n <refsect1>\n\nThe use of the word \"Currently\" stood out to me when reading the next\nhunk. We always document current reality and don't call out that fact. We\ndo not imply some future feature may change how this all works. On a\nrelated note, right now we have stop and ignore, which are basically enums\njust like we have for format (csv, text, binary). Unlike format, though,\nthis option requires single quotes. Why is that? I did keep with not\nspecifying the enum in the main syntax block since format doesn't as well;\nthough writing { stop | ignore } seemed quite appealing.\n\nThe rest of the page indicates what the default is in a sentence by itself,\nnot as a parenthetical next to the option.\n\nThe command limitations seemed worthy of a separate paragraph, though it\nrepeats the description which isn't great. I'm going to sleep on this one.\n\n@@ -379,17 +387,16 @@ COPY { <replaceable\nclass=\"parameter\">table_name</replaceable> [ ( <replaceable\n <listitem>\n <para>\n Specifies which <replaceable class=\"parameter\">\n- error_action</replaceable> to perform when there is malformed data\nin the input.\n- Currently, only <literal>stop</literal> (default) and\n<literal>ignore</literal>\n- values are supported.\n- If the <literal>stop</literal> value is specified,\n- <command>COPY</command> stops operation at the first error.\n- If the <literal>ignore</literal> value is specified,\n- <command>COPY</command> skips malformed data and continues copying\ndata.\n- The option is allowed only in <command>COPY FROM</command>.\n- Only <literal>stop</literal> value is allowed when\n- using <literal>binary</literal> format.\n+ error_action</replaceable> to perform when encountering a malformed\ninput row:\n+ <literal>stop</literal> or <literal>ignore</literal>.\n+ A value of <literal>stop</literal> means fail the command, while\n+ <literal>ignore</literal> means discard the input row and continue\nwith the next one.\n+ The default is <literal>stop</literal>\n </para>\n+ <para>\n+ The ignore option is applicable only for <command>COPY FROM</command>\n+ when the <literal>FORMAT</literal> is <literal>text</literal>\n+ or <literal>csv</literal>.\n+ </para>\n </listitem>\n </varlistentry>\n\nThe following was, IMO, too much text about something not to worry about,\nCOPY TO and ignore mode. The point is dead tuples on error and running\nvacuum. It doesn't really even matter what caused the error, though if the\nerror was even before rows started to be imported then obviously there\nwould be no dead tuples.\n\nOh, and the word \"first\" really isn't adding anything here that we cannot\nreasonably leave to common sense, IMO. We either ignore all errors or stop\non the first one. There isn't a stop mode that is capable of bypassing\nerrors and the ignore mode doesn't have a \"first n\" option so one assumes\nall errors are ignored.\n\n@@ -576,15 +583,12 @@ COPY <replaceable\nclass=\"parameter\">count</replaceable>\n </para>\n\n <para>\n- <command>COPY</command> stops operation at the first error when\n- <literal>ON_ERROR</literal> is not specified. This\n- should not lead to problems in the event of a <command>COPY\n- TO</command>, but the target table will already have received\n- earlier rows in a <command>COPY FROM</command>. These rows will not\n- be visible or accessible, but they still occupy disk space. This might\n- amount to a considerable amount of wasted disk space if the failure\n- happened well into a large copy operation. You might wish to invoke\n- <command>VACUUM</command> to recover the wasted space.\n+ A failed <command>COPY FROM</command> command will have performed\n+ physical insertion of all rows prior to the malformed one.\n+ While these rows will not be visible or accessible, they still occupy\n+ disk space. This might amount to a considerable amount of wasted disk\n+ space if the failure happened well into a large copy operation.\n+ <command>VACUUM</command> should be used to recover the wasted space.\n </para>\n\n <para>\n\nDavid J.\n\nOn Thu, Jan 25, 2024 at 10:40 PM Yugo NAGATA <nagata@sraoss.co.jp> wrote:On Fri, 26 Jan 2024 13:59:09 +0900\nMasahiko Sawada <sawada.mshk@gmail.com> wrote:\n\n> On Fri, Jan 26, 2024 at 11:28 AM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> >\n> > Hi,\n> >\n> > I found that the documentation of COPY ON_ERROR said\n> > COPY stops operation at the first error when\n> > \"ON_ERROR is not specified.\", but it also stop when\n> > ON_ERROR is specified to the default value, \"stop\".\n> >I'm finding the current wording surrounding ON_ERROR to not fit in with the rest of the page. I've tried to improve things by being a bit more invasive.This first hunk updates the description of the COPY command to include describing the purpose of the ON_ERROR clause.I too am concerned about the word \"parsed\" here, and \"malformed\" in the more detailed descriptions; this would need to be modified to better reflect the circumstances under which ignore happens.diff --git a/doc/src/sgml/ref/copy.sgml b/doc/src/sgml/ref/copy.sgmlindex 21a5c4a052..5fe4c9f747 100644--- a/doc/src/sgml/ref/copy.sgml+++ b/doc/src/sgml/ref/copy.sgml@@ -90,6 +90,14 @@ COPY { <replaceable class=\"parameter\">table_name</replaceable> [ ( <replaceable in the <structname>pg_stat_progress_copy</structname> view. See <xref linkend=\"copy-progress-reporting\"/> for details. </para>++ <para>+ By default, <command>COPY</command> will abort if it encounters errors.+ For non-binary format <command>COPY FROM</command> the user can specify+ to instead ignore input rows that cannot be parsed by specifying+ the <literal>ignore</literal> option to the <literal>ON_ERROR</literal>+ clause.+ </para> </refsect1> <refsect1>The use of the word \"Currently\" stood out to me when reading the next hunk. We always document current reality and don't call out that fact. We do not imply some future feature may change how this all works. On a related note, right now we have stop and ignore, which are basically enums just like we have for format (csv, text, binary). Unlike format, though, this option requires single quotes. Why is that? I did keep with not specifying the enum in the main syntax block since format doesn't as well; though writing { stop | ignore } seemed quite appealing.The rest of the page indicates what the default is in a sentence by itself, not as a parenthetical next to the option.The command limitations seemed worthy of a separate paragraph, though it repeats the description which isn't great. I'm going to sleep on this one.@@ -379,17 +387,16 @@ COPY { <replaceable class=\"parameter\">table_name</replaceable> [ ( <replaceable <listitem> <para> Specifies which <replaceable class=\"parameter\">- error_action</replaceable> to perform when there is malformed data in the input.- Currently, only <literal>stop</literal> (default) and <literal>ignore</literal>- values are supported.- If the <literal>stop</literal> value is specified,- <command>COPY</command> stops operation at the first error.- If the <literal>ignore</literal> value is specified,- <command>COPY</command> skips malformed data and continues copying data.- The option is allowed only in <command>COPY FROM</command>.- Only <literal>stop</literal> value is allowed when- using <literal>binary</literal> format.+ error_action</replaceable> to perform when encountering a malformed input row:+ <literal>stop</literal> or <literal>ignore</literal>.+ A value of <literal>stop</literal> means fail the command, while+ <literal>ignore</literal> means discard the input row and continue with the next one.+ The default is <literal>stop</literal> </para>+ <para>+ The ignore option is applicable only for <command>COPY FROM</command>+ when the <literal>FORMAT</literal> is <literal>text</literal>+ or <literal>csv</literal>.+ </para> </listitem> </varlistentry>The following was, IMO, too much text about something not to worry about, COPY TO and ignore mode. The point is dead tuples on error and running vacuum. It doesn't really even matter what caused the error, though if the error was even before rows started to be imported then obviously there would be no dead tuples.Oh, and the word \"first\" really isn't adding anything here that we cannot reasonably leave to common sense, IMO. We either ignore all errors or stop on the first one. There isn't a stop mode that is capable of bypassing errors and the ignore mode doesn't have a \"first n\" option so one assumes all errors are ignored.@@ -576,15 +583,12 @@ COPY <replaceable class=\"parameter\">count</replaceable> </para> <para>- <command>COPY</command> stops operation at the first error when- <literal>ON_ERROR</literal> is not specified. This- should not lead to problems in the event of a <command>COPY- TO</command>, but the target table will already have received- earlier rows in a <command>COPY FROM</command>. These rows will not- be visible or accessible, but they still occupy disk space. This might- amount to a considerable amount of wasted disk space if the failure- happened well into a large copy operation. You might wish to invoke- <command>VACUUM</command> to recover the wasted space.+ A failed <command>COPY FROM</command> command will have performed+ physical insertion of all rows prior to the malformed one.+ While these rows will not be visible or accessible, they still occupy+ disk space. This might amount to a considerable amount of wasted disk+ space if the failure happened well into a large copy operation.+ <command>VACUUM</command> should be used to recover the wasted space. </para> <para>David J.",
"msg_date": "Thu, 25 Jan 2024 23:33:22 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Fri, 26 Jan 2024 15:26:55 +0900\nMasahiko Sawada <sawada.mshk@gmail.com> wrote:\n\n> On Fri, Jan 26, 2024 at 2:40 PM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> >\n> > On Fri, 26 Jan 2024 13:59:09 +0900\n> > Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > > On Fri, Jan 26, 2024 at 11:28 AM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> > > >\n> > > > Hi,\n> > > >\n> > > > I found that the documentation of COPY ON_ERROR said\n> > > > COPY stops operation at the first error when\n> > > > \"ON_ERROR is not specified.\", but it also stop when\n> > > > ON_ERROR is specified to the default value, \"stop\".\n> > > >\n> > > > I attached a very small patch to fix this just for\n> > > > making the description more accurate.\n> > >\n> > > Thank you for the patch!\n> > >\n> > > +1 to fix it.\n> > >\n> > > - <literal>ON_ERROR</literal> is not specified. This\n> > > - should not lead to problems in the event of a <command>COPY\n> > > + <literal>ON_ERROR</literal> is not specified or <literal>stop</literal>.\n> > > + This should not lead to problems in the event of a <command>COPY\n> > >\n> > > How about the followings for consistency with the description of the\n> > > ON_ERROR option?\n> > >\n> > > COPY stops operation at the first error if the stop value is specified\n> > > to the ON_ERROR option. This should not lead to ...\n> >\n> > Thank you for you review. However, after posting the previous patch,\n> > I noticed that I overlooked ON_ERROR works only for errors due to data\n> > type incompatibility (that is mentioned as \"malformed data\" in the\n> > ON_ERROR description, though).\n> \n> Right.\n> \n> >\n> > So, how about rewriting this like:\n> >\n> > COPY stops operation at the first error unless the error is due to data\n> > type incompatibility and a value other than stop is specified to the\n> > ON_ERROR option.\n> \n> Hmm, this sentence seems not very readable to me, especially the \"COPY\n> stops ... unless ... a value other than stop is specified ...\" part. I\n> think we can simplify it:\n\nI can agree with your opinion on the readability, but...\n\n> COPY stops operation at the first data type incompatibility error if\n> the stop value is specified to the ON_ERROR option.\n\nThis statement doesn't explain COPY also stops when an error other than\ndata type incompatibility (e.g. constrain violations) occurs.\n\nMaybe, we can separate the sentese to two, for example:\n\n COPY stops operation at the first error. (The exception is if the error\n is due to data type incompatibility and a value other than stop is specified\n to the ON_ERROR option.)\n\nRegards,\nYugo Nagata\n\n> Regards,\n> \n> -- \n> Masahiko Sawada\n> Amazon Web Services: https://aws.amazon.com\n\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>\n\n\n",
"msg_date": "Fri, 26 Jan 2024 15:48:10 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Thursday, January 25, 2024, Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n\n>\n> Maybe, we can separate the sentese to two, for example:\n>\n> COPY stops operation at the first error. (The exception is if the error\n> is due to data type incompatibility and a value other than stop is\n> specified\n> to the ON_ERROR option.)\n>\n\nI’d lean more toward saying:\n\nCopy from can be instructed to ignore errors that arise from casting input\ndata to the data types of the target columns by setting the on_error option\nto ignore. Skipping the entire input row in the process.\n\nThe last part is because another way to ignore would be to set null values\nfor those columns.\n\nThat a command stops on an error is the assumed behavior throughout the\nsystem, writing “copy stops operation at the first error.” just seems\nreally unnecessary.\n\nI will need to make this tweak and probably a couple others to my own\nsuggestions in 12 hours or so.\n\nDavid J.\n\nOn Thursday, January 25, 2024, Yugo NAGATA <nagata@sraoss.co.jp> wrote:\nMaybe, we can separate the sentese to two, for example:\n\n COPY stops operation at the first error. (The exception is if the error\n is due to data type incompatibility and a value other than stop is specified\n to the ON_ERROR option.)\nI’d lean more toward saying:Copy from can be instructed to ignore errors that arise from casting input data to the data types of the target columns by setting the on_error option to ignore. Skipping the entire input row in the process.The last part is because another way to ignore would be to set null values for those columns.That a command stops on an error is the assumed behavior throughout the system, writing “copy stops operation at the first error.” just seems really unnecessary.I will need to make this tweak and probably a couple others to my own suggestions in 12 hours or so.David J.",
"msg_date": "Fri, 26 Jan 2024 00:00:57 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Thu, 25 Jan 2024 23:33:22 -0700\n\"David G. Johnston\" <david.g.johnston@gmail.com> wrote:\n\n> On Thu, Jan 25, 2024 at 10:40 PM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> \n> > On Fri, 26 Jan 2024 13:59:09 +0900\n> > Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > > On Fri, Jan 26, 2024 at 11:28 AM Yugo NAGATA <nagata@sraoss.co.jp>\n> > wrote:\n> > > >\n> > > > Hi,\n> > > >\n> > > > I found that the documentation of COPY ON_ERROR said\n> > > > COPY stops operation at the first error when\n> > > > \"ON_ERROR is not specified.\", but it also stop when\n> > > > ON_ERROR is specified to the default value, \"stop\".\n> > > >\n> >\n> >\n> I'm finding the current wording surrounding ON_ERROR to not fit in with the\n> rest of the page. I've tried to improve things by being a bit more\n> invasive.\n\nIntroducing the ON_ERROR option changed the behavior of COPY about error\nhandling to some extent, so it might be good to rewrite a bit more parts\nof the documentation as you suggest.\n\n> This first hunk updates the description of the COPY command to include\n> describing the purpose of the ON_ERROR clause.\n> \n> I too am concerned about the word \"parsed\" here, and \"malformed\" in the\n> more detailed descriptions; this would need to be modified to better\n> reflect the circumstances under which ignore happens.\n\nI think \"errors due to data type incompatibility\" would be nice to describe\nthe errors to be ignored by ON_ERROR, as used in the NOTICE message output.\n \n> diff --git a/doc/src/sgml/ref/copy.sgml b/doc/src/sgml/ref/copy.sgml\n> index 21a5c4a052..5fe4c9f747 100644\n> --- a/doc/src/sgml/ref/copy.sgml\n> +++ b/doc/src/sgml/ref/copy.sgml\n> @@ -90,6 +90,14 @@ COPY { <replaceable\n> class=\"parameter\">table_name</replaceable> [ ( <replaceable\n> in the <structname>pg_stat_progress_copy</structname> view. See\n> <xref linkend=\"copy-progress-reporting\"/> for details.\n> </para>\n> +\n> + <para>\n> + By default, <command>COPY</command> will abort if it encounters errors.\n> + For non-binary format <command>COPY FROM</command> the user can specify\n> + to instead ignore input rows that cannot be parsed by specifying\n> + the <literal>ignore</literal> option to the <literal>ON_ERROR</literal>\n> + clause.\n> + </para>\n> </refsect1>\n> \n\n> \n> The following was, IMO, too much text about something not to worry about,\n> COPY TO and ignore mode. The point is dead tuples on error and running\n> vacuum. It doesn't really even matter what caused the error, though if the\n> error was even before rows started to be imported then obviously there\n> would be no dead tuples.\n> \n> Oh, and the word \"first\" really isn't adding anything here that we cannot\n> reasonably leave to common sense, IMO. We either ignore all errors or stop\n> on the first one. There isn't a stop mode that is capable of bypassing\n> errors and the ignore mode doesn't have a \"first n\" option so one assumes\n> all errors are ignored.\n> \n> @@ -576,15 +583,12 @@ COPY <replaceable\n> class=\"parameter\">count</replaceable>\n> </para>\n> \n> <para>\n> - <command>COPY</command> stops operation at the first error when\n> - <literal>ON_ERROR</literal> is not specified. This\n> - should not lead to problems in the event of a <command>COPY\n> - TO</command>, but the target table will already have received\n> - earlier rows in a <command>COPY FROM</command>. These rows will not\n> - be visible or accessible, but they still occupy disk space. This might\n> - amount to a considerable amount of wasted disk space if the failure\n> - happened well into a large copy operation. You might wish to invoke\n> - <command>VACUUM</command> to recover the wasted space.\n> + A failed <command>COPY FROM</command> command will have performed\n> + physical insertion of all rows prior to the malformed one.\n\nAs you said that it does not matter what caused the error, I don't think\nwe have to use \"malformed\" here. Instead, we could say \"we will have\nperformed physical insertion of rows before the failure.\"\n\n\n> + While these rows will not be visible or accessible, they still occupy\n> + disk space. This might amount to a considerable amount of wasted disk\n> + space if the failure happened well into a large copy operation.\n> + <command>VACUUM</command> should be used to recover the wasted space.\n> </para>\n> \n> <para>\n> \n> David J.\n\nRegards,\nYugo Nagata\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>\n\n\n",
"msg_date": "Fri, 26 Jan 2024 18:09:52 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Fri, 26 Jan 2024 00:00:57 -0700\n\"David G. Johnston\" <david.g.johnston@gmail.com> wrote:\n\n> On Thursday, January 25, 2024, Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> \n> >\n> > Maybe, we can separate the sentese to two, for example:\n> >\n> > COPY stops operation at the first error. (The exception is if the error\n> > is due to data type incompatibility and a value other than stop is\n> > specified\n> > to the ON_ERROR option.)\n> >\n> \n> I’d lean more toward saying:\n> \n> Copy from can be instructed to ignore errors that arise from casting input\n> data to the data types of the target columns by setting the on_error option\n> to ignore. Skipping the entire input row in the process.\n> \n> The last part is because another way to ignore would be to set null values\n> for those columns.\n\nThat makes sense. Is is a bit ambiguous to just say \"skips malformed data\";\nit might be unclear for users if the data in the problematic column is skipped\n(NULL is set) or the entire row is skipped. Also, setting null values for those\ncolumns could be a future feature of ON_ERROR option.\n> \n> That a command stops on an error is the assumed behavior throughout the\n> system, writing “copy stops operation at the first error.” just seems\n> really unnecessary.\n\nI think we need to describe this default behavior explicitly somewhere,\nas you suggested in the other post [1].\n\n[1] https://www.postgresql.org/message-id/CAKFQuwZJZ6uaS2B7qpL2FJzWBsnDdzgtbsW3pH9zuT6vC3fH%2Bg%40mail.gmail.com\n\nRegards,\nYugo Nagata\n\n> I will need to make this tweak and probably a couple others to my own\n> suggestions in 12 hours or so.\n> \n> David J.\n\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>\n\n\n",
"msg_date": "Fri, 26 Jan 2024 18:30:05 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Fri, Jan 26, 2024 at 2:30 AM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n\n> On Fri, 26 Jan 2024 00:00:57 -0700\n> \"David G. Johnston\" <david.g.johnston@gmail.com> wrote:\n>\n> > I will need to make this tweak and probably a couple others to my own\n> > suggestions in 12 hours or so.\n> >\n>\n>\nAnd here is my v2.\n\nNotably I choose to introduce the verbiage \"soft error\" and then define in\nthe ON_ERROR clause the specific soft error that matters here - \"invalid\ninput syntax\".\n\nI also note the log message behavior when ignore mode is chosen. I haven't\nconfirmed that it is accurate but that is readily tweaked if approved of.\n\nDavid J.",
"msg_date": "Fri, 26 Jan 2024 08:04:45 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Fri, 26 Jan 2024 08:04:45 -0700\n\"David G. Johnston\" <david.g.johnston@gmail.com> wrote:\n\n> On Fri, Jan 26, 2024 at 2:30 AM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> \n> > On Fri, 26 Jan 2024 00:00:57 -0700\n> > \"David G. Johnston\" <david.g.johnston@gmail.com> wrote:\n> >\n> > > I will need to make this tweak and probably a couple others to my own\n> > > suggestions in 12 hours or so.\n> > >\n> >\n> >\n> And here is my v2.\n> \n> Notably I choose to introduce the verbiage \"soft error\" and then define in\n> the ON_ERROR clause the specific soft error that matters here - \"invalid\n> input syntax\".\n\nI am not sure we should use \"soft error\" without any explanation\nbecause it seems to me that the meaning of words is unclear for users. \n\nThis is explained in src/backend/utils/fmgr/README;\n\n * Some callers of datatype input functions (and in future perhaps\n other classes of functions) pass an instance of ErrorSaveContext.\n This indicates that the caller wishes to handle \"soft\" errors without\n a transaction-terminating exception being thrown: instead, the callee\n should store information about the error cause in the ErrorSaveContext\n struct and return a dummy result value. \n\nHowever, this is not mentioned in the documentation anywhere. So, it\nwould be hard for users to understand what \"soft error\" is because\nthey would not read README.\n\nAlso, I think \"invalid input syntax\" is a bit ambiguous. For example, \nCOPY FROM raises an error when the number of input column does not match\nto the table schema, but this error is not ignored by ON_ERROR while\nthis seems to fall into the category of \"invalid input syntax\".\n\nI found the description as followings in the documentation in COPY:\n\n The column values themselves are strings (...) acceptable to the input\n function, of each attribute's data type.\n\nSo, keeping consistency with the existing description, we can say:\n\n\"Specifies which how to behave when encountering an error due to\n column values unacceptable to the input function of each attribute's\n data type.\"\n\nCurrently, ON_ERROR doesn't support other soft errors, so it can explain\nit more simply without introducing the new concept, \"soft error\" to users.\n\n> I also note the log message behavior when ignore mode is chosen. I haven't\n> confirmed that it is accurate but that is readily tweaked if approved of.\n> \n\n+ An <literal>INFO</literal> level context message containing the ignored row count is\n+ emitted at the end of the <command>COPY FROM</command> if at least one row was discarded.\n\n\nThe log level is NOTICE not INFO.\n\n <para>\n- <command>COPY</command> stops operation at the first error when\n- <literal>ON_ERROR</literal> is not specified. This\n- should not lead to problems in the event of a <command>COPY\n- TO</command>, but the target table will already have received\n- earlier rows in a <command>COPY FROM</command>. These rows will not\n- be visible or accessible, but they still occupy disk space. This might\n+ The <command>COPY FROM</command> command physically inserts input rows\n+ into the table as it progresses. If the command fails these rows are\n+ left in a deleted state, still occupying disk space. This might\n amount to a considerable amount of wasted disk space if the failure\n- happened well into a large copy operation. You might wish to invoke\n- <command>VACUUM</command> to recover the wasted space.\n+ happened well into a large copy operation. <command>VACUUM</command>\n+ should be used to recover the wasted space.\n </para>\n\nI think \"left in a deleted state\" is also unclear for users because this\nexplains the internal state but not how looks from user's view.How about\nleaving the explanation \"These rows will not be visible or accessible\" in\nthe existing statement?\n\nRegards,\nYugo Nagata\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>\n\n\n",
"msg_date": "Mon, 29 Jan 2024 10:52:54 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On 2024-01-27 00:04, David G. Johnston wrote:\n> On Fri, Jan 26, 2024 at 2:30 AM Yugo NAGATA <nagata@sraoss.co.jp>\n> wrote:\n> \n>> On Fri, 26 Jan 2024 00:00:57 -0700\n>> \"David G. Johnston\" <david.g.johnston@gmail.com> wrote:\n>> \n>>> I will need to make this tweak and probably a couple others to my\n>> own\n>>> suggestions in 12 hours or so.\n>>> \n> \n> And here is my v2.\n> \n> Notably I choose to introduce the verbiage \"soft error\" and then\n> define in the ON_ERROR clause the specific soft error that matters\n> here - \"invalid input syntax\".\n> \n> I also note the log message behavior when ignore mode is chosen. I\n> haven't confirmed that it is accurate but that is readily tweaked if\n> approved of.\n> \n> David J.\n\nThanks for refining the doc.\n\n\n> + Specifies which how to behave when encountering a soft error.\n\nTo be consistent with other parts in the manual[1][2], should be “soft” \nerror?\n\n> + An <replaceable class=\"parameter\">error_action</replaceable> \n> value of\n> + <literal>stop</literal> means fail the command, while\n> + <literal>ignore</literal> means discard the input row and \n> continue with the next one.\n> + The default is <literal>stop</literal>\n\nIs \".\" required at the end of the line?\n\n+ <para>\n+ The only relevant soft error is \"invalid input syntax\", which \nmanifests when attempting\n+ to create a column value from the text input.\n+ </para>\n\nI think it is not restricted to \"invalid input syntax\".\nWe can handle out of range error:\n\n =# create table t1(i int);\n CREATE TABLE\n\n =# copy t1 from stdin with(ON_ERROR ignore);\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\n signal.\n >> 111111111111111111111\n >> \\.\n NOTICE: 1 row was skipped due to data type incompatibility\n COPY 0\n\n\nAlso, I'm a little concerned that users might wonder what soft error is.\n\nCertainly there are already references to \"soft\" errors in the manual, \nbut they seem to be for developer, such as creating new TYPE for \nPostgreSQL.\n\nIt might be better to describe what soft error is like below:\n\n> -- src/backend/utils/fmgr/README\n> An error reported \"softly\" must be safe, in the sense that there is\n> no question about our ability to continue normal processing of the\n> transaction.\n\n[1] https://www.postgresql.org/docs/devel/sql-createtype.html\n[2] https://www.postgresql.org/docs/devel/functions-info.html\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Mon, 29 Jan 2024 11:13:26 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": false,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Sunday, January 28, 2024, Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n\n> On Fri, 26 Jan 2024 08:04:45 -0700\n> \"David G. Johnston\" <david.g.johnston@gmail.com> wrote:\n>\n> > On Fri, Jan 26, 2024 at 2:30 AM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> >\n> > > On Fri, 26 Jan 2024 00:00:57 -0700\n> > > \"David G. Johnston\" <david.g.johnston@gmail.com> wrote:\n> > >\n> > > > I will need to make this tweak and probably a couple others to my own\n> > > > suggestions in 12 hours or so.\n> > > >\n> > >\n> > >\n> > And here is my v2.\n> >\n> > Notably I choose to introduce the verbiage \"soft error\" and then define\n> in\n> > the ON_ERROR clause the specific soft error that matters here - \"invalid\n> > input syntax\".\n>\n> I am not sure we should use \"soft error\" without any explanation\n> because it seems to me that the meaning of words is unclear for users.\n\n\nAgreed. It needs to be added to the glossary.\n\n\n\n>\n> Also, I think \"invalid input syntax\" is a bit ambiguous. For example,\n> COPY FROM raises an error when the number of input column does not match\n> to the table schema, but this error is not ignored by ON_ERROR while\n> this seems to fall into the category of \"invalid input syntax\".\n\n\n\nIt is literally the error text that appears if one were not to ignore it.\nIt isn’t a category of errors. But I’m open to ideas here. But being\nexplicit with what on actually sees in the system seemed preferable to\ninventing new classification terms not otherwise used.\n\n\n>\n> So, keeping consistency with the existing description, we can say:\n>\n> \"Specifies which how to behave when encountering an error due to\n> column values unacceptable to the input function of each attribute's\n> data type.\"\n\n\nYeah, I was considering something along those lines as an option as well.\nBut I’d rather add that wording to the glossary.\n\n\n\n> Currently, ON_ERROR doesn't support other soft errors, so it can explain\n> it more simply without introducing the new concept, \"soft error\" to users.\n>\n>\nGood point. Seems we should define what user-facing errors are ignored\nanywhere in the system and if we aren’t consistently leveraging these in\nall areas/commands make the necessary qualifications in those specific\nplaces.\n\n\n\n> > I also note the log message behavior when ignore mode is chosen. I\n> haven't\n> > confirmed that it is accurate but that is readily tweaked if approved of.\n> >\n>\n> + An <literal>INFO</literal> level context message containing the\n> ignored row count is\n> + emitted at the end of the <command>COPY FROM</command> if at least\n> one row was discarded.\n>\n>\n> The log level is NOTICE not INFO.\n\n\nMakes sense, I hadn’t experimented.\n\n\n> I think \"left in a deleted state\" is also unclear for users because this\n> explains the internal state but not how looks from user's view.How about\n> leaving the explanation \"These rows will not be visible or accessible\" in\n> the existing statement?\n>\n\nJust visible then, I don’t like an “or” there and as tuples at least they\nare accessible to the system, in vacuum especially. But I expected the\nuser to understand “as if you deleted it” as their operational concept more\nreadily than visible. I think this will be read by people who haven’t read\nMVCC to fully understand what visible means but know enough to run vacuum\nto clean up updated and deleted data as a rule.\n\nDavid J.\n\nOn Sunday, January 28, 2024, Yugo NAGATA <nagata@sraoss.co.jp> wrote:On Fri, 26 Jan 2024 08:04:45 -0700\n\"David G. Johnston\" <david.g.johnston@gmail.com> wrote:\n\n> On Fri, Jan 26, 2024 at 2:30 AM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> \n> > On Fri, 26 Jan 2024 00:00:57 -0700\n> > \"David G. Johnston\" <david.g.johnston@gmail.com> wrote:\n> >\n> > > I will need to make this tweak and probably a couple others to my own\n> > > suggestions in 12 hours or so.\n> > >\n> >\n> >\n> And here is my v2.\n> \n> Notably I choose to introduce the verbiage \"soft error\" and then define in\n> the ON_ERROR clause the specific soft error that matters here - \"invalid\n> input syntax\".\n\nI am not sure we should use \"soft error\" without any explanation\nbecause it seems to me that the meaning of words is unclear for users. Agreed. It needs to be added to the glossary. \nAlso, I think \"invalid input syntax\" is a bit ambiguous. For example, \nCOPY FROM raises an error when the number of input column does not match\nto the table schema, but this error is not ignored by ON_ERROR while\nthis seems to fall into the category of \"invalid input syntax\".It is literally the error text that appears if one were not to ignore it. It isn’t a category of errors. But I’m open to ideas here. But being explicit with what on actually sees in the system seemed preferable to inventing new classification terms not otherwise used. \nSo, keeping consistency with the existing description, we can say:\n\n\"Specifies which how to behave when encountering an error due to\n column values unacceptable to the input function of each attribute's\n data type.\"Yeah, I was considering something along those lines as an option as well. But I’d rather add that wording to the glossary.\n\nCurrently, ON_ERROR doesn't support other soft errors, so it can explain\nit more simply without introducing the new concept, \"soft error\" to users.\nGood point. Seems we should define what user-facing errors are ignored anywhere in the system and if we aren’t consistently leveraging these in all areas/commands make the necessary qualifications in those specific places. \n> I also note the log message behavior when ignore mode is chosen. I haven't\n> confirmed that it is accurate but that is readily tweaked if approved of.\n> \n\n+ An <literal>INFO</literal> level context message containing the ignored row count is\n+ emitted at the end of the <command>COPY FROM</command> if at least one row was discarded.\n\n\nThe log level is NOTICE not INFO.Makes sense, I hadn’t experimented. \n\nI think \"left in a deleted state\" is also unclear for users because this\nexplains the internal state but not how looks from user's view.How about\nleaving the explanation \"These rows will not be visible or accessible\" in\nthe existing statement?\nJust visible then, I don’t like an “or” there and as tuples at least they are accessible to the system, in vacuum especially. But I expected the user to understand “as if you deleted it” as their operational concept more readily than visible. I think this will be read by people who haven’t read MVCC to fully understand what visible means but know enough to run vacuum to clean up updated and deleted data as a rule.David J.",
"msg_date": "Sun, 28 Jan 2024 19:14:58 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": false,
"msg_subject": "Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Sun, 28 Jan 2024 19:14:58 -0700\n\"David G. Johnston\" <david.g.johnston@gmail.com> wrote:\n\n> > Also, I think \"invalid input syntax\" is a bit ambiguous. For example,\n> > COPY FROM raises an error when the number of input column does not match\n> > to the table schema, but this error is not ignored by ON_ERROR while\n> > this seems to fall into the category of \"invalid input syntax\".\n> \n> \n> \n> It is literally the error text that appears if one were not to ignore it.\n> It isn’t a category of errors. But I’m open to ideas here. But being\n> explicit with what on actually sees in the system seemed preferable to\n> inventing new classification terms not otherwise used.\n\nThank you for explanation! I understood the words was from the error messages\nthat users actually see. However, as Torikoshi-san said in [1], errors other\nthan valid input syntax (e.g. range error) can be also ignored, therefore it\nwould be better to describe to be ignored errors more specifically.\n\n[1] https://www.postgresql.org/message-id/7f1457497fa3bf9dfe486f162d1c8ec6%40oss.nttdata.com\n\n> \n> >\n> > So, keeping consistency with the existing description, we can say:\n> >\n> > \"Specifies which how to behave when encountering an error due to\n> > column values unacceptable to the input function of each attribute's\n> > data type.\"\n> \n> \n> Yeah, I was considering something along those lines as an option as well.\n> But I’d rather add that wording to the glossary.\n\nAlthough I am still be not convinced if we have to introduce the words\n\"soft error\" to the documentation, I don't care it if there are no other\nopposite opinions. \n\n> \n> > Currently, ON_ERROR doesn't support other soft errors, so it can explain\n> > it more simply without introducing the new concept, \"soft error\" to users.\n> >\n> >\n> Good point. Seems we should define what user-facing errors are ignored\n> anywhere in the system and if we aren’t consistently leveraging these in\n> all areas/commands make the necessary qualifications in those specific\n> places.\n> \n\n> > I think \"left in a deleted state\" is also unclear for users because this\n> > explains the internal state but not how looks from user's view.How about\n> > leaving the explanation \"These rows will not be visible or accessible\" in\n> > the existing statement?\n> >\n> \n> Just visible then, I don’t like an “or” there and as tuples at least they\n> are accessible to the system, in vacuum especially. But I expected the\n> user to understand “as if you deleted it” as their operational concept more\n> readily than visible. I think this will be read by people who haven’t read\n> MVCC to fully understand what visible means but know enough to run vacuum\n> to clean up updated and deleted data as a rule.\n\nOk, I agree we can omit \"or accessible\". How do you like the followings?\nStill redundant?\n\n \"If the command fails, these rows are left in a deleted state;\n these rows will not be visible, but they still occupy disk space. \"\n\nRegards,\nYugo Nagata\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>\n\n\n",
"msg_date": "Mon, 29 Jan 2024 15:47:25 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Mon, 29 Jan 2024 15:47:25 +0900\nYugo NAGATA <nagata@sraoss.co.jp> wrote:\n\n> On Sun, 28 Jan 2024 19:14:58 -0700\n> \"David G. Johnston\" <david.g.johnston@gmail.com> wrote:\n> \n> > > Also, I think \"invalid input syntax\" is a bit ambiguous. For example,\n> > > COPY FROM raises an error when the number of input column does not match\n> > > to the table schema, but this error is not ignored by ON_ERROR while\n> > > this seems to fall into the category of \"invalid input syntax\".\n> > \n> > \n> > \n> > It is literally the error text that appears if one were not to ignore it.\n> > It isn’t a category of errors. But I’m open to ideas here. But being\n> > explicit with what on actually sees in the system seemed preferable to\n> > inventing new classification terms not otherwise used.\n> \n> Thank you for explanation! I understood the words was from the error messages\n> that users actually see. However, as Torikoshi-san said in [1], errors other\n> than valid input syntax (e.g. range error) can be also ignored, therefore it\n> would be better to describe to be ignored errors more specifically.\n> \n> [1] https://www.postgresql.org/message-id/7f1457497fa3bf9dfe486f162d1c8ec6%40oss.nttdata.com\n> \n> > \n> > >\n> > > So, keeping consistency with the existing description, we can say:\n> > >\n> > > \"Specifies which how to behave when encountering an error due to\n> > > column values unacceptable to the input function of each attribute's\n> > > data type.\"\n> > \n> > \n> > Yeah, I was considering something along those lines as an option as well.\n> > But I’d rather add that wording to the glossary.\n> \n> Although I am still be not convinced if we have to introduce the words\n> \"soft error\" to the documentation, I don't care it if there are no other\n> opposite opinions. \n\nAttached is a updated patch v3, which is a version that uses the above\nwording instead of \"soft error\".\n\n> > \n> > > Currently, ON_ERROR doesn't support other soft errors, so it can explain\n> > > it more simply without introducing the new concept, \"soft error\" to users.\n> > >\n> > >\n> > Good point. Seems we should define what user-facing errors are ignored\n> > anywhere in the system and if we aren’t consistently leveraging these in\n> > all areas/commands make the necessary qualifications in those specific\n> > places.\n> > \n> \n> > > I think \"left in a deleted state\" is also unclear for users because this\n> > > explains the internal state but not how looks from user's view.How about\n> > > leaving the explanation \"These rows will not be visible or accessible\" in\n> > > the existing statement?\n> > >\n> > \n> > Just visible then, I don’t like an “or” there and as tuples at least they\n> > are accessible to the system, in vacuum especially. But I expected the\n> > user to understand “as if you deleted it” as their operational concept more\n> > readily than visible. I think this will be read by people who haven’t read\n> > MVCC to fully understand what visible means but know enough to run vacuum\n> > to clean up updated and deleted data as a rule.\n> \n> Ok, I agree we can omit \"or accessible\". How do you like the followings?\n> Still redundant?\n> \n> \"If the command fails, these rows are left in a deleted state;\n> these rows will not be visible, but they still occupy disk space. \"\n\nAlso, the above statement is used in the patch.\n\nRegards,\nYugo Nagata\n\n \n> Regards,\n> Yugo Nagata\n> \n> -- \n> Yugo NAGATA <nagata@sraoss.co.jp>\n> \n> \n\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>",
"msg_date": "Thu, 1 Feb 2024 15:16:03 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On 2024-02-01 15:16, Yugo NAGATA wrote:\n> On Mon, 29 Jan 2024 15:47:25 +0900\n> Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> \n>> On Sun, 28 Jan 2024 19:14:58 -0700\n>> \"David G. Johnston\" <david.g.johnston@gmail.com> wrote:\n>> \n>> > > Also, I think \"invalid input syntax\" is a bit ambiguous. For example,\n>> > > COPY FROM raises an error when the number of input column does not match\n>> > > to the table schema, but this error is not ignored by ON_ERROR while\n>> > > this seems to fall into the category of \"invalid input syntax\".\n>> >\n>> >\n>> >\n>> > It is literally the error text that appears if one were not to ignore it.\n>> > It isn’t a category of errors. But I’m open to ideas here. But being\n>> > explicit with what on actually sees in the system seemed preferable to\n>> > inventing new classification terms not otherwise used.\n>> \n>> Thank you for explanation! I understood the words was from the error \n>> messages\n>> that users actually see. However, as Torikoshi-san said in [1], errors \n>> other\n>> than valid input syntax (e.g. range error) can be also ignored, \n>> therefore it\n>> would be better to describe to be ignored errors more specifically.\n>> \n>> [1] \n>> https://www.postgresql.org/message-id/7f1457497fa3bf9dfe486f162d1c8ec6%40oss.nttdata.com\n>> \n>> >\n>> > >\n>> > > So, keeping consistency with the existing description, we can say:\n>> > >\n>> > > \"Specifies which how to behave when encountering an error due to\n>> > > column values unacceptable to the input function of each attribute's\n>> > > data type.\"\n>> >\n>> >\n>> > Yeah, I was considering something along those lines as an option as well.\n>> > But I’d rather add that wording to the glossary.\n>> \n>> Although I am still be not convinced if we have to introduce the words\n>> \"soft error\" to the documentation, I don't care it if there are no \n>> other\n>> opposite opinions.\n> \n> Attached is a updated patch v3, which is a version that uses the above\n> wording instead of \"soft error\".\n> \n>> >\n>> > > Currently, ON_ERROR doesn't support other soft errors, so it can explain\n>> > > it more simply without introducing the new concept, \"soft error\" to users.\n>> > >\n>> > >\n>> > Good point. Seems we should define what user-facing errors are ignored\n>> > anywhere in the system and if we aren’t consistently leveraging these in\n>> > all areas/commands make the necessary qualifications in those specific\n>> > places.\n>> >\n>> \n>> > > I think \"left in a deleted state\" is also unclear for users because this\n>> > > explains the internal state but not how looks from user's view.How about\n>> > > leaving the explanation \"These rows will not be visible or accessible\" in\n>> > > the existing statement?\n>> > >\n>> >\n>> > Just visible then, I don’t like an “or” there and as tuples at least they\n>> > are accessible to the system, in vacuum especially. But I expected the\n>> > user to understand “as if you deleted it” as their operational concept more\n>> > readily than visible. I think this will be read by people who haven’t read\n>> > MVCC to fully understand what visible means but know enough to run vacuum\n>> > to clean up updated and deleted data as a rule.\n>> \n>> Ok, I agree we can omit \"or accessible\". How do you like the \n>> followings?\n>> Still redundant?\n>> \n>> \"If the command fails, these rows are left in a deleted state;\n>> these rows will not be visible, but they still occupy disk space. \"\n> \n> Also, the above statement is used in the patch.\n\nThanks for updating the patch!\n\nI like your description which doesn't use the word soft error.\n\n\nHere are minor comments:\n\n> + <literal>ignore</literal> means discard the input row and \n> continue with the next one.\n> + The default is <literal>stop</literal>\n\nIs \".\" required at the end of the line?\n\n> An <literal>NOTICE</literal> level context message containing the \n> ignored row count is\n\nShould 'An' be 'A'?\n\nAlso, I wasn't sure the necessity of 'context'.\nIt might be possible to just say \"A NOTICE message containing the \nignored row count..\"\nconsidering below existing descriptions:\n\n doc/src/sgml/pltcl.sgml: a <literal>NOTICE</literal> message each \ntime a supported command is\n doc/src/sgml/pltcl.sgml- executed:\n\n doc/src/sgml/plpgsql.sgml: This example trigger simply raises a \n<literal>NOTICE</literal> message\n doc/src/sgml/plpgsql.sgml- each time a supported command is \nexecuted.\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Fri, 02 Feb 2024 11:29:41 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": false,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Fri, 02 Feb 2024 11:29:41 +0900\ntorikoshia <torikoshia@oss.nttdata.com> wrote:\n\n> On 2024-02-01 15:16, Yugo NAGATA wrote:\n> > On Mon, 29 Jan 2024 15:47:25 +0900\n> > Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> > \n> >> On Sun, 28 Jan 2024 19:14:58 -0700\n> >> \"David G. Johnston\" <david.g.johnston@gmail.com> wrote:\n> >> \n> >> > > Also, I think \"invalid input syntax\" is a bit ambiguous. For example,\n> >> > > COPY FROM raises an error when the number of input column does not match\n> >> > > to the table schema, but this error is not ignored by ON_ERROR while\n> >> > > this seems to fall into the category of \"invalid input syntax\".\n> >> >\n> >> >\n> >> >\n> >> > It is literally the error text that appears if one were not to ignore it.\n> >> > It isn’t a category of errors. But I’m open to ideas here. But being\n> >> > explicit with what on actually sees in the system seemed preferable to\n> >> > inventing new classification terms not otherwise used.\n> >> \n> >> Thank you for explanation! I understood the words was from the error \n> >> messages\n> >> that users actually see. However, as Torikoshi-san said in [1], errors \n> >> other\n> >> than valid input syntax (e.g. range error) can be also ignored, \n> >> therefore it\n> >> would be better to describe to be ignored errors more specifically.\n> >> \n> >> [1] \n> >> https://www.postgresql.org/message-id/7f1457497fa3bf9dfe486f162d1c8ec6%40oss.nttdata.com\n> >> \n> >> >\n> >> > >\n> >> > > So, keeping consistency with the existing description, we can say:\n> >> > >\n> >> > > \"Specifies which how to behave when encountering an error due to\n> >> > > column values unacceptable to the input function of each attribute's\n> >> > > data type.\"\n> >> >\n> >> >\n> >> > Yeah, I was considering something along those lines as an option as well.\n> >> > But I’d rather add that wording to the glossary.\n> >> \n> >> Although I am still be not convinced if we have to introduce the words\n> >> \"soft error\" to the documentation, I don't care it if there are no \n> >> other\n> >> opposite opinions.\n> > \n> > Attached is a updated patch v3, which is a version that uses the above\n> > wording instead of \"soft error\".\n> > \n> >> >\n> >> > > Currently, ON_ERROR doesn't support other soft errors, so it can explain\n> >> > > it more simply without introducing the new concept, \"soft error\" to users.\n> >> > >\n> >> > >\n> >> > Good point. Seems we should define what user-facing errors are ignored\n> >> > anywhere in the system and if we aren’t consistently leveraging these in\n> >> > all areas/commands make the necessary qualifications in those specific\n> >> > places.\n> >> >\n> >> \n> >> > > I think \"left in a deleted state\" is also unclear for users because this\n> >> > > explains the internal state but not how looks from user's view.How about\n> >> > > leaving the explanation \"These rows will not be visible or accessible\" in\n> >> > > the existing statement?\n> >> > >\n> >> >\n> >> > Just visible then, I don’t like an “or” there and as tuples at least they\n> >> > are accessible to the system, in vacuum especially. But I expected the\n> >> > user to understand “as if you deleted it” as their operational concept more\n> >> > readily than visible. I think this will be read by people who haven’t read\n> >> > MVCC to fully understand what visible means but know enough to run vacuum\n> >> > to clean up updated and deleted data as a rule.\n> >> \n> >> Ok, I agree we can omit \"or accessible\". How do you like the \n> >> followings?\n> >> Still redundant?\n> >> \n> >> \"If the command fails, these rows are left in a deleted state;\n> >> these rows will not be visible, but they still occupy disk space. \"\n> > \n> > Also, the above statement is used in the patch.\n> \n> Thanks for updating the patch!\n> \n> I like your description which doesn't use the word soft error.\n\nThank you for your comments!\n\n> \n> Here are minor comments:\n> \n> > + <literal>ignore</literal> means discard the input row and \n> > continue with the next one.\n> > + The default is <literal>stop</literal>\n> \n> Is \".\" required at the end of the line?\n>\n> > An <literal>NOTICE</literal> level context message containing the \n> > ignored row count is\n> \n> Should 'An' be 'A'?\n> \n> Also, I wasn't sure the necessity of 'context'.\n> It might be possible to just say \"A NOTICE message containing the \n> ignored row count..\"\n> considering below existing descriptions:\n> \n> doc/src/sgml/pltcl.sgml: a <literal>NOTICE</literal> message each \n> time a supported command is\n> doc/src/sgml/pltcl.sgml- executed:\n> \n> doc/src/sgml/plpgsql.sgml: This example trigger simply raises a \n> <literal>NOTICE</literal> message\n> doc/src/sgml/plpgsql.sgml- each time a supported command is \n> executed.\n\nI attached a updated patch including fixes you pointed out above.\n\nRegards,\nYugo Nagata\n\n> -- \n> Regards,\n> \n> --\n> Atsushi Torikoshi\n> NTT DATA Group Corporation\n\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>",
"msg_date": "Fri, 2 Feb 2024 15:59:23 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Thu, Feb 1, 2024 at 11:59 PM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n\n>\n> I attached a updated patch including fixes you pointed out above.\n>\n>\nRemoved \"which\"; changed \"occupying\" to \"occupy\"\nRemoved on of the two \"amounts\"\nChanged \"unacceptable to the input function\" to just \"converting\" as that\nis what the average reader is more likely to be thinking.\nThe rest was good.\n\ndiff --git a/doc/src/sgml/ref/copy.sgml b/doc/src/sgml/ref/copy.sgml\nindex 3c2feaa11a..55764fc1f2 100644\n--- a/doc/src/sgml/ref/copy.sgml\n+++ b/doc/src/sgml/ref/copy.sgml\n@@ -385,8 +385,8 @@ COPY { <replaceable\nclass=\"parameter\">table_name</replaceable> [ ( <replaceable\n <term><literal>ON_ERROR</literal></term>\n <listitem>\n <para>\n- Specifies which how to behave when encountering an error due to\ncolumn values\n- unacceptable to the input function of each attribute's data type.\n+ Specifies how to behave when encountering an error converting a\ncolumn's\n+ input value into its data type.\n An <replaceable class=\"parameter\">error_action</replaceable> value of\n <literal>stop</literal> means fail the command, while\n <literal>ignore</literal> means discard the input row and continue\nwith the next one.\n@@ -589,7 +589,7 @@ COPY <replaceable class=\"parameter\">count</replaceable>\n The <command>COPY FROM</command> command physically inserts input rows\n into the table as it progresses. If the command fails, these rows are\n left in a deleted state; these rows will not be visible, but still\n- occupying disk space. This might amount to a considerable amount of\n+ occupy disk space. This might amount to considerable\n wasted disk space if the failure happened well into a large copy\n operation. <command>VACUUM</command> should be used to recover the\n wasted space.\n\nDavid J.\n\nOn Thu, Feb 1, 2024 at 11:59 PM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\nI attached a updated patch including fixes you pointed out above.Removed \"which\"; changed \"occupying\" to \"occupy\"Removed on of the two \"amounts\"Changed \"unacceptable to the input function\" to just \"converting\" as that is what the average reader is more likely to be thinking.The rest was good.diff --git a/doc/src/sgml/ref/copy.sgml b/doc/src/sgml/ref/copy.sgmlindex 3c2feaa11a..55764fc1f2 100644--- a/doc/src/sgml/ref/copy.sgml+++ b/doc/src/sgml/ref/copy.sgml@@ -385,8 +385,8 @@ COPY { <replaceable class=\"parameter\">table_name</replaceable> [ ( <replaceable <term><literal>ON_ERROR</literal></term> <listitem> <para>- Specifies which how to behave when encountering an error due to column values- unacceptable to the input function of each attribute's data type.+ Specifies how to behave when encountering an error converting a column's+ input value into its data type. An <replaceable class=\"parameter\">error_action</replaceable> value of <literal>stop</literal> means fail the command, while <literal>ignore</literal> means discard the input row and continue with the next one.@@ -589,7 +589,7 @@ COPY <replaceable class=\"parameter\">count</replaceable> The <command>COPY FROM</command> command physically inserts input rows into the table as it progresses. If the command fails, these rows are left in a deleted state; these rows will not be visible, but still- occupying disk space. This might amount to a considerable amount of+ occupy disk space. This might amount to considerable wasted disk space if the failure happened well into a large copy operation. <command>VACUUM</command> should be used to recover the wasted space.David J.",
"msg_date": "Fri, 2 Feb 2024 13:06:29 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Fri, Feb 2, 2024 at 10:07 PM David G. Johnston\n<david.g.johnston@gmail.com> wrote:\n> On Thu, Feb 1, 2024 at 11:59 PM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n>>\n>>\n>> I attached a updated patch including fixes you pointed out above.\n>>\n>\n> Removed \"which\"; changed \"occupying\" to \"occupy\"\n> Removed on of the two \"amounts\"\n> Changed \"unacceptable to the input function\" to just \"converting\" as that is what the average reader is more likely to be thinking.\n> The rest was good.\n\nThanks to everybody in the thread.\nPushed.\n\n------\nRegards,\nAlexander Korotkov\n\n\n",
"msg_date": "Sat, 3 Feb 2024 01:51:56 +0200",
"msg_from": "Alexander Korotkov <aekorotkov@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
},
{
"msg_contents": "On Sat, 3 Feb 2024 01:51:56 +0200\nAlexander Korotkov <aekorotkov@gmail.com> wrote:\n\n> On Fri, Feb 2, 2024 at 10:07 PM David G. Johnston\n> <david.g.johnston@gmail.com> wrote:\n> > On Thu, Feb 1, 2024 at 11:59 PM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> >>\n> >>\n> >> I attached a updated patch including fixes you pointed out above.\n> >>\n> >\n> > Removed \"which\"; changed \"occupying\" to \"occupy\"\n> > Removed on of the two \"amounts\"\n> > Changed \"unacceptable to the input function\" to just \"converting\" as that is what the average reader is more likely to be thinking.\n> > The rest was good.\n> \n> Thanks to everybody in the thread.\n> Pushed.\n\nThanks!\n> \n> ------\n> Regards,\n> Alexander Korotkov\n\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>\n\n\n",
"msg_date": "Mon, 5 Feb 2024 11:47:15 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: Small fix on COPY ON_ERROR document"
}
] |
[
{
"msg_contents": "Hello hackers,\n\nAfter determining a possible cause for intermittent failures of the test\nsubscription/031_column_list [1], I was wondering what makes another\nsubscription test (014_binary) fail on the buildfarm:\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=snakefly&dt=2024-01-22%2001%3A19%3A03\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mylodon&dt=2024-01-14%2018%3A19%3A20\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=piculet&dt=2023-12-21%2001%3A11%3A52\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mylodon&dt=2023-11-27%2001%3A42%3A39\n\nAll those failures caused by a timeout when waiting for a message expected\nin _subscriber.log. For example, in the snakefly's case:\n[01:14:46.158](1.937s) ok 7 - check synced data on subscriber with custom type\ntimed out waiting for match: (?^:ERROR: ( [A-Z0-9]+:)? incorrect binary data format) at \n/home/bf/bf-build/piculet/HEAD/pgsql/src/test/subscription/t/014_binary.pl line 269.\n\n_subscriber.log contains:\n2023-12-21 01:14:46.215 UTC [410039] 014_binary.pl LOG: statement: ALTER SUBSCRIPTION tsub REFRESH PUBLICATION;\n2023-12-21 01:17:46.756 UTC [409999] ERROR: could not receive data from WAL stream: server closed the connection \nunexpectedly\n This probably means the server terminated abnormally\n before or while processing the request.\n2023-12-21 01:17:46.760 UTC [405057] LOG: background worker \"logical replication apply worker\" (PID 409999) exited with \nexit code 1\n2023-12-21 01:17:46.779 UTC [532857] LOG: logical replication apply worker for subscription \"tsub\" has started\n...\n\nWhile _subscriber.log from a successful test run contains:\n2024-01-26 03:49:07.065 UTC [9726:5] 014_binary.pl LOG: statement: ALTER SUBSCRIPTION tsub REFRESH PUBLICATION;\n2024-01-26 03:49:07.075 UTC [9726:6] 014_binary.pl LOG: disconnection: session time: 0:00:00.014 user=postgres \ndatabase=postgres host=[local]\n2024-01-26 03:49:07.558 UTC [9729:1] LOG: logical replication apply worker for subscription \"tsub\" has started\n2024-01-26 03:49:07.563 UTC [9731:1] LOG: logical replication table synchronization worker for subscription \"tsub\", \ntable \"test_mismatching_types\" has started\n2024-01-26 03:49:07.585 UTC [9731:2] ERROR: incorrect binary data format\n2024-01-26 03:49:07.585 UTC [9731:3] CONTEXT: COPY test_mismatching_types, line 1, column a\n\nIn this case, \"logical replication apply worker for subscription \"tsub\" has\nstarted\" appears just after \"ALTER SUBSCRIPTION\", not 3 minutes later.\n\nI've managed to reproduce this failure locally by running multiple tests in\nparallel, and my analysis shows that it is caused by a race condition when\naccessing variable table_states_valid inside tablesync.c.\n\ntablesync.c does the following with table_states_valid:\n/*\n * Callback from syscache invalidation.\n */\nvoid\ninvalidate_syncing_table_states(Datum arg, int cacheid, uint32 hashvalue)\n{\n table_states_valid = false;\n}\n...\nstatic bool\nFetchTableStates(bool *started_tx)\n{\n...\n if (!table_states_valid)\n {\n...\n /* Fetch all non-ready tables. */\n rstates = GetSubscriptionRelations(MySubscription->oid, true);\n...\n table_states_valid = true;\n }\n\nSo, when syscache invalidation occurs inside the code block\n\"if (!table_states_valid)\", that invalidation is effectively ignored.\n\nIn a failed case I observe the following events:\n1. logical replication apply worker performs\n LogicalRepApplyLoop() -> process_syncing_tables() ->\n process_syncing_tables_for_apply() -> FetchTableStates() periodically.\n\n2. ALTER SUBSCRIPTION tsub REFRESH PUBLICATION invalidates syscache\n for SUBSCRIPTIONRELMAP, and that leads to calling\n invalidate_syncing_table_states().\n\n3. If the apply worker manages to fetch no non-ready tables in\n FetchTableStates() and ignore \"table_states_valid = false\" from\n invalidate_syncing_table_states(), then it just misses the invalidation\n event, so it keeps working without noticing non-ready tables appeared as\n the result of ALTER SUBSCRIPTION (process_syncing_tables_for_apply() skips\n a loop \"foreach(lc, table_states_not_ready) ...\" until some other event\n occurs).\n\npg_usleep(100000) added just below GetSubscriptionRelations(...) proves my\nanalysis -- without it, I need tens of iterations (with 50 tests running in\nparallel) to catch the failure, but with it, I get the failure on the first\niteration.\n\n(Reproduced on REL_16_STABLE..master, where the test 014_binary tries to\n\"Refresh the publication to trigger the tablesync\", but I think the race\ncondition exists in the previous versions as well.)\n\n[1] https://www.postgresql.org/message-id/16d6d9cc-f97d-0b34-be65-425183ed3721@gmail.com\n\nBest regards,\nAlexander\n\n\n",
"msg_date": "Fri, 26 Jan 2024 09:00:00 +0300",
"msg_from": "Alexander Lakhin <exclusion@gmail.com>",
"msg_from_op": true,
"msg_subject": "Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Fri, 26 Jan 2024 at 11:30, Alexander Lakhin <exclusion@gmail.com> wrote:\n>\n> Hello hackers,\n>\n> After determining a possible cause for intermittent failures of the test\n> subscription/031_column_list [1], I was wondering what makes another\n> subscription test (014_binary) fail on the buildfarm:\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=snakefly&dt=2024-01-22%2001%3A19%3A03\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mylodon&dt=2024-01-14%2018%3A19%3A20\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=piculet&dt=2023-12-21%2001%3A11%3A52\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mylodon&dt=2023-11-27%2001%3A42%3A39\n>\n> All those failures caused by a timeout when waiting for a message expected\n> in _subscriber.log. For example, in the snakefly's case:\n> [01:14:46.158](1.937s) ok 7 - check synced data on subscriber with custom type\n> timed out waiting for match: (?^:ERROR: ( [A-Z0-9]+:)? incorrect binary data format) at\n> /home/bf/bf-build/piculet/HEAD/pgsql/src/test/subscription/t/014_binary.pl line 269.\n>\n> _subscriber.log contains:\n> 2023-12-21 01:14:46.215 UTC [410039] 014_binary.pl LOG: statement: ALTER SUBSCRIPTION tsub REFRESH PUBLICATION;\n> 2023-12-21 01:17:46.756 UTC [409999] ERROR: could not receive data from WAL stream: server closed the connection\n> unexpectedly\n> This probably means the server terminated abnormally\n> before or while processing the request.\n> 2023-12-21 01:17:46.760 UTC [405057] LOG: background worker \"logical replication apply worker\" (PID 409999) exited with\n> exit code 1\n> 2023-12-21 01:17:46.779 UTC [532857] LOG: logical replication apply worker for subscription \"tsub\" has started\n> ...\n>\n> While _subscriber.log from a successful test run contains:\n> 2024-01-26 03:49:07.065 UTC [9726:5] 014_binary.pl LOG: statement: ALTER SUBSCRIPTION tsub REFRESH PUBLICATION;\n> 2024-01-26 03:49:07.075 UTC [9726:6] 014_binary.pl LOG: disconnection: session time: 0:00:00.014 user=postgres\n> database=postgres host=[local]\n> 2024-01-26 03:49:07.558 UTC [9729:1] LOG: logical replication apply worker for subscription \"tsub\" has started\n> 2024-01-26 03:49:07.563 UTC [9731:1] LOG: logical replication table synchronization worker for subscription \"tsub\",\n> table \"test_mismatching_types\" has started\n> 2024-01-26 03:49:07.585 UTC [9731:2] ERROR: incorrect binary data format\n> 2024-01-26 03:49:07.585 UTC [9731:3] CONTEXT: COPY test_mismatching_types, line 1, column a\n>\n> In this case, \"logical replication apply worker for subscription \"tsub\" has\n> started\" appears just after \"ALTER SUBSCRIPTION\", not 3 minutes later.\n>\n> I've managed to reproduce this failure locally by running multiple tests in\n> parallel, and my analysis shows that it is caused by a race condition when\n> accessing variable table_states_valid inside tablesync.c.\n>\n> tablesync.c does the following with table_states_valid:\n> /*\n> * Callback from syscache invalidation.\n> */\n> void\n> invalidate_syncing_table_states(Datum arg, int cacheid, uint32 hashvalue)\n> {\n> table_states_valid = false;\n> }\n> ...\n> static bool\n> FetchTableStates(bool *started_tx)\n> {\n> ...\n> if (!table_states_valid)\n> {\n> ...\n> /* Fetch all non-ready tables. */\n> rstates = GetSubscriptionRelations(MySubscription->oid, true);\n> ...\n> table_states_valid = true;\n> }\n>\n> So, when syscache invalidation occurs inside the code block\n> \"if (!table_states_valid)\", that invalidation is effectively ignored.\n>\n> In a failed case I observe the following events:\n> 1. logical replication apply worker performs\n> LogicalRepApplyLoop() -> process_syncing_tables() ->\n> process_syncing_tables_for_apply() -> FetchTableStates() periodically.\n>\n> 2. ALTER SUBSCRIPTION tsub REFRESH PUBLICATION invalidates syscache\n> for SUBSCRIPTIONRELMAP, and that leads to calling\n> invalidate_syncing_table_states().\n>\n> 3. If the apply worker manages to fetch no non-ready tables in\n> FetchTableStates() and ignore \"table_states_valid = false\" from\n> invalidate_syncing_table_states(), then it just misses the invalidation\n> event, so it keeps working without noticing non-ready tables appeared as\n> the result of ALTER SUBSCRIPTION (process_syncing_tables_for_apply() skips\n> a loop \"foreach(lc, table_states_not_ready) ...\" until some other event\n> occurs).\n>\n> pg_usleep(100000) added just below GetSubscriptionRelations(...) proves my\n> analysis -- without it, I need tens of iterations (with 50 tests running in\n> parallel) to catch the failure, but with it, I get the failure on the first\n> iteration.\n\nThanks for the analysis, I was able to reproduce the issue with the\nsteps you had shared. I agree with your analysis. I added some logs to\nverify that the invalidation was getting missed.\n\nI felt that this invalidation is getting ignored because we have used\na boolean variable here, how about changing it slightly so that\ntable_states_invalid gets incremented for every invalidation and then\ndecrementing table_states_invalid after getting the non-ready tables\nlike in the attached patch. I was able to verify that the test passes\nwith the attached patch.\n\nRegards,\nVignesh",
"msg_date": "Mon, 29 Jan 2024 18:52:18 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Monday, January 29, 2024 9:22 PM vignesh C <vignesh21@gmail.com> wrote:\r\n> \r\n> On Fri, 26 Jan 2024 at 11:30, Alexander Lakhin <exclusion@gmail.com> wrote:\r\n> >\r\n> > Hello hackers,\r\n> >\r\n> > After determining a possible cause for intermittent failures of the\r\n> > test subscription/031_column_list [1], I was wondering what makes\r\n> > another subscription test (014_binary) fail on the buildfarm:\r\n> > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=snakefly&dt=20\r\n> > 24-01-22%2001%3A19%3A03\r\n> >\r\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mylodon&dt=202\r\n> > 4-01-14%2018%3A19%3A20\r\n> > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=piculet&dt=202\r\n> > 3-12-21%2001%3A11%3A52\r\n> >\r\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mylodon&dt=202\r\n> > 3-11-27%2001%3A42%3A39\r\n> >\r\n> > All those failures caused by a timeout when waiting for a message\r\n> > expected in _subscriber.log. For example, in the snakefly's case:\r\n> > [01:14:46.158](1.937s) ok 7 - check synced data on subscriber with\r\n> > custom type timed out waiting for match: (?^:ERROR: ( [A-Z0-9]+:)?\r\n> > incorrect binary data format) at\r\n> /home/bf/bf-build/piculet/HEAD/pgsql/src/test/subscription/t/014_binary.pl\r\n> line 269.\r\n> >\r\n> > _subscriber.log contains:\r\n> > 2023-12-21 01:14:46.215 UTC [410039] 014_binary.pl LOG: statement:\r\n> > ALTER SUBSCRIPTION tsub REFRESH PUBLICATION;\r\n> > 2023-12-21 01:17:46.756 UTC [409999] ERROR: could not receive data\r\n> > from WAL stream: server closed the connection unexpectedly\r\n> > This probably means the server terminated abnormally\r\n> > before or while processing the request.\r\n> > 2023-12-21 01:17:46.760 UTC [405057] LOG: background worker \"logical\r\n> > replication apply worker\" (PID 409999) exited with exit code 1\r\n> > 2023-12-21 01:17:46.779 UTC [532857] LOG: logical replication apply\r\n> > worker for subscription \"tsub\" has started ...\r\n> >\r\n> > While _subscriber.log from a successful test run contains:\r\n> > 2024-01-26 03:49:07.065 UTC [9726:5] 014_binary.pl LOG: statement:\r\n> > ALTER SUBSCRIPTION tsub REFRESH PUBLICATION;\r\n> > 2024-01-26 03:49:07.075 UTC [9726:6] 014_binary.pl LOG: disconnection:\r\n> > session time: 0:00:00.014 user=postgres database=postgres host=[local]\r\n> > 2024-01-26 03:49:07.558 UTC [9729:1] LOG: logical replication apply\r\n> > worker for subscription \"tsub\" has started\r\n> > 2024-01-26 03:49:07.563 UTC [9731:1] LOG: logical replication table\r\n> > synchronization worker for subscription \"tsub\", table\r\n> > \"test_mismatching_types\" has started\r\n> > 2024-01-26 03:49:07.585 UTC [9731:2] ERROR: incorrect binary data\r\n> > format\r\n> > 2024-01-26 03:49:07.585 UTC [9731:3] CONTEXT: COPY\r\n> > test_mismatching_types, line 1, column a\r\n> >\r\n> > In this case, \"logical replication apply worker for subscription\r\n> > \"tsub\" has started\" appears just after \"ALTER SUBSCRIPTION\", not 3 minutes\r\n> later.\r\n> >\r\n> > I've managed to reproduce this failure locally by running multiple\r\n> > tests in parallel, and my analysis shows that it is caused by a race\r\n> > condition when accessing variable table_states_valid inside tablesync.c.\r\n> >\r\n> > tablesync.c does the following with table_states_valid:\r\n> > /*\r\n> > * Callback from syscache invalidation.\r\n> > */\r\n> > void\r\n> > invalidate_syncing_table_states(Datum arg, int cacheid, uint32\r\n> > hashvalue) {\r\n> > table_states_valid = false;\r\n> > }\r\n> > ...\r\n> > static bool\r\n> > FetchTableStates(bool *started_tx)\r\n> > {\r\n> > ...\r\n> > if (!table_states_valid)\r\n> > {\r\n> > ...\r\n> > /* Fetch all non-ready tables. */\r\n> > rstates = GetSubscriptionRelations(MySubscription->oid,\r\n> > true); ...\r\n> > table_states_valid = true;\r\n> > }\r\n> >\r\n> > So, when syscache invalidation occurs inside the code block \"if\r\n> > (!table_states_valid)\", that invalidation is effectively ignored.\r\n> >\r\n> > In a failed case I observe the following events:\r\n> > 1. logical replication apply worker performs\r\n> > LogicalRepApplyLoop() -> process_syncing_tables() ->\r\n> > process_syncing_tables_for_apply() -> FetchTableStates() periodically.\r\n> >\r\n> > 2. ALTER SUBSCRIPTION tsub REFRESH PUBLICATION invalidates syscache\r\n> > for SUBSCRIPTIONRELMAP, and that leads to calling\r\n> > invalidate_syncing_table_states().\r\n> >\r\n> > 3. If the apply worker manages to fetch no non-ready tables in\r\n> > FetchTableStates() and ignore \"table_states_valid = false\" from\r\n> > invalidate_syncing_table_states(), then it just misses the invalidation\r\n> > event, so it keeps working without noticing non-ready tables appeared as\r\n> > the result of ALTER SUBSCRIPTION (process_syncing_tables_for_apply()\r\n> skips\r\n> > a loop \"foreach(lc, table_states_not_ready) ...\" until some other event\r\n> > occurs).\r\n> >\r\n> > pg_usleep(100000) added just below GetSubscriptionRelations(...)\r\n> > proves my analysis -- without it, I need tens of iterations (with 50\r\n> > tests running in\r\n> > parallel) to catch the failure, but with it, I get the failure on the\r\n> > first iteration.\r\n> \r\n> Thanks for the analysis, I was able to reproduce the issue with the steps you had\r\n> shared. I agree with your analysis. I added some logs to verify that the\r\n> invalidation was getting missed.\r\n> \r\n> I felt that this invalidation is getting ignored because we have used a boolean\r\n> variable here, how about changing it slightly so that table_states_invalid gets\r\n> incremented for every invalidation and then decrementing table_states_invalid\r\n> after getting the non-ready tables like in the attached patch. I was able to\r\n> verify that the test passes with the attached patch.\r\n\r\nThanks for the patch.\r\n\r\nI am not sure if counting the invalidation number is needed, as even if there\r\nare hundreds of invalidations outside of FetchTableStates, one FetchTableStates\r\ncall should reset the count to 0 as it is checking the latest catalog. I think\r\na better approach is to make the table_states_valid tristate\r\n{TABLE_STATE_NEEDS_REBUILD, TABLE_STATE_REBUILD_START, TABLE_STATE_VALID}. The\r\ncache invalidate callback will set state to TABLE_STATE_NEEDS_REBUILD.\r\nFetchTableStates will set the state to TABLE_STATE_VALID only if the state was\r\nTABLE_STATE_REBUILD_START. See the existing EventTriggerCacheStateType for\r\nreference.\r\n\r\nBest Regards,\r\nHou zj\r\n\r\n",
"msg_date": "Tue, 30 Jan 2024 01:54:42 +0000",
"msg_from": "\"Zhijie Hou (Fujitsu)\" <houzj.fnst@fujitsu.com>",
"msg_from_op": false,
"msg_subject": "RE: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Tue, 30 Jan 2024 at 07:24, Zhijie Hou (Fujitsu)\n<houzj.fnst@fujitsu.com> wrote:\n>\n> On Monday, January 29, 2024 9:22 PM vignesh C <vignesh21@gmail.com> wrote:\n> >\n> > On Fri, 26 Jan 2024 at 11:30, Alexander Lakhin <exclusion@gmail.com> wrote:\n> > >\n> > > Hello hackers,\n> > >\n> > > After determining a possible cause for intermittent failures of the\n> > > test subscription/031_column_list [1], I was wondering what makes\n> > > another subscription test (014_binary) fail on the buildfarm:\n> > > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=snakefly&dt=20\n> > > 24-01-22%2001%3A19%3A03\n> > >\n> > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mylodon&dt=202\n> > > 4-01-14%2018%3A19%3A20\n> > > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=piculet&dt=202\n> > > 3-12-21%2001%3A11%3A52\n> > >\n> > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mylodon&dt=202\n> > > 3-11-27%2001%3A42%3A39\n> > >\n> > > All those failures caused by a timeout when waiting for a message\n> > > expected in _subscriber.log. For example, in the snakefly's case:\n> > > [01:14:46.158](1.937s) ok 7 - check synced data on subscriber with\n> > > custom type timed out waiting for match: (?^:ERROR: ( [A-Z0-9]+:)?\n> > > incorrect binary data format) at\n> > /home/bf/bf-build/piculet/HEAD/pgsql/src/test/subscription/t/014_binary.pl\n> > line 269.\n> > >\n> > > _subscriber.log contains:\n> > > 2023-12-21 01:14:46.215 UTC [410039] 014_binary.pl LOG: statement:\n> > > ALTER SUBSCRIPTION tsub REFRESH PUBLICATION;\n> > > 2023-12-21 01:17:46.756 UTC [409999] ERROR: could not receive data\n> > > from WAL stream: server closed the connection unexpectedly\n> > > This probably means the server terminated abnormally\n> > > before or while processing the request.\n> > > 2023-12-21 01:17:46.760 UTC [405057] LOG: background worker \"logical\n> > > replication apply worker\" (PID 409999) exited with exit code 1\n> > > 2023-12-21 01:17:46.779 UTC [532857] LOG: logical replication apply\n> > > worker for subscription \"tsub\" has started ...\n> > >\n> > > While _subscriber.log from a successful test run contains:\n> > > 2024-01-26 03:49:07.065 UTC [9726:5] 014_binary.pl LOG: statement:\n> > > ALTER SUBSCRIPTION tsub REFRESH PUBLICATION;\n> > > 2024-01-26 03:49:07.075 UTC [9726:6] 014_binary.pl LOG: disconnection:\n> > > session time: 0:00:00.014 user=postgres database=postgres host=[local]\n> > > 2024-01-26 03:49:07.558 UTC [9729:1] LOG: logical replication apply\n> > > worker for subscription \"tsub\" has started\n> > > 2024-01-26 03:49:07.563 UTC [9731:1] LOG: logical replication table\n> > > synchronization worker for subscription \"tsub\", table\n> > > \"test_mismatching_types\" has started\n> > > 2024-01-26 03:49:07.585 UTC [9731:2] ERROR: incorrect binary data\n> > > format\n> > > 2024-01-26 03:49:07.585 UTC [9731:3] CONTEXT: COPY\n> > > test_mismatching_types, line 1, column a\n> > >\n> > > In this case, \"logical replication apply worker for subscription\n> > > \"tsub\" has started\" appears just after \"ALTER SUBSCRIPTION\", not 3 minutes\n> > later.\n> > >\n> > > I've managed to reproduce this failure locally by running multiple\n> > > tests in parallel, and my analysis shows that it is caused by a race\n> > > condition when accessing variable table_states_valid inside tablesync.c.\n> > >\n> > > tablesync.c does the following with table_states_valid:\n> > > /*\n> > > * Callback from syscache invalidation.\n> > > */\n> > > void\n> > > invalidate_syncing_table_states(Datum arg, int cacheid, uint32\n> > > hashvalue) {\n> > > table_states_valid = false;\n> > > }\n> > > ...\n> > > static bool\n> > > FetchTableStates(bool *started_tx)\n> > > {\n> > > ...\n> > > if (!table_states_valid)\n> > > {\n> > > ...\n> > > /* Fetch all non-ready tables. */\n> > > rstates = GetSubscriptionRelations(MySubscription->oid,\n> > > true); ...\n> > > table_states_valid = true;\n> > > }\n> > >\n> > > So, when syscache invalidation occurs inside the code block \"if\n> > > (!table_states_valid)\", that invalidation is effectively ignored.\n> > >\n> > > In a failed case I observe the following events:\n> > > 1. logical replication apply worker performs\n> > > LogicalRepApplyLoop() -> process_syncing_tables() ->\n> > > process_syncing_tables_for_apply() -> FetchTableStates() periodically.\n> > >\n> > > 2. ALTER SUBSCRIPTION tsub REFRESH PUBLICATION invalidates syscache\n> > > for SUBSCRIPTIONRELMAP, and that leads to calling\n> > > invalidate_syncing_table_states().\n> > >\n> > > 3. If the apply worker manages to fetch no non-ready tables in\n> > > FetchTableStates() and ignore \"table_states_valid = false\" from\n> > > invalidate_syncing_table_states(), then it just misses the invalidation\n> > > event, so it keeps working without noticing non-ready tables appeared as\n> > > the result of ALTER SUBSCRIPTION (process_syncing_tables_for_apply()\n> > skips\n> > > a loop \"foreach(lc, table_states_not_ready) ...\" until some other event\n> > > occurs).\n> > >\n> > > pg_usleep(100000) added just below GetSubscriptionRelations(...)\n> > > proves my analysis -- without it, I need tens of iterations (with 50\n> > > tests running in\n> > > parallel) to catch the failure, but with it, I get the failure on the\n> > > first iteration.\n> >\n> > Thanks for the analysis, I was able to reproduce the issue with the steps you had\n> > shared. I agree with your analysis. I added some logs to verify that the\n> > invalidation was getting missed.\n> >\n> > I felt that this invalidation is getting ignored because we have used a boolean\n> > variable here, how about changing it slightly so that table_states_invalid gets\n> > incremented for every invalidation and then decrementing table_states_invalid\n> > after getting the non-ready tables like in the attached patch. I was able to\n> > verify that the test passes with the attached patch.\n>\n> Thanks for the patch.\n>\n> I am not sure if counting the invalidation number is needed, as even if there\n> are hundreds of invalidations outside of FetchTableStates, one FetchTableStates\n> call should reset the count to 0 as it is checking the latest catalog.\n\nAnother approach I was thinking of is to reset table_states_valid\nimmediately in the beginning of FetchTableStates, so any new\ninvalidations will take care of setting table_states_valid again it\nagain which will be handled in the next iteration of fetching\nnon-ready tables like in the attached patch.\n\nRegards,\nVigneshj",
"msg_date": "Tue, 30 Jan 2024 08:50:32 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Tuesday, January 30, 2024 11:21 AM vignesh C <vignesh21@gmail.com> wrote:\r\n> \r\n> On Tue, 30 Jan 2024 at 07:24, Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>\r\n> wrote:\r\n> >\r\n> > On Monday, January 29, 2024 9:22 PM vignesh C <vignesh21@gmail.com>\r\n> wrote:\r\n> > >\r\n> > > On Fri, 26 Jan 2024 at 11:30, Alexander Lakhin <exclusion@gmail.com>\r\n> wrote:\r\n> > > >\r\n> > > > Hello hackers,\r\n> > > >\r\n> > > > After determining a possible cause for intermittent failures of\r\n> > > > the test subscription/031_column_list [1], I was wondering what\r\n> > > > makes another subscription test (014_binary) fail on the buildfarm:\r\n> > > > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=snakefly&d\r\n> > > > t=20\r\n> > > > 24-01-22%2001%3A19%3A03\r\n> > > >\r\n> > >\r\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mylodon&dt=2\r\n> > > 02\r\n> > > > 4-01-14%2018%3A19%3A20\r\n> > > > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=piculet&dt\r\n> > > > =202\r\n> > > > 3-12-21%2001%3A11%3A52\r\n> > > >\r\n> > >\r\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mylodon&dt=2\r\n> > > 02\r\n> > > > 3-11-27%2001%3A42%3A39\r\n> > > >\r\n> > > > All those failures caused by a timeout when waiting for a message\r\n> > > > expected in _subscriber.log. For example, in the snakefly's case:\r\n> > > > [01:14:46.158](1.937s) ok 7 - check synced data on subscriber with\r\n> > > > custom type timed out waiting for match: (?^:ERROR: ( [A-Z0-9]+:)?\r\n> > > > incorrect binary data format) at\r\n> > > /home/bf/bf-build/piculet/HEAD/pgsql/src/test/subscription/t/014_bin\r\n> > > ary.pl\r\n> > > line 269.\r\n> > > >\r\n> > > > _subscriber.log contains:\r\n> > > > 2023-12-21 01:14:46.215 UTC [410039] 014_binary.pl LOG: statement:\r\n> > > > ALTER SUBSCRIPTION tsub REFRESH PUBLICATION;\r\n> > > > 2023-12-21 01:17:46.756 UTC [409999] ERROR: could not receive\r\n> > > > data from WAL stream: server closed the connection unexpectedly\r\n> > > > This probably means the server terminated abnormally\r\n> > > > before or while processing the request.\r\n> > > > 2023-12-21 01:17:46.760 UTC [405057] LOG: background worker\r\n> > > > \"logical replication apply worker\" (PID 409999) exited with exit\r\n> > > > code 1\r\n> > > > 2023-12-21 01:17:46.779 UTC [532857] LOG: logical replication\r\n> > > > apply worker for subscription \"tsub\" has started ...\r\n> > > >\r\n> > > > While _subscriber.log from a successful test run contains:\r\n> > > > 2024-01-26 03:49:07.065 UTC [9726:5] 014_binary.pl LOG: statement:\r\n> > > > ALTER SUBSCRIPTION tsub REFRESH PUBLICATION;\r\n> > > > 2024-01-26 03:49:07.075 UTC [9726:6] 014_binary.pl LOG: disconnection:\r\n> > > > session time: 0:00:00.014 user=postgres database=postgres\r\n> > > > host=[local]\r\n> > > > 2024-01-26 03:49:07.558 UTC [9729:1] LOG: logical replication\r\n> > > > apply worker for subscription \"tsub\" has started\r\n> > > > 2024-01-26 03:49:07.563 UTC [9731:1] LOG: logical replication\r\n> > > > table synchronization worker for subscription \"tsub\", table\r\n> > > > \"test_mismatching_types\" has started\r\n> > > > 2024-01-26 03:49:07.585 UTC [9731:2] ERROR: incorrect binary data\r\n> > > > format\r\n> > > > 2024-01-26 03:49:07.585 UTC [9731:3] CONTEXT: COPY\r\n> > > > test_mismatching_types, line 1, column a\r\n> > > >\r\n> > > > In this case, \"logical replication apply worker for subscription\r\n> > > > \"tsub\" has started\" appears just after \"ALTER SUBSCRIPTION\", not 3\r\n> > > > minutes\r\n> > > later.\r\n> > > >\r\n> > > > I've managed to reproduce this failure locally by running multiple\r\n> > > > tests in parallel, and my analysis shows that it is caused by a\r\n> > > > race condition when accessing variable table_states_valid inside\r\n> tablesync.c.\r\n> > > >\r\n> > > > tablesync.c does the following with table_states_valid:\r\n> > > > /*\r\n> > > > * Callback from syscache invalidation.\r\n> > > > */\r\n> > > > void\r\n> > > > invalidate_syncing_table_states(Datum arg, int cacheid, uint32\r\n> > > > hashvalue) {\r\n> > > > table_states_valid = false;\r\n> > > > }\r\n> > > > ...\r\n> > > > static bool\r\n> > > > FetchTableStates(bool *started_tx) { ...\r\n> > > > if (!table_states_valid)\r\n> > > > {\r\n> > > > ...\r\n> > > > /* Fetch all non-ready tables. */\r\n> > > > rstates = GetSubscriptionRelations(MySubscription->oid,\r\n> > > > true); ...\r\n> > > > table_states_valid = true;\r\n> > > > }\r\n> > > >\r\n> > > > So, when syscache invalidation occurs inside the code block \"if\r\n> > > > (!table_states_valid)\", that invalidation is effectively ignored.\r\n> > > >\r\n> > > > In a failed case I observe the following events:\r\n> > > > 1. logical replication apply worker performs\r\n> > > > LogicalRepApplyLoop() -> process_syncing_tables() ->\r\n> > > > process_syncing_tables_for_apply() -> FetchTableStates() periodically.\r\n> > > >\r\n> > > > 2. ALTER SUBSCRIPTION tsub REFRESH PUBLICATION invalidates\r\n> syscache\r\n> > > > for SUBSCRIPTIONRELMAP, and that leads to calling\r\n> > > > invalidate_syncing_table_states().\r\n> > > >\r\n> > > > 3. If the apply worker manages to fetch no non-ready tables in\r\n> > > > FetchTableStates() and ignore \"table_states_valid = false\" from\r\n> > > > invalidate_syncing_table_states(), then it just misses the invalidation\r\n> > > > event, so it keeps working without noticing non-ready tables\r\n> appeared as\r\n> > > > the result of ALTER SUBSCRIPTION\r\n> > > > (process_syncing_tables_for_apply()\r\n> > > skips\r\n> > > > a loop \"foreach(lc, table_states_not_ready) ...\" until some other event\r\n> > > > occurs).\r\n> > > >\r\n> > > > pg_usleep(100000) added just below GetSubscriptionRelations(...)\r\n> > > > proves my analysis -- without it, I need tens of iterations (with\r\n> > > > 50 tests running in\r\n> > > > parallel) to catch the failure, but with it, I get the failure on\r\n> > > > the first iteration.\r\n> > >\r\n> > > Thanks for the analysis, I was able to reproduce the issue with the\r\n> > > steps you had shared. I agree with your analysis. I added some logs\r\n> > > to verify that the invalidation was getting missed.\r\n> > >\r\n> > > I felt that this invalidation is getting ignored because we have\r\n> > > used a boolean variable here, how about changing it slightly so that\r\n> > > table_states_invalid gets incremented for every invalidation and\r\n> > > then decrementing table_states_invalid after getting the non-ready\r\n> > > tables like in the attached patch. I was able to verify that the test passes\r\n> with the attached patch.\r\n> >\r\n> > Thanks for the patch.\r\n> >\r\n> > I am not sure if counting the invalidation number is needed, as even\r\n> > if there are hundreds of invalidations outside of FetchTableStates,\r\n> > one FetchTableStates call should reset the count to 0 as it is checking the\r\n> latest catalog.\r\n> \r\n> Another approach I was thinking of is to reset table_states_valid immediately in\r\n> the beginning of FetchTableStates, so any new invalidations will take care of\r\n> setting table_states_valid again it again which will be handled in the next\r\n> iteration of fetching non-ready tables like in the attached patch.\r\n\r\nI think this is not the standard appraoch for cache building. Because if any\r\nERROR happens during the cache building, then we will come into the situation\r\nthat table_states_valid=true while the cache data is invalid. Even if we\r\ncurrently don't access these cache after erroring out, but I think we'd better\r\nto avoid this risk.\r\n\r\nBest Regards,\r\nHou zj\r\n",
"msg_date": "Tue, 30 Jan 2024 11:52:17 +0000",
"msg_from": "\"Zhijie Hou (Fujitsu)\" <houzj.fnst@fujitsu.com>",
"msg_from_op": false,
"msg_subject": "RE: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Tue, 30 Jan 2024 at 17:22, Zhijie Hou (Fujitsu)\n<houzj.fnst@fujitsu.com> wrote:\n>\n> On Tuesday, January 30, 2024 11:21 AM vignesh C <vignesh21@gmail.com> wrote:\n> >\n> > On Tue, 30 Jan 2024 at 07:24, Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>\n> > wrote:\n> > >\n> > > On Monday, January 29, 2024 9:22 PM vignesh C <vignesh21@gmail.com>\n> > wrote:\n> > > >\n> > > > On Fri, 26 Jan 2024 at 11:30, Alexander Lakhin <exclusion@gmail.com>\n> > wrote:\n> > > > >\n> > > > > Hello hackers,\n> > > > >\n> > > > > After determining a possible cause for intermittent failures of\n> > > > > the test subscription/031_column_list [1], I was wondering what\n> > > > > makes another subscription test (014_binary) fail on the buildfarm:\n> > > > > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=snakefly&d\n> > > > > t=20\n> > > > > 24-01-22%2001%3A19%3A03\n> > > > >\n> > > >\n> > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mylodon&dt=2\n> > > > 02\n> > > > > 4-01-14%2018%3A19%3A20\n> > > > > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=piculet&dt\n> > > > > =202\n> > > > > 3-12-21%2001%3A11%3A52\n> > > > >\n> > > >\n> > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mylodon&dt=2\n> > > > 02\n> > > > > 3-11-27%2001%3A42%3A39\n> > > > >\n> > > > > All those failures caused by a timeout when waiting for a message\n> > > > > expected in _subscriber.log. For example, in the snakefly's case:\n> > > > > [01:14:46.158](1.937s) ok 7 - check synced data on subscriber with\n> > > > > custom type timed out waiting for match: (?^:ERROR: ( [A-Z0-9]+:)?\n> > > > > incorrect binary data format) at\n> > > > /home/bf/bf-build/piculet/HEAD/pgsql/src/test/subscription/t/014_bin\n> > > > ary.pl\n> > > > line 269.\n> > > > >\n> > > > > _subscriber.log contains:\n> > > > > 2023-12-21 01:14:46.215 UTC [410039] 014_binary.pl LOG: statement:\n> > > > > ALTER SUBSCRIPTION tsub REFRESH PUBLICATION;\n> > > > > 2023-12-21 01:17:46.756 UTC [409999] ERROR: could not receive\n> > > > > data from WAL stream: server closed the connection unexpectedly\n> > > > > This probably means the server terminated abnormally\n> > > > > before or while processing the request.\n> > > > > 2023-12-21 01:17:46.760 UTC [405057] LOG: background worker\n> > > > > \"logical replication apply worker\" (PID 409999) exited with exit\n> > > > > code 1\n> > > > > 2023-12-21 01:17:46.779 UTC [532857] LOG: logical replication\n> > > > > apply worker for subscription \"tsub\" has started ...\n> > > > >\n> > > > > While _subscriber.log from a successful test run contains:\n> > > > > 2024-01-26 03:49:07.065 UTC [9726:5] 014_binary.pl LOG: statement:\n> > > > > ALTER SUBSCRIPTION tsub REFRESH PUBLICATION;\n> > > > > 2024-01-26 03:49:07.075 UTC [9726:6] 014_binary.pl LOG: disconnection:\n> > > > > session time: 0:00:00.014 user=postgres database=postgres\n> > > > > host=[local]\n> > > > > 2024-01-26 03:49:07.558 UTC [9729:1] LOG: logical replication\n> > > > > apply worker for subscription \"tsub\" has started\n> > > > > 2024-01-26 03:49:07.563 UTC [9731:1] LOG: logical replication\n> > > > > table synchronization worker for subscription \"tsub\", table\n> > > > > \"test_mismatching_types\" has started\n> > > > > 2024-01-26 03:49:07.585 UTC [9731:2] ERROR: incorrect binary data\n> > > > > format\n> > > > > 2024-01-26 03:49:07.585 UTC [9731:3] CONTEXT: COPY\n> > > > > test_mismatching_types, line 1, column a\n> > > > >\n> > > > > In this case, \"logical replication apply worker for subscription\n> > > > > \"tsub\" has started\" appears just after \"ALTER SUBSCRIPTION\", not 3\n> > > > > minutes\n> > > > later.\n> > > > >\n> > > > > I've managed to reproduce this failure locally by running multiple\n> > > > > tests in parallel, and my analysis shows that it is caused by a\n> > > > > race condition when accessing variable table_states_valid inside\n> > tablesync.c.\n> > > > >\n> > > > > tablesync.c does the following with table_states_valid:\n> > > > > /*\n> > > > > * Callback from syscache invalidation.\n> > > > > */\n> > > > > void\n> > > > > invalidate_syncing_table_states(Datum arg, int cacheid, uint32\n> > > > > hashvalue) {\n> > > > > table_states_valid = false;\n> > > > > }\n> > > > > ...\n> > > > > static bool\n> > > > > FetchTableStates(bool *started_tx) { ...\n> > > > > if (!table_states_valid)\n> > > > > {\n> > > > > ...\n> > > > > /* Fetch all non-ready tables. */\n> > > > > rstates = GetSubscriptionRelations(MySubscription->oid,\n> > > > > true); ...\n> > > > > table_states_valid = true;\n> > > > > }\n> > > > >\n> > > > > So, when syscache invalidation occurs inside the code block \"if\n> > > > > (!table_states_valid)\", that invalidation is effectively ignored.\n> > > > >\n> > > > > In a failed case I observe the following events:\n> > > > > 1. logical replication apply worker performs\n> > > > > LogicalRepApplyLoop() -> process_syncing_tables() ->\n> > > > > process_syncing_tables_for_apply() -> FetchTableStates() periodically.\n> > > > >\n> > > > > 2. ALTER SUBSCRIPTION tsub REFRESH PUBLICATION invalidates\n> > syscache\n> > > > > for SUBSCRIPTIONRELMAP, and that leads to calling\n> > > > > invalidate_syncing_table_states().\n> > > > >\n> > > > > 3. If the apply worker manages to fetch no non-ready tables in\n> > > > > FetchTableStates() and ignore \"table_states_valid = false\" from\n> > > > > invalidate_syncing_table_states(), then it just misses the invalidation\n> > > > > event, so it keeps working without noticing non-ready tables\n> > appeared as\n> > > > > the result of ALTER SUBSCRIPTION\n> > > > > (process_syncing_tables_for_apply()\n> > > > skips\n> > > > > a loop \"foreach(lc, table_states_not_ready) ...\" until some other event\n> > > > > occurs).\n> > > > >\n> > > > > pg_usleep(100000) added just below GetSubscriptionRelations(...)\n> > > > > proves my analysis -- without it, I need tens of iterations (with\n> > > > > 50 tests running in\n> > > > > parallel) to catch the failure, but with it, I get the failure on\n> > > > > the first iteration.\n> > > >\n> > > > Thanks for the analysis, I was able to reproduce the issue with the\n> > > > steps you had shared. I agree with your analysis. I added some logs\n> > > > to verify that the invalidation was getting missed.\n> > > >\n> > > > I felt that this invalidation is getting ignored because we have\n> > > > used a boolean variable here, how about changing it slightly so that\n> > > > table_states_invalid gets incremented for every invalidation and\n> > > > then decrementing table_states_invalid after getting the non-ready\n> > > > tables like in the attached patch. I was able to verify that the test passes\n> > with the attached patch.\n> > >\n> > > Thanks for the patch.\n> > >\n> > > I am not sure if counting the invalidation number is needed, as even\n> > > if there are hundreds of invalidations outside of FetchTableStates,\n> > > one FetchTableStates call should reset the count to 0 as it is checking the\n> > latest catalog.\n> >\n> > Another approach I was thinking of is to reset table_states_valid immediately in\n> > the beginning of FetchTableStates, so any new invalidations will take care of\n> > setting table_states_valid again it again which will be handled in the next\n> > iteration of fetching non-ready tables like in the attached patch.\n>\n> I think this is not the standard appraoch for cache building. Because if any\n> ERROR happens during the cache building, then we will come into the situation\n> that table_states_valid=true while the cache data is invalid. Even if we\n> currently don't access these cache after erroring out, but I think we'd better\n> to avoid this risk.\n\nHere is an updated patch which changes the boolean variable to a\ntri-state enum and set stable state to valid only if no invalidations\nhave been occurred while the list is being prepared.\n\nRegards,\nVignesh",
"msg_date": "Thu, 1 Feb 2024 10:29:14 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "Hello Vignesh and Hou-san,\n\n01.02.2024 07:59, vignesh C wrote:\n> Here is an updated patch which changes the boolean variable to a\n> tri-state enum and set stable state to valid only if no invalidations\n> have been occurred while the list is being prepared.\n>\n\nWhile testing the v3 patch, I observed another anomaly with the 014_binary\ntest. When I run the test in parallel, I see that sometimes one of the test\ninstances runs much longer than others. For example:\n49 All tests successful.\n49 Files=1, Tests=8, 4 wallclock secs ( 0.03 usr 0.01 sys + 0.43 cusr 0.30 csys = 0.77 CPU)\n49 Result: PASS\n12 All tests successful.\n12 Files=1, Tests=8, 184 wallclock secs ( 0.02 usr 0.01 sys + 0.46 cusr 0.40 csys = 0.89 CPU)\n12 Result: PASS\n\nAs far as I can see, this happens due to another race condition, this time\nin launcher.c.\nFor such a three-minute case I see in _subscriber.log:\n2024-02-01 14:33:13.604 UTC [949255] DEBUG: relation \"public.test_mismatching_types\" does not exist\n2024-02-01 14:33:13.604 UTC [949255] CONTEXT: processing remote data for replication origin \"pg_16398\" during message \ntype \"INSERT\" in transaction 757, finished at 0/153C838\n2024-02-01 14:33:13.604 UTC [949255] ERROR: logical replication target relation \"public.test_mismatching_types\" does \nnot exist\n2024-02-01 14:33:13.604 UTC [949255] CONTEXT: processing remote data for replication origin \"pg_16398\" during message \ntype \"INSERT\" in transaction 757, finished at 0/153C838\n...\n2024-02-01 14:33:13.605 UTC [949276] 014_binary.pl LOG: statement: CREATE TABLE public.test_mismatching_types (\n a int PRIMARY KEY\n );\n2024-02-01 14:33:13.605 UTC [942451] DEBUG: unregistering background worker \"logical replication apply worker for \nsubscription 16398\"\n2024-02-01 14:33:13.605 UTC [942451] LOG: background worker \"logical replication apply worker\" (PID 949255) exited with \nexit code 1\n...\n2024-02-01 14:33:13.607 UTC [949276] 014_binary.pl LOG: statement: ALTER SUBSCRIPTION tsub REFRESH PUBLICATION;\n...\n2024-02-01 14:36:13.642 UTC [942527] DEBUG: starting logical replication worker for subscription \"tsub\"\n(there is no interesting activity between 14:33:13 and 14:36:13)\n\nSo logical replication apply worker exited because CREATE TABLE was not\nexecuted on subscriber yet, and new replication worker started because of a\ntimeout occurred in WaitLatch(..., wait_time, ...) inside\nApplyLauncherMain() (wait_time in this case is DEFAULT_NAPTIME_PER_CYCLE\n(180 sec)).\n\nBut in a normal (fast) case the same WaitLatch exits due to MyLatch set as\na result of:\nlogical replication apply worker| logicalrep_worker_onexit() ->\n ApplyLauncherWakeup() -> kill(LogicalRepCtx->launcher_pid, SIGUSR1) ->\nlauncher| procsignal_sigusr1_handler() -> SetLatch(MyLatch)).\n\nIn a bad case, I see that the SetLatch() called as well, but then the latch\ngets reset by the following code in WaitForReplicationWorkerAttach():\n rc = WaitLatch(MyLatch,\n WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,\n 10L, WAIT_EVENT_BGWORKER_STARTUP);\n\n if (rc & WL_LATCH_SET)\n {\n ResetLatch(MyLatch);\n CHECK_FOR_INTERRUPTS();\n }\n\nWith pg_usleep(300000); added just before ResetLatch and\n $node_subscriber->safe_psql(\n 'postgres', qq(\n+SELECT pg_sleep(0.5);\n CREATE TABLE public.test_mismatching_types (\nin 014_binary.pl, I can see the anomaly without running tests in parallel,\njust when running that test in a loop:\nfor ((i=1;i<=10;i++)); do echo \"iteration $i\"; make -s check -C src/test/subscription/ PROVE_TESTS=\"t/014*\"; done\n...\niteration 2\n# +++ tap check in src/test/subscription +++\nt/014_binary.pl .. ok\nAll tests successful.\nFiles=1, Tests=8, 5 wallclock secs ( 0.00 usr 0.00 sys + 0.24 cusr 0.18 csys = 0.42 CPU)\nResult: PASS\niteration 3\n# +++ tap check in src/test/subscription +++\nt/014_binary.pl .. ok\nAll tests successful.\nFiles=1, Tests=8, 183 wallclock secs ( 0.02 usr 0.00 sys + 0.28 cusr 0.25 csys = 0.55 CPU)\nResult: PASS\n...\n\nIn other words, the abnormal test execution takes place due to the\nfollowing events:\n1. logicalrep worker launcher launches replication worker and waits for it\n to attach:\n ApplyLauncherMain() -> logicalrep_worker_launch() -> WaitForReplicationWorkerAttach()\n2. logicalrep worker exits due to some error (logical replication target\n relation does not exist, in our case) and sends a signal to set the latch\n for launcher\n3. launcher sets the latch in procsignal_sigusr1_handler(), but then resets\n it inside WaitForReplicationWorkerAttach()\n4. launcher gets back to ApplyLauncherMain() where it waits for the latch\n (not set) or a timeout (which happens after DEFAULT_NAPTIME_PER_CYCLE ms).\n\nMoreover, with that sleep in WaitForReplicationWorkerAttach() added, the\ntest 027_nosuperuser executes for 3+ minutes on each run for me.\nAnd we can find such abnormal execution on the buildfarm too:\nhttps://buildfarm.postgresql.org/cgi-bin/show_stage_log.pl?nm=snakefly&dt=2024-02-01%2020%3A34%3A03&stg=subscription-check\n\nSo, if we had PG_TEST_TIMEOUT_DEFAULT less than DEFAULT_NAPTIME_PER_CYCLE,\nwe would notice this situation as a test failure, but that timeouts are\nequal (accidentally?), hence, say, wait_for_log() just waits long enough\nfor an expected replication worker to start eventually.\n\nAs to the initial issue fixes, v3 and v2 look good to me, but v2 is more\nappealing for back-patching (if this fix going to be back-patched), IMHO.\n\nBest regards,\nAlexander\n\n\n",
"msg_date": "Fri, 2 Feb 2024 09:00:00 +0300",
"msg_from": "Alexander Lakhin <exclusion@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Fri, 2 Feb 2024 at 11:30, Alexander Lakhin <exclusion@gmail.com> wrote:\n>\n> Hello Vignesh and Hou-san,\n>\n> 01.02.2024 07:59, vignesh C wrote:\n> > Here is an updated patch which changes the boolean variable to a\n> > tri-state enum and set stable state to valid only if no invalidations\n> > have been occurred while the list is being prepared.\n> >\n>\n> While testing the v3 patch, I observed another anomaly with the 014_binary\n> test. When I run the test in parallel, I see that sometimes one of the test\n> instances runs much longer than others. For example:\n> 49 All tests successful.\n> 49 Files=1, Tests=8, 4 wallclock secs ( 0.03 usr 0.01 sys + 0.43 cusr 0.30 csys = 0.77 CPU)\n> 49 Result: PASS\n> 12 All tests successful.\n> 12 Files=1, Tests=8, 184 wallclock secs ( 0.02 usr 0.01 sys + 0.46 cusr 0.40 csys = 0.89 CPU)\n> 12 Result: PASS\n>\n> As far as I can see, this happens due to another race condition, this time\n> in launcher.c.\n> For such a three-minute case I see in _subscriber.log:\n> 2024-02-01 14:33:13.604 UTC [949255] DEBUG: relation \"public.test_mismatching_types\" does not exist\n> 2024-02-01 14:33:13.604 UTC [949255] CONTEXT: processing remote data for replication origin \"pg_16398\" during message\n> type \"INSERT\" in transaction 757, finished at 0/153C838\n> 2024-02-01 14:33:13.604 UTC [949255] ERROR: logical replication target relation \"public.test_mismatching_types\" does\n> not exist\n> 2024-02-01 14:33:13.604 UTC [949255] CONTEXT: processing remote data for replication origin \"pg_16398\" during message\n> type \"INSERT\" in transaction 757, finished at 0/153C838\n> ...\n> 2024-02-01 14:33:13.605 UTC [949276] 014_binary.pl LOG: statement: CREATE TABLE public.test_mismatching_types (\n> a int PRIMARY KEY\n> );\n> 2024-02-01 14:33:13.605 UTC [942451] DEBUG: unregistering background worker \"logical replication apply worker for\n> subscription 16398\"\n> 2024-02-01 14:33:13.605 UTC [942451] LOG: background worker \"logical replication apply worker\" (PID 949255) exited with\n> exit code 1\n> ...\n> 2024-02-01 14:33:13.607 UTC [949276] 014_binary.pl LOG: statement: ALTER SUBSCRIPTION tsub REFRESH PUBLICATION;\n> ...\n> 2024-02-01 14:36:13.642 UTC [942527] DEBUG: starting logical replication worker for subscription \"tsub\"\n> (there is no interesting activity between 14:33:13 and 14:36:13)\n>\n> So logical replication apply worker exited because CREATE TABLE was not\n> executed on subscriber yet, and new replication worker started because of a\n> timeout occurred in WaitLatch(..., wait_time, ...) inside\n> ApplyLauncherMain() (wait_time in this case is DEFAULT_NAPTIME_PER_CYCLE\n> (180 sec)).\n>\n> But in a normal (fast) case the same WaitLatch exits due to MyLatch set as\n> a result of:\n> logical replication apply worker| logicalrep_worker_onexit() ->\n> ApplyLauncherWakeup() -> kill(LogicalRepCtx->launcher_pid, SIGUSR1) ->\n> launcher| procsignal_sigusr1_handler() -> SetLatch(MyLatch)).\n>\n> In a bad case, I see that the SetLatch() called as well, but then the latch\n> gets reset by the following code in WaitForReplicationWorkerAttach():\n> rc = WaitLatch(MyLatch,\n> WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,\n> 10L, WAIT_EVENT_BGWORKER_STARTUP);\n>\n> if (rc & WL_LATCH_SET)\n> {\n> ResetLatch(MyLatch);\n> CHECK_FOR_INTERRUPTS();\n> }\n>\n> With pg_usleep(300000); added just before ResetLatch and\n> $node_subscriber->safe_psql(\n> 'postgres', qq(\n> +SELECT pg_sleep(0.5);\n> CREATE TABLE public.test_mismatching_types (\n> in 014_binary.pl, I can see the anomaly without running tests in parallel,\n> just when running that test in a loop:\n> for ((i=1;i<=10;i++)); do echo \"iteration $i\"; make -s check -C src/test/subscription/ PROVE_TESTS=\"t/014*\"; done\n> ...\n> iteration 2\n> # +++ tap check in src/test/subscription +++\n> t/014_binary.pl .. ok\n> All tests successful.\n> Files=1, Tests=8, 5 wallclock secs ( 0.00 usr 0.00 sys + 0.24 cusr 0.18 csys = 0.42 CPU)\n> Result: PASS\n> iteration 3\n> # +++ tap check in src/test/subscription +++\n> t/014_binary.pl .. ok\n> All tests successful.\n> Files=1, Tests=8, 183 wallclock secs ( 0.02 usr 0.00 sys + 0.28 cusr 0.25 csys = 0.55 CPU)\n> Result: PASS\n> ...\n>\n> In other words, the abnormal test execution takes place due to the\n> following events:\n> 1. logicalrep worker launcher launches replication worker and waits for it\n> to attach:\n> ApplyLauncherMain() -> logicalrep_worker_launch() -> WaitForReplicationWorkerAttach()\n> 2. logicalrep worker exits due to some error (logical replication target\n> relation does not exist, in our case) and sends a signal to set the latch\n> for launcher\n> 3. launcher sets the latch in procsignal_sigusr1_handler(), but then resets\n> it inside WaitForReplicationWorkerAttach()\n> 4. launcher gets back to ApplyLauncherMain() where it waits for the latch\n> (not set) or a timeout (which happens after DEFAULT_NAPTIME_PER_CYCLE ms).\n>\n> Moreover, with that sleep in WaitForReplicationWorkerAttach() added, the\n> test 027_nosuperuser executes for 3+ minutes on each run for me.\n\nThanks for the steps for the issue, I was able to reproduce this issue\nin my environment with the steps provided. The attached patch has a\nproposed fix where the latch will not be set in case of the apply\nworker exiting immediately after starting.\n\nRegards,\nVignesh",
"msg_date": "Mon, 5 Feb 2024 15:43:41 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "05.02.2024 13:13, vignesh C wrote:\n> Thanks for the steps for the issue, I was able to reproduce this issue\n> in my environment with the steps provided. The attached patch has a\n> proposed fix where the latch will not be set in case of the apply\n> worker exiting immediately after starting.\n\nIt looks like the proposed fix doesn't help when ApplyLauncherWakeup()\ncalled by a backend executing CREATE SUBSCRIPTION command.\nThat is, with the v4-0002 patch applied and pg_usleep(300000L); added\njust below\n if (!worker_in_use)\n return worker_in_use;\nI still observe the test 027_nosuperuser running for 3+ minutes:\nt/027_nosuperuser.pl .. ok\nAll tests successful.\nFiles=1, Tests=19, 187 wallclock secs ( 0.01 usr 0.00 sys + 4.82 cusr 4.47 csys = 9.30 CPU)\n\nIIUC, it's because a launcher wakeup call, sent by \"CREATE SUBSCRIPTION\nregression_sub ...\", gets missed when launcher waits for start of another\nworker (logical replication worker for subscription \"admin_sub\"), launched\njust before that command.\n\nBest regards,\nAlexander\n\n\n",
"msg_date": "Tue, 6 Feb 2024 16:00:00 +0300",
"msg_from": "Alexander Lakhin <exclusion@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Tue, 6 Feb 2024 at 18:30, Alexander Lakhin <exclusion@gmail.com> wrote:\n>\n> 05.02.2024 13:13, vignesh C wrote:\n> > Thanks for the steps for the issue, I was able to reproduce this issue\n> > in my environment with the steps provided. The attached patch has a\n> > proposed fix where the latch will not be set in case of the apply\n> > worker exiting immediately after starting.\n>\n> It looks like the proposed fix doesn't help when ApplyLauncherWakeup()\n> called by a backend executing CREATE SUBSCRIPTION command.\n> That is, with the v4-0002 patch applied and pg_usleep(300000L); added\n> just below\n> if (!worker_in_use)\n> return worker_in_use;\n> I still observe the test 027_nosuperuser running for 3+ minutes:\n> t/027_nosuperuser.pl .. ok\n> All tests successful.\n> Files=1, Tests=19, 187 wallclock secs ( 0.01 usr 0.00 sys + 4.82 cusr 4.47 csys = 9.30 CPU)\n>\n> IIUC, it's because a launcher wakeup call, sent by \"CREATE SUBSCRIPTION\n> regression_sub ...\", gets missed when launcher waits for start of another\n> worker (logical replication worker for subscription \"admin_sub\"), launched\n> just before that command.\n\nYes, the wakeup call sent by the \"CREATE SUBSCRIPTION\" command was\ngetting missed in this case. The wakeup call can be sent during\nsubscription creation/modification and when the apply worker exits.\nWaitForReplicationWorkerAttach should not reset the latch here as it\nwill end up delaying the apply worker to get started after 180 seconds\ntimeout(DEFAULT_NAPTIME_PER_CYCLE). The attached patch does not reset\nthe latch and lets ApplyLauncherMain to reset the latch and checks if\nany new worker or missing worker needs to be started.\n\nRegards,\nVignesh",
"msg_date": "Thu, 8 Feb 2024 14:55:23 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "08.02.2024 12:25, vignesh C wrote:\n> Yes, the wakeup call sent by the \"CREATE SUBSCRIPTION\" command was\n> getting missed in this case. The wakeup call can be sent during\n> subscription creation/modification and when the apply worker exits.\n> WaitForReplicationWorkerAttach should not reset the latch here as it\n> will end up delaying the apply worker to get started after 180 seconds\n> timeout(DEFAULT_NAPTIME_PER_CYCLE). The attached patch does not reset\n> the latch and lets ApplyLauncherMain to reset the latch and checks if\n> any new worker or missing worker needs to be started.\n\nThank you for the updated patch!\nI ran all the subscription tests in a loop (with the sleeps added as\nbefore) and observed no failures and 180+ seconds duration.\n\nBest regards,\nAlexander\n\n\n",
"msg_date": "Thu, 8 Feb 2024 21:00:01 +0300",
"msg_from": "Alexander Lakhin <exclusion@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Thu, 8 Feb 2024 at 23:30, Alexander Lakhin <exclusion@gmail.com> wrote:\n>\n> 08.02.2024 12:25, vignesh C wrote:\n> > Yes, the wakeup call sent by the \"CREATE SUBSCRIPTION\" command was\n> > getting missed in this case. The wakeup call can be sent during\n> > subscription creation/modification and when the apply worker exits.\n> > WaitForReplicationWorkerAttach should not reset the latch here as it\n> > will end up delaying the apply worker to get started after 180 seconds\n> > timeout(DEFAULT_NAPTIME_PER_CYCLE). The attached patch does not reset\n> > the latch and lets ApplyLauncherMain to reset the latch and checks if\n> > any new worker or missing worker needs to be started.\n>\n> Thank you for the updated patch!\n> I ran all the subscription tests in a loop (with the sleeps added as\n> before) and observed no failures and 180+ seconds duration.\n\nThanks, I have created the following Commitfest entry for this:\nhttps://commitfest.postgresql.org/47/4816/\n\nRegards,\nVignesh\n\n\n",
"msg_date": "Fri, 9 Feb 2024 12:19:28 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Tue, Mar 12, 2024 at 2:59 PM vignesh C <vignesh21@gmail.com> wrote:\n\n>\n> Thanks, I have created the following Commitfest entry for this:\n> https://commitfest.postgresql.org/47/4816/\n>\n> Regards,\n> Vignesh\n>\n\nThanks for the patch, I have verified that the fix works well by following\nthe steps mentioned to reproduce the problem.\nReviewing the patch, it seems good and is well documented. Just one minor\ncomment I had was probably to change the name of the variable\ntable_states_valid to table_states_validity. The current name made sense\nwhen it was a bool, but now that it is a tri-state enum, it doesn't fit\nwell.\n\nregards,\nAjin Cherian\nFujitsu Australia\n\nOn Tue, Mar 12, 2024 at 2:59 PM vignesh C <vignesh21@gmail.com> wrote:\nThanks, I have created the following Commitfest entry for this:\nhttps://commitfest.postgresql.org/47/4816/\n\nRegards,\nVigneshThanks for the patch, I have verified that the fix works well by following the steps mentioned to reproduce the problem. Reviewing the patch, it seems good and is well documented. Just one minor comment I had was probably to change the name of the variable table_states_valid to table_states_validity. The current name made sense when it was a bool, but now that it is a tri-state enum, it doesn't fit well.regards,Ajin CherianFujitsu Australia",
"msg_date": "Tue, 12 Mar 2024 15:04:12 +1100",
"msg_from": "Ajin Cherian <itsajin@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Tue, 12 Mar 2024 at 09:34, Ajin Cherian <itsajin@gmail.com> wrote:\n>\n>\n>\n> On Tue, Mar 12, 2024 at 2:59 PM vignesh C <vignesh21@gmail.com> wrote:\n>>\n>>\n>> Thanks, I have created the following Commitfest entry for this:\n>> https://commitfest.postgresql.org/47/4816/\n>>\n>> Regards,\n>> Vignesh\n>\n>\n> Thanks for the patch, I have verified that the fix works well by following the steps mentioned to reproduce the problem.\n> Reviewing the patch, it seems good and is well documented. Just one minor comment I had was probably to change the name of the variable table_states_valid to table_states_validity. The current name made sense when it was a bool, but now that it is a tri-state enum, it doesn't fit well.\n\nThanks for reviewing the patch, the attached v6 patch has the changes\nfor the same.\n\nRegards,\nVignesh",
"msg_date": "Wed, 13 Mar 2024 09:18:48 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Wednesday, March 13, 2024 11:49 AMvignesh C <vignesh21@gmail.com> wrote:\r\n> On Tue, 12 Mar 2024 at 09:34, Ajin Cherian <itsajin@gmail.com> wrote:\r\n> >\r\n> >\r\n> >\r\n> > On Tue, Mar 12, 2024 at 2:59 PM vignesh C <vignesh21@gmail.com> wrote:\r\n> >>\r\n> >>\r\n> >> Thanks, I have created the following Commitfest entry for this:\r\n> >> https://commitfest.postgresql.org/47/4816/\r\n> >>\r\n> >> Regards,\r\n> >> Vignesh\r\n> >\r\n> >\r\n> > Thanks for the patch, I have verified that the fix works well by following the\r\n> steps mentioned to reproduce the problem.\r\n> > Reviewing the patch, it seems good and is well documented. Just one minor\r\n> comment I had was probably to change the name of the variable\r\n> table_states_valid to table_states_validity. The current name made sense when\r\n> it was a bool, but now that it is a tri-state enum, it doesn't fit well.\r\n> \r\n> Thanks for reviewing the patch, the attached v6 patch has the changes for the\r\n> same.\r\n\r\nThanks for the patches.\r\n\r\nI saw a recent similar BF error[1] which seems related to the issue that 0001\r\npatch is trying to solve. i.e. The table sync worker is somehow not started\r\nafter refreshing the publication on the subscriber. I didn't see other related ERRORs in\r\nthe log, so I think the reason is the same as the one being discussed in this\r\nthread, which is the table state invalidation got lost. And the 0001 patch\r\nlooks good to me.\r\n\r\nFor 0002, instead of avoid resetting the latch, is it possible to let the\r\nlogical rep worker wake up the launcher once after attaching ?\r\n\r\n[1] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=francolin&dt=2024-03-11%2000%3A52%3A42\r\n\r\nBest Regards,\r\nHou zj\r\n",
"msg_date": "Wed, 13 Mar 2024 04:42:42 +0000",
"msg_from": "\"Zhijie Hou (Fujitsu)\" <houzj.fnst@fujitsu.com>",
"msg_from_op": false,
"msg_subject": "RE: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Wed, 13 Mar 2024 at 10:12, Zhijie Hou (Fujitsu)\n<houzj.fnst@fujitsu.com> wrote:\n>\n> On Wednesday, March 13, 2024 11:49 AMvignesh C <vignesh21@gmail.com> wrote:\n> > On Tue, 12 Mar 2024 at 09:34, Ajin Cherian <itsajin@gmail.com> wrote:\n> > >\n> > >\n> > >\n> > > On Tue, Mar 12, 2024 at 2:59 PM vignesh C <vignesh21@gmail.com> wrote:\n> > >>\n> > >>\n> > >> Thanks, I have created the following Commitfest entry for this:\n> > >> https://commitfest.postgresql.org/47/4816/\n> > >>\n> > >> Regards,\n> > >> Vignesh\n> > >\n> > >\n> > > Thanks for the patch, I have verified that the fix works well by following the\n> > steps mentioned to reproduce the problem.\n> > > Reviewing the patch, it seems good and is well documented. Just one minor\n> > comment I had was probably to change the name of the variable\n> > table_states_valid to table_states_validity. The current name made sense when\n> > it was a bool, but now that it is a tri-state enum, it doesn't fit well.\n> >\n> > Thanks for reviewing the patch, the attached v6 patch has the changes for the\n> > same.\n>\n> Thanks for the patches.\n>\n> I saw a recent similar BF error[1] which seems related to the issue that 0001\n> patch is trying to solve. i.e. The table sync worker is somehow not started\n> after refreshing the publication on the subscriber. I didn't see other related ERRORs in\n> the log, so I think the reason is the same as the one being discussed in this\n> thread, which is the table state invalidation got lost. And the 0001 patch\n> looks good to me.\n>\n> For 0002, instead of avoid resetting the latch, is it possible to let the\n> logical rep worker wake up the launcher once after attaching ?\n\nWaking up of the launch process uses the same latch that is used for\nsubscription creation/modification and apply worker process exit. As\nthe handling of this latch for subscription creation/modification and\nworker process exit can be done only by ApplyLauncherMain, we will not\nbe able to reset the latch in WaitForReplicationWorkerAttach. I feel\nwaking up the launcher process might not help in this case as\ncurrently we will not be able to differentiate between worker\nattached, subscription creation/modification and apply worker process\nexit.\n\nRegards,\nVignesh\n\n\n",
"msg_date": "Wed, 13 Mar 2024 11:58:38 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Wednesday, March 13, 2024 11:49 AM vignesh C <vignesh21@gmail.com> wrote:\r\n> \r\n> On Tue, 12 Mar 2024 at 09:34, Ajin Cherian <itsajin@gmail.com> wrote:\r\n> >\r\n> >\r\n> >\r\n> > On Tue, Mar 12, 2024 at 2:59 PM vignesh C <vignesh21@gmail.com> wrote:\r\n> >>\r\n> >>\r\n> >> Thanks, I have created the following Commitfest entry for this:\r\n> >> https://commitfest.postgresql.org/47/4816/\r\n> >>\r\n> >> Regards,\r\n> >> Vignesh\r\n> >\r\n> >\r\n> > Thanks for the patch, I have verified that the fix works well by following the\r\n> steps mentioned to reproduce the problem.\r\n> > Reviewing the patch, it seems good and is well documented. Just one minor\r\n> comment I had was probably to change the name of the variable\r\n> table_states_valid to table_states_validity. The current name made sense when\r\n> it was a bool, but now that it is a tri-state enum, it doesn't fit well.\r\n> \r\n> Thanks for reviewing the patch, the attached v6 patch has the changes for the\r\n> same.\r\n\r\nFYI, I noticed that there is one open item on\r\nhttps://wiki.postgresql.org/wiki/PostgreSQL_17_Open_Items which is related to\r\nthe fix in this thread.\r\n\r\n--\r\nIntermittent failures in 040_standby_failover_slots_sync test\r\n Possible solution in this thread: Race condition in FetchTableStates\r\n--\r\n\r\nAFAICS, the bug discussed here is not a new issue on\r\nPG17, so I am thinking to move the item to the \"Older bugs affecting stable\r\nbranches\" section if no objections.\r\n\r\nBest Regards,\r\nHou zj\r\n\r\n",
"msg_date": "Tue, 16 Apr 2024 06:36:50 +0000",
"msg_from": "\"Zhijie Hou (Fujitsu)\" <houzj.fnst@fujitsu.com>",
"msg_from_op": false,
"msg_subject": "RE: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Wed, Mar 13, 2024 at 11:59 AM vignesh C <vignesh21@gmail.com> wrote:\n>\n> On Wed, 13 Mar 2024 at 10:12, Zhijie Hou (Fujitsu)\n> <houzj.fnst@fujitsu.com> wrote:\n> >\n> >\n> > For 0002, instead of avoid resetting the latch, is it possible to let the\n> > logical rep worker wake up the launcher once after attaching ?\n>\n> Waking up of the launch process uses the same latch that is used for\n> subscription creation/modification and apply worker process exit. As\n> the handling of this latch for subscription creation/modification and\n> worker process exit can be done only by ApplyLauncherMain, we will not\n> be able to reset the latch in WaitForReplicationWorkerAttach. I feel\n> waking up the launcher process might not help in this case as\n> currently we will not be able to differentiate between worker\n> attached, subscription creation/modification and apply worker process\n> exit.\n>\n\nIIUC, even if we set the latch once the worker attaches, the other\nset_latch by subscription creation/modification or apply_worker_exit\ncould also be consumed due to reset of latch in\nWaitForReplicationWorkerAttach(). Is that understanding correct? If\nso, can we use some other way to wake up\nWaitForReplicationWorkerAttach() say condition variable? The current\nproposal can fix the issue but looks bit adhoc.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Tue, 23 Apr 2024 16:53:47 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Wed, Mar 13, 2024 at 9:19 AM vignesh C <vignesh21@gmail.com> wrote:\n>\n> On Tue, 12 Mar 2024 at 09:34, Ajin Cherian <itsajin@gmail.com> wrote:\n> >\n> >\n> >\n> > On Tue, Mar 12, 2024 at 2:59 PM vignesh C <vignesh21@gmail.com> wrote:\n> >>\n> >>\n> >> Thanks, I have created the following Commitfest entry for this:\n> >> https://commitfest.postgresql.org/47/4816/\n> >>\n> >> Regards,\n> >> Vignesh\n> >\n> >\n> > Thanks for the patch, I have verified that the fix works well by following the steps mentioned to reproduce the problem.\n> > Reviewing the patch, it seems good and is well documented. Just one minor comment I had was probably to change the name of the variable table_states_valid to table_states_validity. The current name made sense when it was a bool, but now that it is a tri-state enum, it doesn't fit well.\n>\n> Thanks for reviewing the patch, the attached v6 patch has the changes\n> for the same.\n>\n\nv6_0001* looks good to me. This should be backpatched unless you or\nothers think otherwise.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Wed, 24 Apr 2024 11:59:22 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Tue, Apr 23, 2024 at 4:53 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Wed, Mar 13, 2024 at 11:59 AM vignesh C <vignesh21@gmail.com> wrote:\n> >\n> > On Wed, 13 Mar 2024 at 10:12, Zhijie Hou (Fujitsu)\n> > <houzj.fnst@fujitsu.com> wrote:\n> > >\n> > >\n> > > For 0002, instead of avoid resetting the latch, is it possible to let the\n> > > logical rep worker wake up the launcher once after attaching ?\n> >\n> > Waking up of the launch process uses the same latch that is used for\n> > subscription creation/modification and apply worker process exit. As\n> > the handling of this latch for subscription creation/modification and\n> > worker process exit can be done only by ApplyLauncherMain, we will not\n> > be able to reset the latch in WaitForReplicationWorkerAttach. I feel\n> > waking up the launcher process might not help in this case as\n> > currently we will not be able to differentiate between worker\n> > attached, subscription creation/modification and apply worker process\n> > exit.\n> >\n>\n> IIUC, even if we set the latch once the worker attaches, the other\n> set_latch by subscription creation/modification or apply_worker_exit\n> could also be consumed due to reset of latch in\n> WaitForReplicationWorkerAttach(). Is that understanding correct? If\n> so, can we use some other way to wake up\n> WaitForReplicationWorkerAttach() say condition variable?\n>\n\nThe other possibility is to have a GUC launcher_retry_time or\nsomething like that instead of using a DEFAULT_NAPTIME_PER_CYCLE. This\nstill may not resolve the issue if launcher_retry_time is longer but\nat least users would be able to configure it. I am not sure if this is\na good idea or not but just trying to brainstorm different ideas to\nsolve this problem.\n\nBTW, as far as I understand, this is an improvement in the existing\ncode, so should be done only for HEAD (probably PG18) and should be\ndiscussed in a separate thread.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Wed, 24 Apr 2024 15:49:35 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Wed, 24 Apr 2024 at 11:59, Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Wed, Mar 13, 2024 at 9:19 AM vignesh C <vignesh21@gmail.com> wrote:\n> >\n> > On Tue, 12 Mar 2024 at 09:34, Ajin Cherian <itsajin@gmail.com> wrote:\n> > >\n> > >\n> > >\n> > > On Tue, Mar 12, 2024 at 2:59 PM vignesh C <vignesh21@gmail.com> wrote:\n> > >>\n> > >>\n> > >> Thanks, I have created the following Commitfest entry for this:\n> > >> https://commitfest.postgresql.org/47/4816/\n> > >>\n> > >> Regards,\n> > >> Vignesh\n> > >\n> > >\n> > > Thanks for the patch, I have verified that the fix works well by following the steps mentioned to reproduce the problem.\n> > > Reviewing the patch, it seems good and is well documented. Just one minor comment I had was probably to change the name of the variable table_states_valid to table_states_validity. The current name made sense when it was a bool, but now that it is a tri-state enum, it doesn't fit well.\n> >\n> > Thanks for reviewing the patch, the attached v6 patch has the changes\n> > for the same.\n> >\n>\n> v6_0001* looks good to me. This should be backpatched unless you or\n> others think otherwise.\n\nThis patch needs to be committed in master,PG16 and PG15.\nThis is not required from PG14 onwards because they don't have\nHasSubscriptionRelations call before updating table_states_valid:\n /*\n * Does the subscription have tables?\n *\n * If there were not-READY relations found then we know it does. But\n * if table_states_not_ready was empty we still need to check again to\n * see if there are 0 tables.\n */\n has_subrels = (table_states_not_ready != NIL) ||\n HasSubscriptionRelations(MySubscription->oid);\n\nSo the invalidation function will not be called here.\n\nWhereas for PG15 and newer versions this is applicable:\nHasSubscriptionRelations calls table_open function which will get the\ninvalidate callback like in:\nHasSubscriptionRelations -> table_open -> relation_open ->\nLockRelationOid -> AcceptInvalidationMessages ->\nReceiveSharedInvalidMessages -> LocalExecuteInvalidationMessage ->\nCallSyscacheCallbacks -> invalidate_syncing_table_states\n\nThe attached patch\nv7-0001-Table-sync-missed-due-to-race-condition-in-subscr.patch\napplies for master and PG16 branch,\nv7-0001-Table-sync-missed-due-to-race-condition-in-subscr_PG15.patch\napplies for PG15 branch.\n\nRegards,\nVignesh",
"msg_date": "Wed, 24 Apr 2024 15:58:30 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Wednesday, April 24, 2024 6:29 PM vignesh C <vignesh21@gmail.com> wrote:\r\n> \r\n> On Wed, 24 Apr 2024 at 11:59, Amit Kapila <amit.kapila16@gmail.com> wrote:\r\n> >\r\n> > On Wed, Mar 13, 2024 at 9:19 AM vignesh C <vignesh21@gmail.com> wrote:\r\n> > >\r\n> > > On Tue, 12 Mar 2024 at 09:34, Ajin Cherian <itsajin@gmail.com> wrote:\r\n> > > >\r\n> > > >\r\n> > > >\r\n> > > > On Tue, Mar 12, 2024 at 2:59 PM vignesh C <vignesh21@gmail.com>\r\n> wrote:\r\n> > > >>\r\n> > > >>\r\n> > > >> Thanks, I have created the following Commitfest entry for this:\r\n> > > >> https://commitfest.postgresql.org/47/4816/\r\n> > > >>\r\n> > > >> Regards,\r\n> > > >> Vignesh\r\n> > > >\r\n> > > >\r\n> > > > Thanks for the patch, I have verified that the fix works well by following\r\n> the steps mentioned to reproduce the problem.\r\n> > > > Reviewing the patch, it seems good and is well documented. Just one\r\n> minor comment I had was probably to change the name of the variable\r\n> table_states_valid to table_states_validity. The current name made sense when\r\n> it was a bool, but now that it is a tri-state enum, it doesn't fit well.\r\n> > >\r\n> > > Thanks for reviewing the patch, the attached v6 patch has the\r\n> > > changes for the same.\r\n> > >\r\n> >\r\n> > v6_0001* looks good to me. This should be backpatched unless you or\r\n> > others think otherwise.\r\n> \r\n> This patch needs to be committed in master,PG16 and PG15.\r\n> This is not required from PG14 onwards because they don't have\r\n> HasSubscriptionRelations call before updating table_states_valid:\r\n> /*\r\n> * Does the subscription have tables?\r\n> *\r\n> * If there were not-READY relations found then we know it does. But\r\n> * if table_states_not_ready was empty we still need to check again to\r\n> * see if there are 0 tables.\r\n> */\r\n> has_subrels = (table_states_not_ready != NIL) ||\r\n> HasSubscriptionRelations(MySubscription->oid);\r\n> \r\n> So the invalidation function will not be called here.\r\n> \r\n> Whereas for PG15 and newer versions this is applicable:\r\n> HasSubscriptionRelations calls table_open function which will get the\r\n> invalidate callback like in:\r\n> HasSubscriptionRelations -> table_open -> relation_open -> LockRelationOid\r\n> -> AcceptInvalidationMessages -> ReceiveSharedInvalidMessages ->\r\n> LocalExecuteInvalidationMessage -> CallSyscacheCallbacks ->\r\n> invalidate_syncing_table_states\r\n> \r\n> The attached patch\r\n> v7-0001-Table-sync-missed-due-to-race-condition-in-subscr.patch\r\n> applies for master and PG16 branch,\r\n> v7-0001-Table-sync-missed-due-to-race-condition-in-subscr_PG15.patch\r\n> applies for PG15 branch.\r\n\r\nThanks, I have verified that the patches can be applied cleanly and fix the\r\nissue on each branch. The regression test can also pass after applying the patch\r\non my machine.\r\n\r\nBest Regards,\r\nHou zj\r\n",
"msg_date": "Thu, 25 Apr 2024 01:31:11 +0000",
"msg_from": "\"Zhijie Hou (Fujitsu)\" <houzj.fnst@fujitsu.com>",
"msg_from_op": false,
"msg_subject": "RE: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Thu, Apr 25, 2024 at 7:01 AM Zhijie Hou (Fujitsu)\n<houzj.fnst@fujitsu.com> wrote:\n>\n> On Wednesday, April 24, 2024 6:29 PM vignesh C <vignesh21@gmail.com> wrote:\n> >\n> >\n> > The attached patch\n> > v7-0001-Table-sync-missed-due-to-race-condition-in-subscr.patch\n> > applies for master and PG16 branch,\n> > v7-0001-Table-sync-missed-due-to-race-condition-in-subscr_PG15.patch\n> > applies for PG15 branch.\n>\n> Thanks, I have verified that the patches can be applied cleanly and fix the\n> issue on each branch. The regression test can also pass after applying the patch\n> on my machine.\n>\n\nPushed.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Thu, 25 Apr 2024 16:20:19 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Wed, 24 Apr 2024 at 15:49, Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Tue, Apr 23, 2024 at 4:53 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > On Wed, Mar 13, 2024 at 11:59 AM vignesh C <vignesh21@gmail.com> wrote:\n> > >\n> > > On Wed, 13 Mar 2024 at 10:12, Zhijie Hou (Fujitsu)\n> > > <houzj.fnst@fujitsu.com> wrote:\n> > > >\n> > > >\n> > > > For 0002, instead of avoid resetting the latch, is it possible to let the\n> > > > logical rep worker wake up the launcher once after attaching ?\n> > >\n> > > Waking up of the launch process uses the same latch that is used for\n> > > subscription creation/modification and apply worker process exit. As\n> > > the handling of this latch for subscription creation/modification and\n> > > worker process exit can be done only by ApplyLauncherMain, we will not\n> > > be able to reset the latch in WaitForReplicationWorkerAttach. I feel\n> > > waking up the launcher process might not help in this case as\n> > > currently we will not be able to differentiate between worker\n> > > attached, subscription creation/modification and apply worker process\n> > > exit.\n> > >\n> >\n> > IIUC, even if we set the latch once the worker attaches, the other\n> > set_latch by subscription creation/modification or apply_worker_exit\n> > could also be consumed due to reset of latch in\n> > WaitForReplicationWorkerAttach(). Is that understanding correct? If\n> > so, can we use some other way to wake up\n> > WaitForReplicationWorkerAttach() say condition variable?\n> >\n>\n> The other possibility is to have a GUC launcher_retry_time or\n> something like that instead of using a DEFAULT_NAPTIME_PER_CYCLE. This\n> still may not resolve the issue if launcher_retry_time is longer but\n> at least users would be able to configure it. I am not sure if this is\n> a good idea or not but just trying to brainstorm different ideas to\n> solve this problem.\n>\n> BTW, as far as I understand, this is an improvement in the existing\n> code, so should be done only for HEAD (probably PG18) and should be\n> discussed in a separate thread.\n\nI have started a new thread at [1] to discuss this:\nhttps://www.postgresql.org/message-id/CALDaNm01_KEgHM1tKtgXkCGLJ5209SMSmGw3UmhZbOz365_%3DeA%40mail.gmail.com\n\nRegards,\nVignesh\n\n\n",
"msg_date": "Thu, 25 Apr 2024 16:46:37 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
},
{
"msg_contents": "On Thu, 25 Apr 2024 at 16:20, Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Thu, Apr 25, 2024 at 7:01 AM Zhijie Hou (Fujitsu)\n> <houzj.fnst@fujitsu.com> wrote:\n> >\n> > On Wednesday, April 24, 2024 6:29 PM vignesh C <vignesh21@gmail.com> wrote:\n> > >\n> > >\n> > > The attached patch\n> > > v7-0001-Table-sync-missed-due-to-race-condition-in-subscr.patch\n> > > applies for master and PG16 branch,\n> > > v7-0001-Table-sync-missed-due-to-race-condition-in-subscr_PG15.patch\n> > > applies for PG15 branch.\n> >\n> > Thanks, I have verified that the patches can be applied cleanly and fix the\n> > issue on each branch. The regression test can also pass after applying the patch\n> > on my machine.\n> >\n>\n> Pushed.\n\nThanks for pushing this, I have marked the commitfest entry at [1] as committed.\n[1] - https://commitfest.postgresql.org/48/4816/\n\nRegards,\nVignesh\n\n\n",
"msg_date": "Mon, 29 Apr 2024 08:51:55 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Race condition in FetchTableStates() breaks synchronization of\n subscription tables"
}
] |
[
{
"msg_contents": "Currently, nodeMemoize.c builds the hashtable for the cache during\nexecutor startup. This is not what is done in hash joins. I think we\nshould make the two behave the same way.\n\nPer [1] and the corresponding discussion leading to that, making a\npossibly large allocation at executor startup can lead to excessively\nlong EXPLAIN (not EXPLAIN ANALYZE) times. This can confuse users as\nwe don't mention in EXPLAIN where the time is being spent.\n\nAlthough there's not yet any conclusion that Memoize is to blame,\nthere's another report from someone confused about where this time is\nbeing spent in [2].\n\nWorking on the Memoize code, I originally created the hash table\nduring executor startup to save on having to check we have a table\neach time the node is executed. However, the branch for this should\nbe quite predictable and I doubt it'll add any overhead that we would\nnotice.\n\nThe patch to do this is attached.\n\nDavid\n\n[1] https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=1e731ed12aa\n[2] https://postgr.es/m/61e642df-5f48-4e4e-b4c3-58936f90ddaa@thefreecat.org",
"msg_date": "Fri, 26 Jan 2024 19:54:16 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": true,
"msg_subject": "Delay Memoize hashtable build until executor run"
},
{
"msg_contents": "On Fri, 26 Jan 2024 at 19:54, David Rowley <dgrowleyml@gmail.com> wrote:\n> Currently, nodeMemoize.c builds the hashtable for the cache during\n> executor startup. This is not what is done in hash joins. I think we\n> should make the two behave the same way.\n\nI ran a few benchmarks on this, mostly for archive purposes.\n\n-- Test 1: Demonstrate there is a problem\n\ndrop table if exists t,r;\ncreate table t (a int);\ncreate table r (a int primary key);\ninsert into t select x%5000000 from generate_Series(1,20000000)x;\ninsert into r select x from generate_Series(0,4999999)x;\nvacuum analyze t,r;\nset work_mem='1GB';\nset enable_hashjoin=0;\nset enable_mergejoin=0;\nset max_parallel_workers_per_gather=0;\n\\timing on\n\nexplain (summary on) select count(*) from t inner join r on t.a=r.a;\n\nset enable_memoize=1;\n\n-- I'm including Planning Time just to show that the extra time is not\nspent in planning\nPlanning Time: 0.094 ms -> Time: 53.061 ms\nPlanning Time: 0.093 ms -> Time: 53.064 ms\nPlanning Time: 0.095 ms -> Time: 69.682 ms\n\nset enable_memoize=0;\n\nPlanning Time: 0.113 ms -> Time: 0.438 ms\nPlanning Time: 0.111 ms -> Time: 0.436 ms\nPlanning Time: 0.113 ms -> Time: 0.445 ms\n\nConclusion: There's a problem\n\n-- Patched with memoize on\nPlanning Time: 0.116 ms -> Time: 0.472 ms\nPlanning Time: 0.118 ms -> Time: 0.444 ms\nPlanning Time: 0.117 ms -> Time: 0.443 ms\n\nConclusion: The patch fixes the problem\n\n-- Test 2: Make sure we're not slowing things down by checking the\ntable exists each tuple\n\ndrop table if exists t,r;\n\ncreate table t (a int);\ncreate table r (a int primary key);\n\ninsert into t select 1 from generate_series(1,1000000);\ninsert into r select x from generate_series(1,1000000)x;\nvacuum analyze t,r;\n\nset enable_hashjoin=0;\nset enable_mergejoin=0;\nset enable_memoize=1;\nset max_parallel_workers_per_gather=0;\n\n-- only 1 cache miss so that we hammer the cache hit code as hard as we can\n-- with the smallest hash table possible so lookups are very fast.\nexplain (analyze, timing off) select count(*) from t inner join r on t.a=r.a;\n\n-- Master\nExecution Time: 206.403 ms\nExecution Time: 211.472 ms\nExecution Time: 204.688 ms\n\n-- Patched\nExecution Time: 205.967 ms\nExecution Time: 206.406 ms\nExecution Time: 205.061 ms\n\nConclusion: No slowdown.\n\nI'll push this change to master only as there don't seem to have been\nany complaints. We can reconsider that if someone complains.\n\nDavid\n\n\n",
"msg_date": "Tue, 30 Jan 2024 12:25:02 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Delay Memoize hashtable build until executor run"
},
{
"msg_contents": "On Tue, 30 Jan 2024 at 12:25, David Rowley <dgrowleyml@gmail.com> wrote:\n> I'll push this change to master only as there don't seem to have been\n> any complaints. We can reconsider that if someone complains.\n\nPushed.\n\nDavid\n\n\n",
"msg_date": "Tue, 30 Jan 2024 12:37:51 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Delay Memoize hashtable build until executor run"
}
] |
[
{
"msg_contents": "In 5543677ec9 we introduced an optimization that uses Limit instead of\nUnique to implement DISTINCT when all the DISTINCT pathkeys have been\nmarked as redundant. I happened to notice that this optimization was\nnot applied to partial DISTINCT, which I think should be. This can\nimprove plans in some cases, such as\n\n-- on master\nexplain (costs off) select distinct four from tenk1 where four = 4;\n QUERY PLAN\n----------------------------------------------\n Limit\n -> Gather\n Workers Planned: 4\n -> Unique\n -> Parallel Seq Scan on tenk1\n Filter: (four = 4)\n(6 rows)\n\n-- patched\nexplain (costs off) select distinct four from tenk1 where four = 4;\n QUERY PLAN\n----------------------------------------------\n Limit\n -> Gather\n Workers Planned: 4\n -> Limit\n -> Parallel Seq Scan on tenk1\n Filter: (four = 4)\n(6 rows)\n\nSuch queries might not be that common, but it's very cheap to apply this\noptimization.\n\nAttached is a patch for that.\n\nThanks\nRichard",
"msg_date": "Fri, 26 Jan 2024 15:42:33 +0800",
"msg_from": "Richard Guo <guofenglinux@gmail.com>",
"msg_from_op": true,
"msg_subject": "Apply the \"LIMIT 1\" optimization to partial DISTINCT"
},
{
"msg_contents": "On Fri, 26 Jan 2024 at 20:42, Richard Guo <guofenglinux@gmail.com> wrote:\n>\n> In 5543677ec9 we introduced an optimization that uses Limit instead of\n> Unique to implement DISTINCT when all the DISTINCT pathkeys have been\n> marked as redundant. I happened to notice that this optimization was\n> not applied to partial DISTINCT, which I think should be.\n\nIt seems very likely that the parallel plan would only be chosen if\nthe planner estimated there'd just be 1 row before the distinct.\nOtherwise, the non-partial path's LIMIT would come out so cheap that\nit would be unlikely that the parallel plan would be picked.\n\nI think your test case only chooses the parallel plan because you're\ndoing FROM tenk1 WHERE four=4. And that column only contains values\n0..3.\n\nHowever, having said that. Parallel plans are often picked when there\nis some highly selective qual as parallel_tuple_cost has to be applied\nto fewer tuples for such plans, so probably this is worth doing.\n\nDavid\n\n\n",
"msg_date": "Fri, 26 Jan 2024 21:14:01 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Apply the \"LIMIT 1\" optimization to partial DISTINCT"
},
{
"msg_contents": "On Fri, 26 Jan 2024 at 21:14, David Rowley <dgrowleyml@gmail.com> wrote:\n> However, having said that. Parallel plans are often picked when there\n> is some highly selective qual as parallel_tuple_cost has to be applied\n> to fewer tuples for such plans, so probably this is worth doing.\n\nI was messing around with your test case and didn't manage to get any\nplan that had any rows to use the partial path with the LIMIT. I\nended up dropping the test that was checking the results were empty as\nI didn't think it added much more value over the EXPLAIN output.\n\nI pushed the result.\n\nThanks for working on this.\n\nDavid\n\n\n",
"msg_date": "Wed, 31 Jan 2024 17:25:48 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Apply the \"LIMIT 1\" optimization to partial DISTINCT"
},
{
"msg_contents": "On Wed, Jan 31, 2024 at 12:26 PM David Rowley <dgrowleyml@gmail.com> wrote:\n\n> On Fri, 26 Jan 2024 at 21:14, David Rowley <dgrowleyml@gmail.com> wrote:\n> > However, having said that. Parallel plans are often picked when there\n> > is some highly selective qual as parallel_tuple_cost has to be applied\n> > to fewer tuples for such plans, so probably this is worth doing.\n>\n> I was messing around with your test case and didn't manage to get any\n> plan that had any rows to use the partial path with the LIMIT. I\n> ended up dropping the test that was checking the results were empty as\n> I didn't think it added much more value over the EXPLAIN output.\n>\n> I pushed the result.\n\n\nThanks for pushing it!\n\nThanks\nRichard\n\nOn Wed, Jan 31, 2024 at 12:26 PM David Rowley <dgrowleyml@gmail.com> wrote:On Fri, 26 Jan 2024 at 21:14, David Rowley <dgrowleyml@gmail.com> wrote:\n> However, having said that. Parallel plans are often picked when there\n> is some highly selective qual as parallel_tuple_cost has to be applied\n> to fewer tuples for such plans, so probably this is worth doing.\n\nI was messing around with your test case and didn't manage to get any\nplan that had any rows to use the partial path with the LIMIT. I\nended up dropping the test that was checking the results were empty as\nI didn't think it added much more value over the EXPLAIN output.\n\nI pushed the result.Thanks for pushing it!ThanksRichard",
"msg_date": "Wed, 31 Jan 2024 15:12:26 +0800",
"msg_from": "Richard Guo <guofenglinux@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Apply the \"LIMIT 1\" optimization to partial DISTINCT"
}
] |
[
{
"msg_contents": "Hi,\n\n9e2d870 enabled the COPY command to skip soft error, and I think we can \nadd another option which specifies the maximum tolerable number of soft \nerrors.\n\nI remember this was discussed in [1], and feel it would be useful when \nloading 'dirty' data but there is a limit to how dirty it can be.\n\nAttached a patch for this.\n\nWhat do you think?\n\n\n[1] \nhttps://www.postgresql.org/message-id/752672.1699474336%40sss.pgh.pa.us\n\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation",
"msg_date": "Fri, 26 Jan 2024 18:49:10 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "On Fri, Jan 26, 2024 at 2:49 AM torikoshia <torikoshia@oss.nttdata.com>\nwrote:\n\n> Hi,\n>\n> 9e2d870 enabled the COPY command to skip soft error, and I think we can\n> add another option which specifies the maximum tolerable number of soft\n> errors.\n>\n> I remember this was discussed in [1], and feel it would be useful when\n> loading 'dirty' data but there is a limit to how dirty it can be.\n>\n> Attached a patch for this.\n>\n> What do you think?\n>\n>\nI'm opposed to adding this particular feature.\n\nWhen implementing this kind of business rule I'd need the option to specify\na percentage, not just an absolute value.\n\nI would focus on trying to put the data required to make this kind of\ndetermination into a place where applications implementing such business\nrules and monitoring can readily get at it. The \"ERRORS TO\" and maybe a\ncorresponding \"STATS TO\" option where a table can be specified for the\nsystem to place the problematic data and stats about the copy itself.\n\nDavid J.\n\nOn Fri, Jan 26, 2024 at 2:49 AM torikoshia <torikoshia@oss.nttdata.com> wrote:Hi,\n\n9e2d870 enabled the COPY command to skip soft error, and I think we can \nadd another option which specifies the maximum tolerable number of soft \nerrors.\n\nI remember this was discussed in [1], and feel it would be useful when \nloading 'dirty' data but there is a limit to how dirty it can be.\n\nAttached a patch for this.\n\nWhat do you think?I'm opposed to adding this particular feature.When implementing this kind of business rule I'd need the option to specify a percentage, not just an absolute value.I would focus on trying to put the data required to make this kind of determination into a place where applications implementing such business rules and monitoring can readily get at it. The \"ERRORS TO\" and maybe a corresponding \"STATS TO\" option where a table can be specified for the system to place the problematic data and stats about the copy itself.David J.",
"msg_date": "Fri, 26 Jan 2024 08:20:01 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "On 2024-01-27 00:20, David G. Johnston wrote:\n\nThanks for your comments!\n\n> On Fri, Jan 26, 2024 at 2:49 AM torikoshia\n> <torikoshia@oss.nttdata.com> wrote:\n> \n>> Hi,\n>> \n>> 9e2d870 enabled the COPY command to skip soft error, and I think we\n>> can\n>> add another option which specifies the maximum tolerable number of\n>> soft\n>> errors.\n>> \n>> I remember this was discussed in [1], and feel it would be useful\n>> when\n>> loading 'dirty' data but there is a limit to how dirty it can be.\n>> \n>> Attached a patch for this.\n>> \n>> What do you think?\n> \n> I'm opposed to adding this particular feature.\n> \n> When implementing this kind of business rule I'd need the option to\n> specify a percentage, not just an absolute value.\n\nYeah, it seems useful for some cases.\nActually, Greenplum enables to specify not only the max number of bad \nrows but also its percentage[1].\n\nI may be wrong, but considering some dataloaders support something like \nreject_limit(Redshift supports MAXERROR[2], pg_bulkload supports \nPARSE_ERRORS[3]), specifying the \"number\" of the bad row might also be \nuseful.\n\nI think we can implement reject_limit specified by percentage simply \ncalculating the ratio of skipped and processed at the end of CopyFrom() \nlike this:\n\n if (cstate->opts.reject_limit > 0 && (double) skipped / (processed + \nskipped) > cstate->opts.reject_limit_percent)\n ereport(ERROR,\n \n(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),\n errmsg(\"exceeded the ratio specified \nby ..\n\n\n> I would focus on trying to put the data required to make this kind of\n> determination into a place where applications implementing such\n> business rules and monitoring can readily get at it. The \"ERRORS TO\"\n> and maybe a corresponding \"STATS TO\" option where a table can be\n> specified for the system to place the problematic data and stats about\n> the copy itself.\n\nIt'd be nice to have such informative tables, but I believe the benefit \nof reject_limit is it fails the entire loading when the threshold is \nexceeded.\nI imagine when we just have error and stats information tables for COPY, \nusers have to delete the rows when they confirmed too many errors in \nthese tables.\n\n\n[1]https://docs.vmware.com/en/VMware-Greenplum/7/greenplum-database/admin_guide-load-topics-g-handling-load-errors.html\n[2]https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-data-load.html\n[3]https://ossc-db.github.io/pg_bulkload/pg_bulkload.html\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Fri, 02 Feb 2024 15:17:15 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "\n\nOn 2024/01/26 18:49, torikoshia wrote:\n> Hi,\n> \n> 9e2d870 enabled the COPY command to skip soft error, and I think we can add another option which specifies the maximum tolerable number of soft errors.\n> \n> I remember this was discussed in [1], and feel it would be useful when loading 'dirty' data but there is a limit to how dirty it can be.\n> \n> Attached a patch for this.\n> \n> What do you think?\n\nThe patch no longer applies cleanly to HEAD. Could you update it?\n\nI think the REJECT_LIMIT feature is useful. Allowing it to be set as either the absolute number of skipped rows or a percentage of the total input rows is a good idea.\n\nHowever, if we support REJECT_LIMIT, I'm not sure if the ON_ERROR option is still necessary. REJECT_LIMIT seems to cover the same cases. For instance, REJECT_LIMIT=infinity can act like ON_ERROR=ignore, and REJECT_LIMIT=0 can act like ON_ERROR=stop.\n\nTherefore, having both ON_ERROR and REJECT_LIMIT might be confusing.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n",
"msg_date": "Wed, 3 Jul 2024 02:07:16 +0900",
"msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "On 2024-07-03 02:07, Fujii Masao wrote:\nThanks for your comments!\n\n> On 2024/01/26 18:49, torikoshia wrote:\n>> Hi,\n>> \n>> 9e2d870 enabled the COPY command to skip soft error, and I think we \n>> can add another option which specifies the maximum tolerable number of \n>> soft errors.\n>> \n>> I remember this was discussed in [1], and feel it would be useful when \n>> loading 'dirty' data but there is a limit to how dirty it can be.\n>> \n>> Attached a patch for this.\n>> \n>> What do you think?\n> \n> The patch no longer applies cleanly to HEAD. Could you update it?\n\nI'm going to update it after discussing the option format as described \nbelow.\n\n> \n> I think the REJECT_LIMIT feature is useful. Allowing it to be set as\n> either the absolute number of skipped rows or a percentage of the\n> total input rows is a good idea.\n> \n> However, if we support REJECT_LIMIT, I'm not sure if the ON_ERROR\n> option is still necessary. REJECT_LIMIT seems to cover the same cases.\n> For instance, REJECT_LIMIT=infinity can act like ON_ERROR=ignore, and\n> REJECT_LIMIT=0 can act like ON_ERROR=stop.\n\nI agree that it's possible to use only REJECT_LIMIT without ON_ERROR.\nI also think it's easy to understand that REJECT_LIMIT=0 is \nON_ERROR=stop.\nHowever, expressing REJECT_LIMIT='infinity' needs some definition like \n\"setting REJECT_LIMIT to -1 means 'infinity'\", doesn't it? If so, I \nthink this might not so intuitive.\n\nAlso, since it seems Snowflake and Redshift have both options equivalent \nto REJECT_LIMIT and ON_ERROR, having both of them in PostgreSQL COPY \nmight not be surprising:\n- Snowflake's ON_ERROR accepts \"CONTINUE | SKIP_FILE | SKIP_FILE_num | \n'SKIP_FILE_num%' | ABORT_STATEMENT\"[1]\n- Redshift has MAXERROR and IGNOREALLERRORS options[2]\n\nBTW after seeing Snowflake makes SKIP_FILE_num one of the options of \nON_ERROR, I'm a bit wondering whether REJECT_LIMIT also should be the \nsame.\n\n\n[1] \nhttps://docs.snowflake.com/en/sql-reference/sql/copy-into-table#copy-options-copyoptions\n[2] \nhttps://docs.aws.amazon.com/en_en/redshift/latest/dg/copy-parameters-data-load.html\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Thu, 04 Jul 2024 12:05:25 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "\n\nOn 2024/07/04 12:05, torikoshia wrote:\n> I'm going to update it after discussing the option format as described below.\n\nThanks!\n\n> I agree that it's possible to use only REJECT_LIMIT without ON_ERROR.\n> I also think it's easy to understand that REJECT_LIMIT=0 is ON_ERROR=stop.\n> However, expressing REJECT_LIMIT='infinity' needs some definition like \"setting REJECT_LIMIT to -1 means 'infinity'\", doesn't it? If so, I think this might not so intuitive.\n\nHow about allowing REJECT_LIMIT to accept the keywords \"infinity\", \"unlimited\",\nor \"all\" in addition to a number? This way, users can specify one of these\nkeywords instead of -1 to ignore all errors. The server code would then\ninternally set the REJECT_LIMIT to -1 or another appropriate value when\nthese keywords are used, but users wouldn't need to worry about this detail.\n\nIf we choose \"all\" as the keyword, renaming the option to IGNORE_ERRORS\nmight be more intuitive and easier to understand than REJECT_LIMIT.\n\n\n> Also, since it seems Snowflake and Redshift have both options equivalent to REJECT_LIMIT and ON_ERROR, having both of them in PostgreSQL COPY might not be surprising:\n> - Snowflake's ON_ERROR accepts \"CONTINUE | SKIP_FILE | SKIP_FILE_num | 'SKIP_FILE_num%' | ABORT_STATEMENT\"[1]\n> - Redshift has MAXERROR and IGNOREALLERRORS options[2]\n\nOk, so here's a summary of the options and their behaviors:\n\nTo ignore all errors and continue to the end:\n\n- Snowflake: ON_ERROR=CONTINUE\n- Redshift: IGNOREALLERRORS\n- Postgres (with your patch): ON_ERROR=ignore\n- Postgres (with my idea): IGNORE_ERRORS=all\n\nTo fail as soon as an error is found:\n\n- Snowflake: ON_ERROR=ABORT_STATEMENT (default) / SKIP_FILE\n- Redshift: MAXERROR=0 (default)\n- Postgres (with your patch): ON_ERROR=stop (default)\n- Postgres (with my idea): IGNORE_ERRORS=0 (default)\n\nTo fail when NNN or more errors are found:\n\n- Snowflake: ON_ERROR=SKIP_FILE_NNN\n- Redshift: MAXERROR=NNN\n- Postgres (with your patch): REJECT_LIMIT=NNN-1 and ON_ERROR=ignore\n- Postgres (with my idea): IGNORE_ERRORS=NNN\n\nThis makes me think it might be better to treat REJECT_LIMIT as\nan additional option for ON_ERROR=stop instead of ON_ERROR=ignore\nif we adopt your patch. Since ON_ERROR=stop is the default,\nusers could set the maximum number of allowed errors by specifying\nonly REJECT_LIMIT. Otherwise, they would need to specify both\nON_ERROR=ignore and REJECT_LIMIT.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n",
"msg_date": "Fri, 5 Jul 2024 12:59:11 +0900",
"msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "On 2024-07-05 12:59, Fujii Masao wrote:\n> On 2024/07/04 12:05, torikoshia wrote:\n>> I'm going to update it after discussing the option format as described \n>> below.\n> \n> Thanks!\n> \n>> I agree that it's possible to use only REJECT_LIMIT without ON_ERROR.\n>> I also think it's easy to understand that REJECT_LIMIT=0 is \n>> ON_ERROR=stop.\n>> However, expressing REJECT_LIMIT='infinity' needs some definition like \n>> \"setting REJECT_LIMIT to -1 means 'infinity'\", doesn't it? If so, I \n>> think this might not so intuitive.\n> \n> How about allowing REJECT_LIMIT to accept the keywords \"infinity\", \n> \"unlimited\",\n> or \"all\" in addition to a number? This way, users can specify one of \n> these\n> keywords instead of -1 to ignore all errors. The server code would then\n> internally set the REJECT_LIMIT to -1 or another appropriate value when\n> these keywords are used, but users wouldn't need to worry about this \n> detail.\n\nAgreed.\n\n> If we choose \"all\" as the keyword, renaming the option to IGNORE_ERRORS\n> might be more intuitive and easier to understand than REJECT_LIMIT.\n\nI feel that 'infinite' and 'unlimited' are unfamiliar values for \nPostgreSQL parameters, so 'all' might be better and IGNORE_ERRORS would \nbe a better parameter name as your suggestion.\n\n>> Also, since it seems Snowflake and Redshift have both options \n>> equivalent to REJECT_LIMIT and ON_ERROR, having both of them in \n>> PostgreSQL COPY might not be surprising:\n>> - Snowflake's ON_ERROR accepts \"CONTINUE | SKIP_FILE | SKIP_FILE_num | \n>> 'SKIP_FILE_num%' | ABORT_STATEMENT\"[1]\n>> - Redshift has MAXERROR and IGNOREALLERRORS options[2]\n> \n> Ok, so here's a summary of the options and their behaviors:\n> \n> To ignore all errors and continue to the end:\n> \n> - Snowflake: ON_ERROR=CONTINUE\n> - Redshift: IGNOREALLERRORS\n> - Postgres (with your patch): ON_ERROR=ignore\n> - Postgres (with my idea): IGNORE_ERRORS=all\n> \n> To fail as soon as an error is found:\n> \n> - Snowflake: ON_ERROR=ABORT_STATEMENT (default) / SKIP_FILE\n> - Redshift: MAXERROR=0 (default)\n> - Postgres (with your patch): ON_ERROR=stop (default)\n> - Postgres (with my idea): IGNORE_ERRORS=0 (default)\n> \n> To fail when NNN or more errors are found:\n> \n> - Snowflake: ON_ERROR=SKIP_FILE_NNN\n> - Redshift: MAXERROR=NNN\n> - Postgres (with your patch): REJECT_LIMIT=NNN-1 and ON_ERROR=ignore\n> - Postgres (with my idea): IGNORE_ERRORS=NNN\n\nThanks for the summary.\n\n> This makes me think it might be better to treat REJECT_LIMIT as\n> an additional option for ON_ERROR=stop instead of ON_ERROR=ignore\n> if we adopt your patch. Since ON_ERROR=stop is the default,\n> users could set the maximum number of allowed errors by specifying\n> only REJECT_LIMIT. Otherwise, they would need to specify both\n> ON_ERROR=ignore and REJECT_LIMIT.\n\nThat makes sense.\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Fri, 05 Jul 2024 16:13:10 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "On 2024-07-03 02:07, Fujii Masao wrote:\n> However, if we support REJECT_LIMIT, I'm not sure if the ON_ERROR \n> option is still necessary.\n\nI remembered another reason for the necessity of ON_ERROR.\n\nON_ERROR defines how to behave when encountering an error and it just \naccepts 'ignore' and 'stop' currently, but is expected to support other \noptions such as saving details of errors to a table[1].\nON_ERROR=stop is a synonym for REJECT_LIMIT=infinity, but I imagine \nREJECT_LIMIT would not replace future options of ON_ERROR.\n\nConsidering this and the option we want to add this time is to specify \nan upper limit on the number or ratio of errors, the name of this option \nlike \"reject_limit\" seems better than \"ignore_errors\".\n\nOn Fri, Jul 5, 2024 at 4:13 PM torikoshia <torikoshia@oss.nttdata.com> \nwrote:\n> On 2024-07-05 12:59, Fujii Masao wrote:\n>> On 2024/07/04 12:05, torikoshia wrote:\n>>> I'm going to update it after discussing the option format as \n>>> described\n>>> below.\n\nUpdated the patch.\n0001 sets limit by the absolute number of error rows and 0002 sets limit \nby ratio of the error.\n\n>> If we choose \"all\" as the keyword, renaming the option to \n>> IGNORE_ERRORS\n>> might be more intuitive and easier to understand than REJECT_LIMIT.\n\n> I feel that 'infinite' and 'unlimited' are unfamiliar values for\n> PostgreSQL parameters, so 'all' might be better and IGNORE_ERRORS would\n> be a better parameter name as your suggestion.\n\nAs described above, attached patch adopts REJECT_LIMIT, so it uses \n\"infinity\".\n\n>> This makes me think it might be better to treat REJECT_LIMIT as\n>> an additional option for ON_ERROR=stop instead of ON_ERROR=ignore\n>> if we adopt your patch. Since ON_ERROR=stop is the default,\n>> users could set the maximum number of allowed errors by specifying\n>> only REJECT_LIMIT. Otherwise, they would need to specify both\n>> ON_ERROR=ignore and REJECT_LIMIT.\n\n> That makes sense.\n\nOn my second thought, whatever value ON_ERROR is specified(e.g. ignore, \nstop, table), it seems fine to use REJECT_LIMIT.\nI feel REJECT_LIMIT has both \"ignore\" and \"stop\" characteristics, \nmeaning it ignores errors until it reaches REJECT_LIMIT and stops when \nit exceeds the REJECT_LIMIT.\nAnd REJECT_LIMIT seems orthogonal to 'table', which specifies where to \nsave error details.\n\nAttached patch allows using REJECT_LIMIT regardless of the ON_ERROR \noption value.\n\n\n[1] \nhttps://www.postgresql.org/message-id/flat/CACJufxH_OJpVra=0c4ow8fbxHj7heMcVaTNEPa5vAurSeNA-6Q@mail.gmail.com\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation",
"msg_date": "Wed, 17 Jul 2024 22:21:07 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "\n\nOn 2024/07/17 22:21, torikoshia wrote:\n> On 2024-07-03 02:07, Fujii Masao wrote:\n>> However, if we support REJECT_LIMIT, I'm not sure if the ON_ERROR option is still necessary.\n> \n> I remembered another reason for the necessity of ON_ERROR.\n> \n> ON_ERROR defines how to behave when encountering an error and it just accepts 'ignore' and 'stop' currently, but is expected to support other options such as saving details of errors to a table[1].\n\nWouldn't it be better to separate the option specifying where\nerror details are output from the ON_ERROR option\n(which determines behavior when encountering errors)?\n\"table\" seems valid for both ON_ERROR=ignore and ON_ERROR=stop.\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n",
"msg_date": "Fri, 19 Jul 2024 22:03:57 +0900",
"msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "Hi Torikoshia,\n\nOn Wed, Jul 17, 2024 at 9:21 PM torikoshia <torikoshia@oss.nttdata.com> wrote:\n>\n> On 2024-07-03 02:07, Fujii Masao wrote:\n> > However, if we support REJECT_LIMIT, I'm not sure if the ON_ERROR\n> > option is still necessary.\n>\n> I remembered another reason for the necessity of ON_ERROR.\n>\n> ON_ERROR defines how to behave when encountering an error and it just\n> accepts 'ignore' and 'stop' currently, but is expected to support other\n> options such as saving details of errors to a table[1].\n> ON_ERROR=stop is a synonym for REJECT_LIMIT=infinity, but I imagine\n> REJECT_LIMIT would not replace future options of ON_ERROR.\n>\n> Considering this and the option we want to add this time is to specify\n> an upper limit on the number or ratio of errors, the name of this option\n> like \"reject_limit\" seems better than \"ignore_errors\".\n>\n> On Fri, Jul 5, 2024 at 4:13 PM torikoshia <torikoshia@oss.nttdata.com>\n> wrote:\n> > On 2024-07-05 12:59, Fujii Masao wrote:\n> >> On 2024/07/04 12:05, torikoshia wrote:\n> >>> I'm going to update it after discussing the option format as\n> >>> described\n> >>> below.\n>\n> Updated the patch.\n> 0001 sets limit by the absolute number of error rows and 0002 sets limit\n> by ratio of the error.\n\nIn patch 0002, the ratio is calculated by the already skipped/processed\nrows, but what if a user wants to copy 1000 rows, and he/she can tolerate\n10 error rows, so he/she might set *reject_limit 0.01*, but one bad row in the\nfirst 100 rows will fail the entire command, this might surprise the user.\n\nThis case can be resolved by 0001 *reject_limit 10*, so I think the *by ratio*\nis less useful.\n\n>\n> >> If we choose \"all\" as the keyword, renaming the option to\n> >> IGNORE_ERRORS\n> >> might be more intuitive and easier to understand than REJECT_LIMIT.\n>\n> > I feel that 'infinite' and 'unlimited' are unfamiliar values for\n> > PostgreSQL parameters, so 'all' might be better and IGNORE_ERRORS would\n> > be a better parameter name as your suggestion.\n>\n> As described above, attached patch adopts REJECT_LIMIT, so it uses\n> \"infinity\".\n>\n> >> This makes me think it might be better to treat REJECT_LIMIT as\n> >> an additional option for ON_ERROR=stop instead of ON_ERROR=ignore\n> >> if we adopt your patch. Since ON_ERROR=stop is the default,\n> >> users could set the maximum number of allowed errors by specifying\n> >> only REJECT_LIMIT. Otherwise, they would need to specify both\n> >> ON_ERROR=ignore and REJECT_LIMIT.\n>\n> > That makes sense.\n>\n> On my second thought, whatever value ON_ERROR is specified(e.g. ignore,\n> stop, table), it seems fine to use REJECT_LIMIT.\n> I feel REJECT_LIMIT has both \"ignore\" and \"stop\" characteristics,\n> meaning it ignores errors until it reaches REJECT_LIMIT and stops when\n> it exceeds the REJECT_LIMIT.\n> And REJECT_LIMIT seems orthogonal to 'table', which specifies where to\n> save error details.\n>\n> Attached patch allows using REJECT_LIMIT regardless of the ON_ERROR\n> option value.\n>\n>\n> [1]\n> https://www.postgresql.org/message-id/flat/CACJufxH_OJpVra=0c4ow8fbxHj7heMcVaTNEPa5vAurSeNA-6Q@mail.gmail.com\n>\n> --\n> Regards,\n>\n> --\n> Atsushi Torikoshi\n> NTT DATA Group Corporation\n\n\n\n-- \nRegards\nJunwang Zhao\n\n\n",
"msg_date": "Fri, 19 Jul 2024 22:48:31 +0800",
"msg_from": "Junwang Zhao <zhjwpku@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "\n\nOn 2024/07/19 22:03, Fujii Masao wrote:\n> \n> \n> On 2024/07/17 22:21, torikoshia wrote:\n>> On 2024-07-03 02:07, Fujii Masao wrote:\n>>> However, if we support REJECT_LIMIT, I'm not sure if the ON_ERROR option is still necessary.\n>>\n>> I remembered another reason for the necessity of ON_ERROR.\n>>\n>> ON_ERROR defines how to behave when encountering an error and it just accepts 'ignore' and 'stop' currently, but is expected to support other options such as saving details of errors to a table[1].\n> \n> Wouldn't it be better to separate the option specifying where\n> error details are output from the ON_ERROR option\n> (which determines behavior when encountering errors)?\n> \"table\" seems valid for both ON_ERROR=ignore and ON_ERROR=stop.\n\nI still find it odd to accept \"table\" as a value for ON_ERROR. However,\n\"set_to_null\" or \"replace-column\" proposed in [1] seem valid for\nON_ERROR. So, I'm okay with keeping the ON_ERROR option.\n\n\n> On my second thought, whatever value ON_ERROR is specified(e.g. ignore, stop, table), it seems fine to use REJECT_LIMIT.\n> I feel REJECT_LIMIT has both \"ignore\" and \"stop\" characteristics, meaning it ignores errors until it reaches REJECT_LIMIT and stops when it exceeds the REJECT_LIMIT.\n\nON_ERROR specifies how to handle errors, and \"stop\" means to fail\nthe command. So, if ON_ERROR=stop, REJECT_LIMIT should have no effect,\nand the command should fail immediately upon encountering an error.\n\nAs in your original proposal, I now think REJECT_LIMIT should only\napply when ON_ERROR=ignore. The command would ignore errors and\ncontinue processing, but if the number of errors exceeds REJECT_LIMIT,\nthe command should fail. Thought?\n\nBTW if \"set_to_null\" is supported someday, REJECT_LIMIT can also\napply. The command would cinsert NULL into the target table upon\nencountering errors and continue, but fail if the number of errors\nexceed REJECT_LIMIT.\n\nRegards,\n\n[1] https://www.postgresql.org/message-id/flat/CAKFQuwawy1e6YR4S=j+y7pXqg_Dw1WBVrgvf=BP3d1_aSfe_+Q@mail.gmail.com\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n",
"msg_date": "Sat, 20 Jul 2024 02:08:39 +0900",
"msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "On Fri, Jul 19, 2024 at 11:48 PM Junwang Zhao <zhjwpku@gmail.com> wrote:\nThanks for the comment.\n\n> In patch 0002, the ratio is calculated by the already skipped/processed\n> rows, but what if a user wants to copy 1000 rows, and he/she can \n> tolerate\n> 10 error rows, so he/she might set *reject_limit 0.01*, but one bad row \n> in the\n> first 100 rows will fail the entire command, this might surprise the \n> user.\n\nSince the ratio is calculated after all data is processed, the case \"one \nbad row in the first 100 rows will fail the entire command\" doesn't \nhappen:\n\n\n =# \\! wc -l 1000rows-with-10err.data\n 1000 1000rows-with-10err.data\n\n =# COPY t1 from '1000rows-with-10err.data' with (log_verbosity \nverbose, reject_limit 0.01);\n NOTICE: skipping row due to data type incompatibility at line 10 for \ncolumn i: \"a\"\n NOTICE: skipping row due to data type incompatibility at line 11 for \ncolumn i: \"a\"\n NOTICE: skipping row due to data type incompatibility at line 12 for \ncolumn i: \"a\"\n NOTICE: skipping row due to data type incompatibility at line 13 for \ncolumn i: \"a\"\n NOTICE: skipping row due to data type incompatibility at line 14 for \ncolumn i: \"a\"\n NOTICE: skipping row due to data type incompatibility at line 15 for \ncolumn i: \"a\"\n NOTICE: skipping row due to data type incompatibility at line 16 for \ncolumn i: \"a\"\n NOTICE: skipping row due to data type incompatibility at line 17 for \ncolumn i: \"a\"\n NOTICE: skipping row due to data type incompatibility at line 18 for \ncolumn i: \"a\"\n NOTICE: skipping row due to data type incompatibility at line 19 for \ncolumn i: \"a\"\n NOTICE: 10 rows were skipped due to data type incompatibility\n COPY 990\n\n\nOn 2024-07-20 02:08, Fujii Masao wrote:\n> On 2024/07/19 22:03, Fujii Masao wrote:\n>> \n>> \n>> On 2024/07/17 22:21, torikoshia wrote:\n>>> On 2024-07-03 02:07, Fujii Masao wrote:\n>>>> However, if we support REJECT_LIMIT, I'm not sure if the ON_ERROR \n>>>> option is still necessary.\n>>> \n>>> I remembered another reason for the necessity of ON_ERROR.\n>>> \n>>> ON_ERROR defines how to behave when encountering an error and it just \n>>> accepts 'ignore' and 'stop' currently, but is expected to support \n>>> other options such as saving details of errors to a table[1].\n>> \n>> Wouldn't it be better to separate the option specifying where\n>> error details are output from the ON_ERROR option\n>> (which determines behavior when encountering errors)?\n>> \"table\" seems valid for both ON_ERROR=ignore and ON_ERROR=stop.\n> \n> I still find it odd to accept \"table\" as a value for ON_ERROR. However,\n> \"set_to_null\" or \"replace-column\" proposed in [1] seem valid for\n> ON_ERROR. So, I'm okay with keeping the ON_ERROR option.\n\nAgreed.\n\n>> On my second thought, whatever value ON_ERROR is specified(e.g. \n>> ignore, stop, table), it seems fine to use REJECT_LIMIT.\n>> I feel REJECT_LIMIT has both \"ignore\" and \"stop\" characteristics, \n>> meaning it ignores errors until it reaches REJECT_LIMIT and stops when \n>> it exceeds the REJECT_LIMIT.\n> \n> ON_ERROR specifies how to handle errors, and \"stop\" means to fail\n> the command. So, if ON_ERROR=stop, REJECT_LIMIT should have no effect,\n> and the command should fail immediately upon encountering an error.\n> \n> As in your original proposal, I now think REJECT_LIMIT should only\n> apply when ON_ERROR=ignore. The command would ignore errors and\n> continue processing, but if the number of errors exceeds REJECT_LIMIT,\n> the command should fail. Thought?\n\nMakes sense.\nUpdated the patch.\n\n> BTW if \"set_to_null\" is supported someday, REJECT_LIMIT can also\n> apply. The command would cinsert NULL into the target table upon\n> encountering errors and continue, but fail if the number of errors\n> exceed REJECT_LIMIT.\n\nAgreed.\n\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation",
"msg_date": "Mon, 22 Jul 2024 21:37:03 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "Hi! Nice feature.\n\nFew comments:\n\n> + When a positive integer value is specified, <command>COPY</command> limits\n> + the maximum tolerable number of errors while converting a column's input\n> + value into its data type.\n\nIf nothing is specified, then the maximum tolerable number of errors\nis one, right? Should we state this explicitly in the documentation?\n\n> +COPY x from stdin with (on_error ignore, reject_limit 0);\nHow about a test where reject_limit is a string, but not\n(case-intensively) 'infinity'?\n\n> + CopyRejectLimits reject_limits; /* thresholds of reject_limit */\n\nWhy are there multiple thresholds? Can we have only one?\n\nOther places look good to me.\n\n\n",
"msg_date": "Mon, 22 Jul 2024 22:06:11 +0500",
"msg_from": "Kirill Reshke <reshkekirill@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "\n\nOn 2024/07/22 21:37, torikoshia wrote:\n> On Fri, Jul 19, 2024 at 11:48 PM Junwang Zhao <zhjwpku@gmail.com> wrote:\n> Thanks for the comment.\n> \n>> In patch 0002, the ratio is calculated by the already skipped/processed\n>> rows, but what if a user wants to copy 1000 rows, and he/she can tolerate\n>> 10 error rows, so he/she might set *reject_limit 0.01*, but one bad row in the\n>> first 100 rows will fail the entire command, this might surprise the user.\n> \n> Since the ratio is calculated after all data is processed, the case \"one bad row in the first 100 rows will fail the entire command\" doesn't happen:\n\nYes, but is this the desired behavior when using the ratio threshold?\nI was thinking that COPY should fail once the error ratio (errors vs.\ntotal rows in the input file) reaches the threshold. Since it's\ndifficult to know the total number of rows in the input file,\nimplementing this seems not easy, though.\n\n> Updated the patch.\n\nThanks for updating the patch!\n\n\n+ This option must be used with <literal>ON_ERROR</literal> to be set to\n+ other than <literal>stop</literal>.\n\nRegarding the ON_ERROR option, now it only has two values.\nInstead of saying \"other than stop,\" we should simply use \"ignore\"\nfor clarity and intuition?\n\n\n+ When specified <literal>INFINITY</literal>, <command>COPY</command> ignores all\n+ the errors. This is a synonym for <literal>ON_ERROR</literal> <literal>ignore</literal>.\n\nFor the INFINITY value, the description is a bit unclear.\nAs I understand it, INFINITY is the default for REJECT_LIMIT.\nSo, if ON_ERROR=ignore is set without specifying REJECT_LIMIT,\nCOPY will ignore all errors, similar to when REJECT_LIMIT=INFINITY is used.\n\n\nIn line with my previous suggestion, if we support only REJECT_LIMIT\nwithout ON_ERROR, having INFINITY makes sense. However,\nwith ON_ERROR supported, REJECT_LIMIT=INFINITY seems redundant.\nUsers can just set ON_ERROR=ignore to ignore all errors,\nmaking INFINITY unnecessary for REJECT_LIMIT. This is open for\ndiscussion, but I believe it's better to remove INFINITY from\nthe REJECT_LIMIT options.\n\n\n+\t\telse if (strcmp(defel->defname, \"reject_limit\") == 0)\n+\t\t{\n+\t\t\tif (reject_limit_specified)\n+\t\t\t\terrorConflictingDefElem(defel, pstate);\n+\t\t\tif (!opts_out->on_error)\n+\t\t\t\tereport(ERROR,\n+\t\t\t\t\t\t(errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n+\t\t\t\t\t\t errmsg(\"REJECT_LIMIT requires ON_ERROR to be set to other than stop\")));\n\nUsing \"ignore\" instead of \"other than stop\" in the error message\nis clearer and more intuitive.\n\n\nChecking if ON_ERROR and REJECT_LIMIT are specified should be\ndone after the foreach() processing of the options. Otherwise,\nif REJECT_LIMIT is specified before ON_ERROR, unexpected errors can occur.\n\n---------------\n=# copy test from '...' WITH (REJECT_LIMIT 7, ON_ERROR 'ignore');\nERROR: REJECT_LIMIT requires ON_ERROR to be set to other than stop\n---------------\n\n\n+\t\t\t\tereport(ERROR,\n+\t\t\t\t\t\t(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),\n+\t\t\t\t\t\t errmsg(\"exceeded the number specified by REJECT_LIMIT \\\"%lld\\\"\",\n+\t\t\t\t\t\t\t\t(long long) cstate->opts.reject_limits.num_err)));\n\nThe error message isn't clear about what exceeded REJECT_LIMIT.\nHow about saying \"skipped more than REJECT_LIMIT rows\" or something instead?\n\n\n+/*\n+ * A struct to hold reject_limit options, in a parsed form.\n+ * More values to be added in another patch.\n+ */\n\nThe latter comment doesn't seem necessary or helpful.\n\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n",
"msg_date": "Tue, 23 Jul 2024 13:35:40 +0900",
"msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "On Tue, Jul 23, 2024 at 1:35 PM Fujii Masao \n<masao.fujii@oss.nttdata.com> wrote:\n\nThanks for your review.\n\n> On 2024/07/22 21:37, torikoshia wrote:\n>> On Fri, Jul 19, 2024 at 11:48 PM Junwang Zhao <zhjwpku@gmail.com> \n>> wrote:\n>> Thanks for the comment.\n>> \n>>> In patch 0002, the ratio is calculated by the already \n>>> skipped/processed\n>>> rows, but what if a user wants to copy 1000 rows, and he/she can \n>>> tolerate\n>>> 10 error rows, so he/she might set *reject_limit 0.01*, but one bad \n>>> row in the\n>>> first 100 rows will fail the entire command, this might surprise the \n>>> user.\n>> \n>> Since the ratio is calculated after all data is processed, the case \n>> \"one bad row in the first 100 rows will fail the entire command\" \n>> doesn't happen:\n> \n> Yes, but is this the desired behavior when using the ratio threshold?\n> I was thinking that COPY should fail once the error ratio (errors vs.\n> total rows in the input file) reaches the threshold.\n\nUsers might expect like you.\nHowever, implementing it would need a row number counting feature as you \npointed out, and it seems an overkill.\n\nDescribing the difference between ratio and number in the manual might \nhelp, but\nit might be better to make REJECT_LIMIT support only the number of \nerrors and leave it to the user to calculate the number from the ratio.\n\nI'd like to hear if anyone has an opinion on the need for supporting \nratio.\nI remember David prefers ratio[1].\n\n> + This option must be used with <literal>ON_ERROR</literal> to be \n> set to\n> + other than <literal>stop</literal>.\n> \n> Regarding the ON_ERROR option, now it only has two values.\n> Instead of saying \"other than stop,\" we should simply use \"ignore\"\n> for clarity and intuition?\n\nI'll Modify it.\nThe reason for the roundabout wording was the expectation that on_error \nwould support values other than these in the future, but as you point \nout, there are currently only two.\n\n\n> + When specified <literal>INFINITY</literal>, \n> <command>COPY</command> ignores all\n> + the errors. This is a synonym for <literal>ON_ERROR</literal> \n> <literal>ignore</literal>.\n> \n> For the INFINITY value, the description is a bit unclear.\n> As I understand it, INFINITY is the default for REJECT_LIMIT.\n> So, if ON_ERROR=ignore is set without specifying REJECT_LIMIT,\n> COPY will ignore all errors, similar to when REJECT_LIMIT=INFINITY is \n> used.\n> \n> \n> In line with my previous suggestion, if we support only REJECT_LIMIT\n> without ON_ERROR, having INFINITY makes sense. However,\n> with ON_ERROR supported, REJECT_LIMIT=INFINITY seems redundant.\n> Users can just set ON_ERROR=ignore to ignore all errors,\n> making INFINITY unnecessary for REJECT_LIMIT. This is open for\n> discussion, but I believe it's better to remove INFINITY from\n> the REJECT_LIMIT options.\n\nAgreed.\nUnless there are opposing opinions, I'm going to remove 'INFINITY' in \nthe next patch.\n\n> + else if (strcmp(defel->defname, \"reject_limit\") == 0)\n> + {\n> + if (reject_limit_specified)\n> + errorConflictingDefElem(defel, pstate);\n> + if (!opts_out->on_error)\n> + ereport(ERROR,\n> + \n> (errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n> + errmsg(\"REJECT_LIMIT \n> requires ON_ERROR to be set to other than stop\")));\n> \n> Using \"ignore\" instead of \"other than stop\" in the error message\n> is clearer and more intuitive.\n\nAgreed.\n\n\n> Checking if ON_ERROR and REJECT_LIMIT are specified should be\n> done after the foreach() processing of the options. Otherwise,\n> if REJECT_LIMIT is specified before ON_ERROR, unexpected errors can \n> occur.\n> \n> ---------------\n> =# copy test from '...' WITH (REJECT_LIMIT 7, ON_ERROR 'ignore');\n> ERROR: REJECT_LIMIT requires ON_ERROR to be set to other than stop\n> ---------------\n\nUgh, I'll modify it.\n\n> + ereport(ERROR,\n> + \n> (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),\n> + errmsg(\"exceeded the \n> number specified by REJECT_LIMIT \\\"%lld\\\"\",\n> + (long \n> long) cstate->opts.reject_limits.num_err)));\n> \n> The error message isn't clear about what exceeded REJECT_LIMIT.\n> How about saying \"skipped more than REJECT_LIMIT rows\" or something \n> instead?\n\nAgreed.\n\n> +/*\n> + * A struct to hold reject_limit options, in a parsed form.\n> + * More values to be added in another patch.\n> + */\n> \n> The latter comment doesn't seem necessary or helpful.\n\nAgreed.\n\n[1] \nhttps://www.postgresql.org/message-id/CAKFQuwYP91_G6tktYFTZq_CmkZ_%3DzuWjkz1%2B25Nd8bpsrDkx5Q%40mail.gmail.com\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Tue, 23 Jul 2024 23:06:32 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "On 2024-07-23 02:06, Kirill Reshke wrote:\n\nThanks for your review.\n\n> Few comments:\n> \n>> + When a positive integer value is specified, \n>> <command>COPY</command> limits\n>> + the maximum tolerable number of errors while converting a \n>> column's input\n>> + value into its data type.\n> \n> If nothing is specified, then the maximum tolerable number of errors\n> is one, right? Should we state this explicitly in the documentation?\n\nREJECT_LIMIT now can be used wonly when on_error=ignore, I think the \ndefault(when only on_error=ignore is specified) is unlimited.\nAnyway, I'm going to add a description about the default.\n\n>> +COPY x from stdin with (on_error ignore, reject_limit 0);\n> How about a test where reject_limit is a string, but not\n> (case-intensively) 'infinity'?\n\nConsidering the discussion in[1], I'm now going to remove 'infinity'.\n\n>> + CopyRejectLimits reject_limits; /* thresholds of reject_limit */\n> \n> Why are there multiple thresholds? Can we have only one?\n\nThis is because I thought it'd be more convenient to support both the \nnumber and the ratio of error, but I'm also beginning to think that it \nmight be better to support only the number of cases, as discussed in \n[1].\n\n[1]https://www.postgresql.org/message-id/5f807fcf3a36df7ba41464ab40b5c37d%40oss.nttdata.com\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Tue, 23 Jul 2024 23:10:24 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "Updated the patch.\n\nOn 2024-07-23 23:06, torikoshia wrote:\n\n> On Tue, Jul 23, 2024 at 1:35 PM Fujii Masao \n> <masao.fujii@oss.nttdata.com> wrote:\n> \n> Thanks for your review.\n> \n>> On 2024/07/22 21:37, torikoshia wrote:\n>>> On Fri, Jul 19, 2024 at 11:48 PM Junwang Zhao <zhjwpku@gmail.com> \n>>> wrote:\n>>> Thanks for the comment.\n>>> \n>>>> In patch 0002, the ratio is calculated by the already \n>>>> skipped/processed\n>>>> rows, but what if a user wants to copy 1000 rows, and he/she can \n>>>> tolerate\n>>>> 10 error rows, so he/she might set *reject_limit 0.01*, but one bad \n>>>> row in the\n>>>> first 100 rows will fail the entire command, this might surprise the \n>>>> user.\n>>> \n>>> Since the ratio is calculated after all data is processed, the case \n>>> \"one bad row in the first 100 rows will fail the entire command\" \n>>> doesn't happen:\n>> \n>> Yes, but is this the desired behavior when using the ratio threshold?\n>> I was thinking that COPY should fail once the error ratio (errors vs.\n>> total rows in the input file) reaches the threshold.\n> \n> Users might expect like you.\n> However, implementing it would need a row number counting feature as\n> you pointed out, and it seems an overkill.\n> \n> Describing the difference between ratio and number in the manual might \n> help, but\n> it might be better to make REJECT_LIMIT support only the number of\n> errors and leave it to the user to calculate the number from the\n> ratio.\n> \n> I'd like to hear if anyone has an opinion on the need for supporting \n> ratio.\n\nSince there was no opinion about it, attached a patch only for \nREJECT_LIMIT specifying number.\n\n>> + This option must be used with <literal>ON_ERROR</literal> to be \n>> set to\n>> + other than <literal>stop</literal>.\n>> \n>> Regarding the ON_ERROR option, now it only has two values.\n>> Instead of saying \"other than stop,\" we should simply use \"ignore\"\n>> for clarity and intuition?\n> \n> I'll Modify it.\n> The reason for the roundabout wording was the expectation that\n> on_error would support values other than these in the future, but as\n> you point out, there are currently only two.\n> \n> \n>> + When specified <literal>INFINITY</literal>, \n>> <command>COPY</command> ignores all\n>> + the errors. This is a synonym for <literal>ON_ERROR</literal> \n>> <literal>ignore</literal>.\n>> \n>> For the INFINITY value, the description is a bit unclear.\n>> As I understand it, INFINITY is the default for REJECT_LIMIT.\n>> So, if ON_ERROR=ignore is set without specifying REJECT_LIMIT,\n>> COPY will ignore all errors, similar to when REJECT_LIMIT=INFINITY is \n>> used.\n>> \n>> \n>> In line with my previous suggestion, if we support only REJECT_LIMIT\n>> without ON_ERROR, having INFINITY makes sense. However,\n>> with ON_ERROR supported, REJECT_LIMIT=INFINITY seems redundant.\n>> Users can just set ON_ERROR=ignore to ignore all errors,\n>> making INFINITY unnecessary for REJECT_LIMIT. This is open for\n>> discussion, but I believe it's better to remove INFINITY from\n>> the REJECT_LIMIT options.\n> \n> Agreed.\n> Unless there are opposing opinions, I'm going to remove 'INFINITY' in\n> the next patch.\n\nAs there are no opposing opinions, removed 'INFINITY' as well.\n\n>> + else if (strcmp(defel->defname, \"reject_limit\") == 0)\n>> + {\n>> + if (reject_limit_specified)\n>> + errorConflictingDefElem(defel, \n>> pstate);\n>> + if (!opts_out->on_error)\n>> + ereport(ERROR,\n>> + \n>> (errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n>> + errmsg(\"REJECT_LIMIT \n>> requires ON_ERROR to be set to other than stop\")));\n>> \n>> Using \"ignore\" instead of \"other than stop\" in the error message\n>> is clearer and more intuitive.\n> \n> Agreed.\n> \n> \n>> Checking if ON_ERROR and REJECT_LIMIT are specified should be\n>> done after the foreach() processing of the options. Otherwise,\n>> if REJECT_LIMIT is specified before ON_ERROR, unexpected errors can \n>> occur.\n>> \n>> ---------------\n>> =# copy test from '...' WITH (REJECT_LIMIT 7, ON_ERROR 'ignore');\n>> ERROR: REJECT_LIMIT requires ON_ERROR to be set to other than stop\n>> ---------------\n> \n> Ugh, I'll modify it.\n> \n>> + ereport(ERROR,\n>> + \n>> (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),\n>> + errmsg(\"exceeded the \n>> number specified by REJECT_LIMIT \\\"%lld\\\"\",\n>> + (long \n>> long) cstate->opts.reject_limits.num_err)));\n>> \n>> The error message isn't clear about what exceeded REJECT_LIMIT.\n>> How about saying \"skipped more than REJECT_LIMIT rows\" or something \n>> instead?\n> \n> Agreed.\n> \n>> +/*\n>> + * A struct to hold reject_limit options, in a parsed form.\n>> + * More values to be added in another patch.\n>> + */\n>> \n>> The latter comment doesn't seem necessary or helpful.\n> \n> Agreed.\n> \n> [1] \n> https://www.postgresql.org/message-id/CAKFQuwYP91_G6tktYFTZq_CmkZ_%3DzuWjkz1%2B25Nd8bpsrDkx5Q%40mail.gmail.com\n\n\n\nOn Tue, Jul 23, 2024 at 11:10 PM torikoshia <torikoshia@oss.nttdata.com> \nwrote:\n> On 2024-07-23 02:06, Kirill Reshke wrote:\n\n>> If nothing is specified, then the maximum tolerable number of errors\n>> is one, right? Should we state this explicitly in the documentation?\n\n> REJECT_LIMIT now can be used wonly when on_error=ignore, I think the\n> default(when only on_error=ignore is specified) is unlimited.\n> Anyway, I'm going to add a description about the default.\n\nAdded the following description:\n\n+ Just setting <literal>ON_ERROR</literal> to \n<literal>ignore</literal>\n+ tolerates unlimited number of errors.\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation",
"msg_date": "Tue, 24 Sep 2024 14:25:47 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "\n\nOn 2024/09/24 14:25, torikoshia wrote:\n> Updated the patch.\n\nThanks for updating the patch!\n\n+ REJECT_LIMIT { <replaceable class=\"parameter\">integer</replaceable> }\n\nThe curly braces {} seem unnecessary here.\n\n+ When a positive integer value is specified, <command>COPY</command> limits\n+ the maximum tolerable number of errors while converting a column's input\n+ value into its data type.\n+ If input data caused more errors than the specified value, entire\n+ <command>COPY</command> fails.\n+ Otherwise, <command>COPY</command> discards the input row and continues\n+ with the next one.\n+ This option must be used with <literal>ON_ERROR</literal> to be set to\n+ <literal>ignore</literal>.\n+ Just setting <literal>ON_ERROR</literal> to <literal>ignore</literal>\n+ tolerates unlimited number of errors.\n\nRegarding the description of REJECT_LIMIT, how about clarifying what the option specifies up front, like this:\n\n----------------\nSpecifies the maximum number of errors tolerated while converting a column's\ninput value to its data type, when on_error is set to \"ignore.\" If the input\ncauses more errors than the specified value, the COPY command fails,\neven with on_error set to \"ignore.\" This value must be positive and used with\non_error=\"ignore\". If not specified, on_error=\"ignore\" allows an unlimited\nnumber of errors, meaning COPY will skip all erroneous data.\n----------------\n\n+\t\t\tereport(ERROR,\n+\t\t\t\t(errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n+\t\t\t\t errmsg(\"number for REJECT_LIMIT must be greater than zero\")));\n+\t}\n+\telse\n+\t\tereport(ERROR,\n+\t\t\t(errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n+\t\t\t errmsg(\"value for REJECT_LIMIT must be positive integer\")));\n\nThe phrases \"number for\" and \"value for\" seem unnecessary in the error messages.\nAlso, \"positive number\" should be \"a positive number.\" Would it be better to display\nthe actual specified value in the error message, like: errmsg(\"REJECT_LIMIT (%s) must\nbe a positive number\", value)?\n\nLastly, during my testing, if nothing is specified for REJECT_LIMIT\n(e.g., COPY ... WITH (..., REJECT_LIMIT)), the COPY command caused a segmentation fault.\n\n\n>> I'd like to hear if anyone has an opinion on the need for supporting ratio.\n> \n> Since there was no opinion about it, attached a patch only for REJECT_LIMIT specifying number.\n\n+1\n\n> As there are no opposing opinions, removed 'INFINITY' as well.\n\n+1\n\nRegards,\n\n-- \nFujii Masao\nAdvanced Computing Technology Center\nResearch and Development Headquarters\nNTT DATA CORPORATION\n\n\n\n",
"msg_date": "Wed, 25 Sep 2024 02:22:52 +0900",
"msg_from": "Fujii Masao <masao.fujii@oss.nttdata.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "On 2024-09-25 02:22, Fujii Masao wrote:\nThanks for your review!\n\nAttached v5 patch.\n\n> On 2024/09/24 14:25, torikoshia wrote:\n>> Updated the patch.\n> \n> Thanks for updating the patch!\n> \n> + REJECT_LIMIT { <replaceable \n> class=\"parameter\">integer</replaceable> }\n> \n> The curly braces {} seem unnecessary here.\n> \n> + When a positive integer value is specified,\n> <command>COPY</command> limits\n> + the maximum tolerable number of errors while converting a \n> column's input\n> + value into its data type.\n> + If input data caused more errors than the specified value, \n> entire\n> + <command>COPY</command> fails.\n> + Otherwise, <command>COPY</command> discards the input row and \n> continues\n> + with the next one.\n> + This option must be used with <literal>ON_ERROR</literal> to be \n> set to\n> + <literal>ignore</literal>.\n> + Just setting <literal>ON_ERROR</literal> to \n> <literal>ignore</literal>\n> + tolerates unlimited number of errors.\n> \n> Regarding the description of REJECT_LIMIT, how about clarifying what\n> the option specifies up front, like this:\n> \n> ----------------\n> Specifies the maximum number of errors tolerated while converting a \n> column's\n> input value to its data type, when on_error is set to \"ignore.\" If the \n> input\n> causes more errors than the specified value, the COPY command fails,\n> even with on_error set to \"ignore.\" This value must be positive and \n> used with\n> on_error=\"ignore\". If not specified, on_error=\"ignore\" allows an \n> unlimited\n> number of errors, meaning COPY will skip all erroneous data.\n> ----------------\n\nThanks for writing it. It seems better.\n\n> +\t\t\tereport(ERROR,\n> +\t\t\t\t(errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n> +\t\t\t\t errmsg(\"number for REJECT_LIMIT must be greater than zero\")));\n> +\t}\n> +\telse\n> +\t\tereport(ERROR,\n> +\t\t\t(errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n> +\t\t\t errmsg(\"value for REJECT_LIMIT must be positive integer\")));\n> \n> The phrases \"number for\" and \"value for\" seem unnecessary in the error \n> messages.\n> Also, \"positive number\" should be \"a positive number.\" Would it be\n> better to display\n> the actual specified value in the error message, like:\n> errmsg(\"REJECT_LIMIT (%s) must\n> be a positive number\", value)?\n\nAgreed.\n\n> Lastly, during my testing, if nothing is specified for REJECT_LIMIT\n> (e.g., COPY ... WITH (..., REJECT_LIMIT)), the COPY command caused a\n> segmentation fault.\n\nOh, thanks for finding it. Fixed.\n> \n> \n>>> I'd like to hear if anyone has an opinion on the need for supporting \n>>> ratio.\n>> \n>> Since there was no opinion about it, attached a patch only for \n>> REJECT_LIMIT specifying number.\n> \n> +1\n> \n>> As there are no opposing opinions, removed 'INFINITY' as well.\n> \n> +1\n> \n> Regards,\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation",
"msg_date": "Thu, 26 Sep 2024 22:38:18 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "+/*\n+ * Extract REJECT_LIMIT value from a DefElem.\n+ */\n+static int64\n+defGetCopyRejectLimitOptions(DefElem *def)\n+{\n+ int64 reject_limit;\n+\n+ if (def->arg == NULL)\n+ ereport(ERROR,\n+ (errcode(ERRCODE_SYNTAX_ERROR),\n+ errmsg(\"REJECT_LIMIT requires a positive integer\")));\n+\n+ if (nodeTag(def->arg) == T_Integer)\n+ {\n+ reject_limit = defGetInt64(def);\n+ if (reject_limit <= 0)\n+ ereport(ERROR,\n+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n+ errmsg(\"REJECT_LIMIT (%lld) must be greater than zero\",\n+ (long long) reject_limit)));\n+ }\n+ else\n+ {\n+ char *sval = defGetString(def);\n+ ereport(ERROR,\n+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n+ errmsg(\"REJECT_LIMIT (%s) must be a positive integer\",\n+ sval)));\n+ }\n+\n+ return reject_limit;\n+}\nthere will be an integer overflow issue?\n\nCan you try the following?\n\nstatic int64\ndefGetCopyRejectLimitOptions(DefElem *def)\n{\n int64 reject_limit;\n reject_limit = defGetInt64(def);\n if (reject_limit <= 0)\n ereport(ERROR,\n (errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n errmsg(\"REJECT_LIMIT (%lld) must be greater than zero\",\n (long long) reject_limit)));\n}\n\n\n\n\nREJECT_LIMIT <replaceable class=\"parameter\">integer</replaceable>\ni think, you want REJECT_LIMIT be bigint?\nso here it should be\nREJECT_LIMIT <replaceable class=\"parameter\">bigint</replaceable>\\\n?\n\n\n",
"msg_date": "Sat, 28 Sep 2024 09:48:00 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
},
{
"msg_contents": "On 2024-09-28 10:48, Jian he wrote:\n\nThanks for your comments!\n\n> +/*\n> + * Extract REJECT_LIMIT value from a DefElem.\n> + */\n> +static int64\n> +defGetCopyRejectLimitOptions(DefElem *def)\n> +{\n> + int64 reject_limit;\n> +\n> + if (def->arg == NULL)\n> + ereport(ERROR,\n> + (errcode(ERRCODE_SYNTAX_ERROR),\n> + errmsg(\"REJECT_LIMIT requires a positive integer\")));\n> +\n> + if (nodeTag(def->arg) == T_Integer)\n> + {\n> + reject_limit = defGetInt64(def);\n> + if (reject_limit <= 0)\n> + ereport(ERROR,\n> + (errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n> + errmsg(\"REJECT_LIMIT (%lld) must be greater than zero\",\n> + (long long) reject_limit)));\n> + }\n> + else\n> + {\n> + char *sval = defGetString(def);\n> + ereport(ERROR,\n> + (errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n> + errmsg(\"REJECT_LIMIT (%s) must be a positive integer\",\n> + sval)));\n> + }\n> +\n> + return reject_limit;\n> +}\n> there will be an integer overflow issue?\n> \n> Can you try the following?\n\nSince defGetInt64() checks not only whether the input value exceeds the \nrange of bigint but also input value is specified, attached v6 patch \nchecks them by directly calling defGetInt64().\n\n> \n> static int64\n> defGetCopyRejectLimitOptions(DefElem *def)\n> {\n> int64 reject_limit;\n> reject_limit = defGetInt64(def);\n> if (reject_limit <= 0)\n> ereport(ERROR,\n> (errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n> errmsg(\"REJECT_LIMIT (%lld) must be greater than zero\",\n> (long long) reject_limit)));\n> }\n> \n> \n> \n> \n> REJECT_LIMIT <replaceable class=\"parameter\">integer</replaceable>\n> i think, you want REJECT_LIMIT be bigint?\n> so here it should be\n> REJECT_LIMIT <replaceable class=\"parameter\">bigint</replaceable>\\\n> ?\n\nHmm, bigint and integer include numbers less than 0, but REJECT_LIMIT \nonly accepts numbers greater than 0. I now feel both may not be \nappropriate.\nReferring to the manual of CREATE SEQUENCE[1], here we may be able to \nuse not only the data types, such as bigint and integer but something \nlike minvalue, maxvalue.\nI'm wondering if we can use the wording maxerror as in the attached \npatch.\n\n\n[1] https://www.postgresql.org/docs/devel/sql-createsequence.html\n\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation",
"msg_date": "Mon, 30 Sep 2024 21:08:47 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": true,
"msg_subject": "Re: Add new COPY option REJECT_LIMIT"
}
] |
[
{
"msg_contents": "Hi hackers,\r\n\r\nI'm not sure if it's the best list for my question but I have a following problem.\r\n\r\nI have an existing DB with lots of data and I need to modify the behavior of one specific\r\nbuilt-in function. I can of course create my own function and redefine the behavior but\r\nnow I need to find every single instance of the old function being used. There is\r\ndependency tracking with pg_depend but it doesn't work for built-in functions.\r\n\r\nI also tried a different approach and tried to create a C-language hook for function\r\ncall but hooks also don't work for built-in functions.\r\n\r\nDo you have some advice for me?\r\n\r\nThanks.\r\n",
"msg_date": "Fri, 26 Jan 2024 10:38:50 +0000",
"msg_from": "Kurlaev Jaroslav <j.kurlaev@cft.ru>",
"msg_from_op": true,
"msg_subject": "Finding every use of a built-in function"
},
{
"msg_contents": "Hi\n\npá 26. 1. 2024 v 11:39 odesílatel Kurlaev Jaroslav <j.kurlaev@cft.ru>\nnapsal:\n\n> Hi hackers,\n>\n> I'm not sure if it's the best list for my question but I have a following\n> problem.\n>\n> I have an existing DB with lots of data and I need to modify the behavior\n> of one specific\n> built-in function. I can of course create my own function and redefine the\n> behavior but\n> now I need to find every single instance of the old function being used.\n> There is\n> dependency tracking with pg_depend but it doesn't work for built-in\n> functions.\n>\n> I also tried a different approach and tried to create a C-language hook\n> for function\n> call but hooks also don't work for built-in functions.\n>\n> Do you have some advice for me?\n>\n\n plpgsq_check can show dependencies\nhttps://github.com/okbob/plpgsql_check#dependency-list\n\nor you can write query SELECT * FROM pg_proc WHERE proname ilike '%name of\nyour function %'\n\nRegards\n\nPavel\n\n\n> Thanks.\n>\n\nHipá 26. 1. 2024 v 11:39 odesílatel Kurlaev Jaroslav <j.kurlaev@cft.ru> napsal:Hi hackers,\n\nI'm not sure if it's the best list for my question but I have a following problem.\n\nI have an existing DB with lots of data and I need to modify the behavior of one specific\nbuilt-in function. I can of course create my own function and redefine the behavior but\nnow I need to find every single instance of the old function being used. There is\ndependency tracking with pg_depend but it doesn't work for built-in functions.\n\nI also tried a different approach and tried to create a C-language hook for function\ncall but hooks also don't work for built-in functions.\n\nDo you have some advice for me? plpgsq_check can show dependencies https://github.com/okbob/plpgsql_check#dependency-listor you can write query SELECT * FROM pg_proc WHERE proname ilike '%name of your function %'RegardsPavel\n\nThanks.",
"msg_date": "Fri, 26 Jan 2024 13:02:12 +0100",
"msg_from": "Pavel Stehule <pavel.stehule@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Finding every use of a built-in function"
},
{
"msg_contents": "> plpgsq_check can show dependencies https://github.com/okbob/plpgsql_check#dependency-list\r\n\r\nThat's not exactly what I was looking for, but it's a useful tool that could help me anyway. Thanks!\r\n",
"msg_date": "Mon, 29 Jan 2024 13:30:41 +0000",
"msg_from": "Kurlaev Jaroslav <j.kurlaev@cft.ru>",
"msg_from_op": true,
"msg_subject": "RE: Finding every use of a built-in function"
}
] |
[
{
"msg_contents": "Hi,\n\nThe option choice of \"ignore\" in the COPY ON_ERROR clause seems overly\ngeneric. There would seem to be two relevant ways to ignore bad column\ninput data - drop the entire row or just set the column value to null. I\ncan see us wanting to provide the set to null option and in any case having\nthe option name be explicit that it ignores the row seems like a good idea.\n\nDavid J.\n\nHi,The option choice of \"ignore\" in the COPY ON_ERROR clause seems overly generic. There would seem to be two relevant ways to ignore bad column input data - drop the entire row or just set the column value to null. I can see us wanting to provide the set to null option and in any case having the option name be explicit that it ignores the row seems like a good idea.David J.",
"msg_date": "Fri, 26 Jan 2024 08:08:29 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": true,
"msg_subject": "Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "On Fri, Jan 26, 2024 at 11:09 PM David G. Johnston\n<david.g.johnston@gmail.com> wrote:\n>\n> Hi,\n>\n> The option choice of \"ignore\" in the COPY ON_ERROR clause seems overly generic. There would seem to be two relevant ways to ignore bad column input data - drop the entire row or just set the column value to null. I can see us wanting to provide the set to null option and in any case having the option name be explicit that it ignores the row seems like a good idea.\n\ntwo issue I found out while playing around with it;\ncreate table x1(a int not null, b int not null );\n\nyou can only do:\nCOPY x1 from stdin (on_error 'null');\nbut you cannot do\nCOPY x1 from stdin (on_error null);\nwe need to hack the gram.y to escape the \"null\". I don't know how to\nmake it work.\nrelated post I found:\nhttps://stackoverflow.com/questions/31786611/how-to-escape-flex-keyword\n\nanother issue:\nCOPY x1 from stdin (on_error null);\n\nwhen we already have `not null` top level constraint for table x1.\nDo we need an error immediately?\n\"on_error null\" seems to conflict with `not null` constraint (assume\nrefers to the same column).\nit may fail while doing bulk inserts while on_error is set to null\nbecause of violating a not null constraint.\n\n\n",
"msg_date": "Mon, 29 Jan 2024 07:50:00 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "On Sun, Jan 28, 2024 at 4:51 PM jian he <jian.universality@gmail.com> wrote:\n\n> On Fri, Jan 26, 2024 at 11:09 PM David G. Johnston\n> <david.g.johnston@gmail.com> wrote:\n> >\n> > Hi,\n> >\n> > The option choice of \"ignore\" in the COPY ON_ERROR clause seems overly\n> generic. There would seem to be two relevant ways to ignore bad column\n> input data - drop the entire row or just set the column value to null. I\n> can see us wanting to provide the set to null option and in any case having\n> the option name be explicit that it ignores the row seems like a good idea.\n>\n> two issue I found out while playing around with it;\n> create table x1(a int not null, b int not null );\n>\n> another issue:\n> COPY x1 from stdin (on_error null);\n>\n> when we already have `not null` top level constraint for table x1.\n> Do we need an error immediately?\n> \"on_error null\" seems to conflict with `not null` constraint (assume\n> refers to the same column).\n> it may fail while doing bulk inserts while on_error is set to null\n> because of violating a not null constraint.\n>\n\nYou should not error immediately since whether or not there is a problem is\ntable and data dependent. I would not check for the case of all columns\nbeing defined not null and just let the mismatch happen.\n\nThat said, maybe with this being a string we can accept something like:\n'null, ignore'\n\nAnd so if attempting to place any one null fails, assuming we can make that\na soft error too, we would then ignore the entire row.\n\nDavid J.\n\nOn Sun, Jan 28, 2024 at 4:51 PM jian he <jian.universality@gmail.com> wrote:On Fri, Jan 26, 2024 at 11:09 PM David G. Johnston\n<david.g.johnston@gmail.com> wrote:\n>\n> Hi,\n>\n> The option choice of \"ignore\" in the COPY ON_ERROR clause seems overly generic. There would seem to be two relevant ways to ignore bad column input data - drop the entire row or just set the column value to null. I can see us wanting to provide the set to null option and in any case having the option name be explicit that it ignores the row seems like a good idea.\n\ntwo issue I found out while playing around with it;\ncreate table x1(a int not null, b int not null );\nanother issue:\nCOPY x1 from stdin (on_error null);\n\nwhen we already have `not null` top level constraint for table x1.\nDo we need an error immediately?\n\"on_error null\" seems to conflict with `not null` constraint (assume\nrefers to the same column).\nit may fail while doing bulk inserts while on_error is set to null\nbecause of violating a not null constraint.You should not error immediately since whether or not there is a problem is table and data dependent. I would not check for the case of all columns being defined not null and just let the mismatch happen.That said, maybe with this being a string we can accept something like: 'null, ignore'And so if attempting to place any one null fails, assuming we can make that a soft error too, we would then ignore the entire row.David J.",
"msg_date": "Sun, 28 Jan 2024 17:19:47 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "On Fri, 26 Jan 2024 08:08:29 -0700\n\"David G. Johnston\" <david.g.johnston@gmail.com> wrote:\n\n> Hi,\n> \n> The option choice of \"ignore\" in the COPY ON_ERROR clause seems overly\n> generic. There would seem to be two relevant ways to ignore bad column\n> input data - drop the entire row or just set the column value to null. I\n> can see us wanting to provide the set to null option and in any case having\n> the option name be explicit that it ignores the row seems like a good idea.\n\nI am not in favour of renaming the option name \"ignore\", instead we can\nuse another style of name for the option to set the column value to NULL,\nfor example, \"set_to_null\".\n\n(Maybe, we can make a more generic option \"set_to (col, val)\" that can set\nthe value of column specified by \"col\" value to the specified value \"val\" \n(e.g. 'N/A') on a soft error, although the syntax would be a bit complex...) \n\nIMO, it is more simple to define \"ignore\" as to skip the entire row rather\nthan having variety of \"ignore\". Once defined it so, the option to set the\ncolumn value to NULL should not be called \"ignore\" because values in other\ncolumns will be inserted.\n\nRegards,\nYugo Nagata\n\n> \n> David J.\n\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>\n\n\n",
"msg_date": "Mon, 29 Jan 2024 17:28:58 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "The idea of on_error is to tolerate errors, I think.\nif a column has a not null constraint, let it cannot be used with\n(on_error 'null')\n\nBased on this, I've made a patch.\nbased on COPY Synopsis: ON_ERROR 'error_action'\non_error 'null', the keyword NULL should be single quoted.\n\ndemo:\nCOPY check_ign_err FROM STDIN WITH (on_error 'null');\n1 {1} a\n2 {2} 1\n3 {3} 2\n4 {4} b\na {5} c\n\\.\n\n\\pset null NULL\n\nSELECT * FROM check_ign_err;\n n | m | k\n------+-----+------\n 1 | {1} | NULL\n 2 | {2} | 1\n 3 | {3} | 2\n 4 | {4} | NULL\n NULL | {5} | NULL",
"msg_date": "Sat, 3 Feb 2024 14:22:08 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "Hi,\n\nOn 2024-02-03 15:22, jian he wrote:\n> The idea of on_error is to tolerate errors, I think.\n> if a column has a not null constraint, let it cannot be used with\n> (on_error 'null')\n\n> + /*\n> + * we can specify on_error 'null', but it can only apply to \n> columns\n> + * don't have not null constraint.\n> + */\n> + if (att->attnotnull && cstate->opts.on_error == \n> COPY_ON_ERROR_NULL)\n> + ereport(ERROR,\n> + (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),\n> + errmsg(\"copy on_error 'null' cannot be used with \n> not null constraint column\")));\n\nThis means we cannot use ON_ERROR 'null' even when there is one column \nwhich have NOT NULL constraint, i.e. primary key, right?\nIMHO this is strong constraint and will decrease the opportunity to use \nthis feature.\n\nIt might be better to allow error_action 'null' for tables which have \nNOT NULL constraint columns, and when facing soft errors for those rows, \nskip that row or stop COPY.\n\n> Based on this, I've made a patch.\n> based on COPY Synopsis: ON_ERROR 'error_action'\n> on_error 'null', the keyword NULL should be single quoted.\n\nAs you mentioned, single quotation seems a little odd..\n\nI'm not sure what is the best name and syntax for this feature, but \nsince current error_action are verbs('stop' and 'ignore'), I feel 'null' \nmight not be appropriate.\n\n> demo:\n> COPY check_ign_err FROM STDIN WITH (on_error 'null');\n> 1 {1} a\n> 2 {2} 1\n> 3 {3} 2\n> 4 {4} b\n> a {5} c\n> \\.\n> \n> \\pset null NULL\n> \n> SELECT * FROM check_ign_err;\n> n | m | k\n> ------+-----+------\n> 1 | {1} | NULL\n> 2 | {2} | 1\n> 3 | {3} | 2\n> 4 | {4} | NULL\n> NULL | {5} | NULL\n\nSince we notice the number of ignored rows when ON_ERROR is 'ignore', \nusers may want to know the number of rows which was changed to NULL when \nusing ON_ERROR 'null'.\n\n-- \nRegards,\n\n--\nAtsushi Torikoshi\nNTT DATA Group Corporation\n\n\n",
"msg_date": "Mon, 05 Feb 2024 11:28:59 +0900",
"msg_from": "torikoshia <torikoshia@oss.nttdata.com>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "On Mon, Feb 5, 2024 at 10:29 AM torikoshia <torikoshia@oss.nttdata.com> wrote:\n>\n> Hi,\n>\n> On 2024-02-03 15:22, jian he wrote:\n> > The idea of on_error is to tolerate errors, I think.\n> > if a column has a not null constraint, let it cannot be used with\n> > (on_error 'null')\n>\n> > + /*\n> > + * we can specify on_error 'null', but it can only apply to\n> > columns\n> > + * don't have not null constraint.\n> > + */\n> > + if (att->attnotnull && cstate->opts.on_error ==\n> > COPY_ON_ERROR_NULL)\n> > + ereport(ERROR,\n> > + (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),\n> > + errmsg(\"copy on_error 'null' cannot be used with\n> > not null constraint column\")));\n>\n> This means we cannot use ON_ERROR 'null' even when there is one column\n> which have NOT NULL constraint, i.e. primary key, right?\n> IMHO this is strong constraint and will decrease the opportunity to use\n> this feature.\n\nI don't want to fail in the middle of bulk inserts,\nso I thought immediately erroring out would be a great idea.\nLet's see what other people think.\n\n\n",
"msg_date": "Mon, 5 Feb 2024 14:26:46 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "On Mon, 05 Feb 2024 11:28:59 +0900\ntorikoshia <torikoshia@oss.nttdata.com> wrote:\n\n> > Based on this, I've made a patch.\n> > based on COPY Synopsis: ON_ERROR 'error_action'\n> > on_error 'null', the keyword NULL should be single quoted.\n> \n> As you mentioned, single quotation seems a little odd..\n> \n> I'm not sure what is the best name and syntax for this feature, but \n> since current error_action are verbs('stop' and 'ignore'), I feel 'null' \n> might not be appropriate.\n\nI am not in favour of using 'null' either, so I suggested to use\n\"set_to_null\" or more generic syntax like \"set_to (col, val)\" in my\nprevious post[1], although I'm not convinced what is the best either.\n\n[1] https://www.postgresql.org/message-id/20240129172858.ccb6c77c3be95a295e2b2b44%40sraoss.co.jp\n\nRegards,\nYugo Nagata\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>\n\n\n",
"msg_date": "Mon, 5 Feb 2024 17:22:56 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "At Mon, 5 Feb 2024 17:22:56 +0900, Yugo NAGATA <nagata@sraoss.co.jp> wrote in \n> On Mon, 05 Feb 2024 11:28:59 +0900\n> torikoshia <torikoshia@oss.nttdata.com> wrote:\n> \n> > > Based on this, I've made a patch.\n> > > based on COPY Synopsis: ON_ERROR 'error_action'\n> > > on_error 'null', the keyword NULL should be single quoted.\n> > \n> > As you mentioned, single quotation seems a little odd..\n> > \n> > I'm not sure what is the best name and syntax for this feature, but \n> > since current error_action are verbs('stop' and 'ignore'), I feel 'null' \n> > might not be appropriate.\n> \n> I am not in favour of using 'null' either, so I suggested to use\n> \"set_to_null\" or more generic syntax like \"set_to (col, val)\" in my\n> previous post[1], although I'm not convinced what is the best either.\n> \n> [1] https://www.postgresql.org/message-id/20240129172858.ccb6c77c3be95a295e2b2b44%40sraoss.co.jp\n\nTom sugggested using a separate option, and I agree with the\nsuggestion. Taking this into consideration, I imagined something like\nthe following, for example. Although I'm not sure we are actually\ngoing to do whole-tuple replacement, the action name in this example\nhas the suffix '-column'.\n\nCOPY (on_error 'replace-colomn', replacement 'null') ..\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n",
"msg_date": "Tue, 06 Feb 2024 09:39:09 +0900 (JST)",
"msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "On Tue, 06 Feb 2024 09:39:09 +0900 (JST)\nKyotaro Horiguchi <horikyota.ntt@gmail.com> wrote:\n\n> At Mon, 5 Feb 2024 17:22:56 +0900, Yugo NAGATA <nagata@sraoss.co.jp> wrote in \n> > On Mon, 05 Feb 2024 11:28:59 +0900\n> > torikoshia <torikoshia@oss.nttdata.com> wrote:\n> > \n> > > > Based on this, I've made a patch.\n> > > > based on COPY Synopsis: ON_ERROR 'error_action'\n> > > > on_error 'null', the keyword NULL should be single quoted.\n> > > \n> > > As you mentioned, single quotation seems a little odd..\n> > > \n> > > I'm not sure what is the best name and syntax for this feature, but \n> > > since current error_action are verbs('stop' and 'ignore'), I feel 'null' \n> > > might not be appropriate.\n> > \n> > I am not in favour of using 'null' either, so I suggested to use\n> > \"set_to_null\" or more generic syntax like \"set_to (col, val)\" in my\n> > previous post[1], although I'm not convinced what is the best either.\n> > \n> > [1] https://www.postgresql.org/message-id/20240129172858.ccb6c77c3be95a295e2b2b44%40sraoss.co.jp\n> \n> Tom sugggested using a separate option, and I agree with the\n> suggestion. Taking this into consideration, I imagined something like\n> the following, for example. Although I'm not sure we are actually\n> going to do whole-tuple replacement, the action name in this example\n> has the suffix '-column'.\n> \n> COPY (on_error 'replace-colomn', replacement 'null') ..\n\nThank you for your information. I've found a post[1] you mentioned, \nwhere adding a separate option for error log destination was suggested. \n\nConsidering consistency with other options, adding a separate option\nwould be better if we want to specify a value to replace the invalid\nvalue, without introducing a complex syntax that allows options with\nmore than one parameters. Maybe, if we allow to use values for the\nreplacement other than NULL, we have to also add a option to specify\na column (or a type) for each replacement value. Or, we may add a\noption to specify a list of replacement values as many as the number of\ncolumns, each of whose default is NULL.\n\nAnyway, I prefer 'replace\" (or 'set_to') to just 'null' as the option\nvalue.\n\n[1] https://www.postgresql.org/message-id/2070915.1705527477%40sss.pgh.pa.us\n\nRegards,\nYugo Nagata\n\n\n> regards.\n> \n> -- \n> Kyotaro Horiguchi\n> NTT Open Source Software Center\n\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>\n\n\n",
"msg_date": "Tue, 6 Feb 2024 16:46:41 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "On Tue, Feb 6, 2024 at 3:46 PM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n>\n> On Tue, 06 Feb 2024 09:39:09 +0900 (JST)\n> Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote:\n>\n> > At Mon, 5 Feb 2024 17:22:56 +0900, Yugo NAGATA <nagata@sraoss.co.jp> wrote in\n> > > On Mon, 05 Feb 2024 11:28:59 +0900\n> > > torikoshia <torikoshia@oss.nttdata.com> wrote:\n> > >\n> > > > > Based on this, I've made a patch.\n> > > > > based on COPY Synopsis: ON_ERROR 'error_action'\n> > > > > on_error 'null', the keyword NULL should be single quoted.\n> > > >\n> > > > As you mentioned, single quotation seems a little odd..\n> > > >\n> > > > I'm not sure what is the best name and syntax for this feature, but\n> > > > since current error_action are verbs('stop' and 'ignore'), I feel 'null'\n> > > > might not be appropriate.\n> > >\n> > > I am not in favour of using 'null' either, so I suggested to use\n> > > \"set_to_null\" or more generic syntax like \"set_to (col, val)\" in my\n> > > previous post[1], although I'm not convinced what is the best either.\n> > >\n> > > [1] https://www.postgresql.org/message-id/20240129172858.ccb6c77c3be95a295e2b2b44%40sraoss.co.jp\n> >\n> > Tom sugggested using a separate option, and I agree with the\n> > suggestion. Taking this into consideration, I imagined something like\n> > the following, for example. Although I'm not sure we are actually\n> > going to do whole-tuple replacement, the action name in this example\n> > has the suffix '-column'.\n> >\n> > COPY (on_error 'replace-colomn', replacement 'null') ..\n>\n> Thank you for your information. I've found a post[1] you mentioned,\n> where adding a separate option for error log destination was suggested.\n>\n> Considering consistency with other options, adding a separate option\n> would be better if we want to specify a value to replace the invalid\n> value, without introducing a complex syntax that allows options with\n> more than one parameters. Maybe, if we allow to use values for the\n> replacement other than NULL, we have to also add a option to specify\n> a column (or a type) for each replacement value. Or, we may add a\n> option to specify a list of replacement values as many as the number of\n> columns, each of whose default is NULL.\n>\n> Anyway, I prefer 'replace\" (or 'set_to') to just 'null' as the option\n> value.\n>\n\nLet's say tabe t column (a,b,c)\nif we support set_to_null(a,b), what should we do if column c has an error.\nshould we ignore this row or error out immediately?\nalso I am not sure it's doable to just extract columnList from the\nfunction defGetCopyOnErrorChoice.\n\nto make `COPY x from stdin (on_error set_to_null(a,b);` work,\nwe may need to refactor to gram.y, in a similar way we do force null\n\ni am ok with\nCOPY x from stdin (on_error set_to_null);\n\n\n",
"msg_date": "Tue, 6 Feb 2024 16:38:31 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "On Mon, 5 Feb 2024 14:26:46 +0800\njian he <jian.universality@gmail.com> wrote:\n\n> On Mon, Feb 5, 2024 at 10:29 AM torikoshia <torikoshia@oss.nttdata.com> wrote:\n> >\n> > Hi,\n> >\n> > On 2024-02-03 15:22, jian he wrote:\n> > > The idea of on_error is to tolerate errors, I think.\n> > > if a column has a not null constraint, let it cannot be used with\n> > > (on_error 'null')\n> >\n> > > + /*\n> > > + * we can specify on_error 'null', but it can only apply to\n> > > columns\n> > > + * don't have not null constraint.\n> > > + */\n> > > + if (att->attnotnull && cstate->opts.on_error ==\n> > > COPY_ON_ERROR_NULL)\n> > > + ereport(ERROR,\n> > > + (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),\n> > > + errmsg(\"copy on_error 'null' cannot be used with\n> > > not null constraint column\")));\n> >\n> > This means we cannot use ON_ERROR 'null' even when there is one column\n> > which have NOT NULL constraint, i.e. primary key, right?\n> > IMHO this is strong constraint and will decrease the opportunity to use\n> > this feature.\n> \n> I don't want to fail in the middle of bulk inserts,\n> so I thought immediately erroring out would be a great idea.\n> Let's see what other people think.\n\nI also think this restriction is too strong because it is very\ncommon that a table has a primary key, unless there is some way\nto specify columns that can be set to NULL. Even when ON_ERROR\nis specified, any constraint violation errors cannot be generally\nignored, so we cannot elimiate the posibility COPY FROM fails in\nthe middle due to invalid data, anyway.\n\nRegards,\nYugo Nagata\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>\n\n\n",
"msg_date": "Tue, 6 Feb 2024 19:19:37 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "attached v2.\nsyntax: `on_error set_to_null`\nbased on upthread discussion, now if you specified `on_error\nset_to_null` and your column has `not\nnull` constraint, we convert the error field to null, so it may error\nwhile bulk inserting for violating NOT NULL constraint.",
"msg_date": "Mon, 12 Feb 2024 08:00:00 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "Hi!\n\nOn 12.02.24 01:00, jian he wrote:\n> attached v2.\n> syntax: `on_error set_to_null`\n> based on upthread discussion, now if you specified `on_error\n> set_to_null` and your column has `not\n> null` constraint, we convert the error field to null, so it may error\n> while bulk inserting for violating NOT NULL constraint.\nThat's a very nice feature. Thanks for implementing it!\n\nv2 applies cleanly and works as described.\n\n\\pset null '(NULL)'\n\nCREATE TEMPORARY TABLE t1 (a int, b int);\nCOPY t1 (a,b) FROM STDIN;\n1 a\n2 1\n3 2\n4 b\na c\n\\.\nSELECT * FROM t1;\n\nCONTEXT: COPY t1, line 1, column b: \"a\"\n a | b\n---+---\n(0 rows)\n\n\nCREATE TEMPORARY TABLE t2 (a int, b int);\nCOPY t2 (a,b) FROM STDIN WITH (on_error set_to_null);\n1 a\n2 1\n3 2\n4 b\na c\n\\.\nSELECT * FROM t2;\n\npsql:test-copy-on_error-2.sql:12: NOTICE: some columns of 3 rows, value\nwere converted to NULL due to data type incompatibility\nCOPY 5\n a | b \n--------+--------\n 1 | (NULL)\n 2 | 1\n 3 | 2\n 4 | (NULL)\n (NULL) | (NULL)\n(5 rows)\n\n\nI have one question though:\n\nIn case all columns of a record have been set to null due to data type\nincompatibility, should we insert it at all? See t2 example above.\nI'm not sure if these records would be of any use in the table. What do\nyou think?\n\nSince the parameter is already called \"set_to_null\", maybe it is not\nnecessary to mention in the NOTICE message that the values have been set\nto null.\nPerhaps something like \"XX records were only partially copied due to\ndata type incompatibility\"\n\n\n-- \nJim\n\n\n\n",
"msg_date": "Fri, 16 Feb 2024 21:16:53 +0100",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "On Fri, Feb 16, 2024 at 1:16 PM Jim Jones <jim.jones@uni-muenster.de> wrote:\n\n> In case all columns of a record have been set to null due to data type\n> incompatibility, should we insert it at all?\n\n\nYes. In particular not all columns in the table need be specified in the\ncopy command so while the parsed input data is all nulls the record itself\nmay not be.\n\nThe system should allow the user to exclude rows with incomplete data by\nignoring a not null constraint violation.\n\nIn short we shouldn't judge non-usefulness and instead give tools to the\nuser to decide for themselves.\n\nDavid J.\n\nOn Fri, Feb 16, 2024 at 1:16 PM Jim Jones <jim.jones@uni-muenster.de> wrote:In case all columns of a record have been set to null due to data type\nincompatibility, should we insert it at all?Yes. In particular not all columns in the table need be specified in the copy command so while the parsed input data is all nulls the record itself may not be.The system should allow the user to exclude rows with incomplete data by ignoring a not null constraint violation.In short we shouldn't judge non-usefulness and instead give tools to the user to decide for themselves.David J.",
"msg_date": "Fri, 16 Feb 2024 13:31:25 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "\n\nOn 16.02.24 21:31, David G. Johnston wrote:\n> Yes. In particular not all columns in the table need be specified in\n> the copy command so while the parsed input data is all nulls the\n> record itself may not be.\n\nYeah, you have a point there.\nI guess if users want to avoid it to happen they can rely on NOT NULL\nconstraints.\n\nThanks\n\n-- \nJim\n\n\n\n",
"msg_date": "Sat, 17 Feb 2024 00:05:18 +0100",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "hi all.\npatch updated.\nsimplified the code a lot.\n\nidea is same:\nCOPY t_on_error_null FROM STDIN WITH (on_error set_to_null);\n\nIf the STDIN number of columns is the same as the target table, then\nInputFunctionCallSafe\ncall failure will make that column values be null.\n\n\nIf the STDIN number of columns is not the same as the target table, then error\nERROR: missing data for column \\\"%s\\\"\nERROR: extra data after last expected column\nwhich is status quo.",
"msg_date": "Mon, 26 Aug 2024 08:00:00 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "\nHi there\n\nOn 26.08.24 02:00, jian he wrote:\n> hi all.\n> patch updated.\n> simplified the code a lot.\n>\n> idea is same:\n> COPY t_on_error_null FROM STDIN WITH (on_error set_to_null);\n>\n> If the STDIN number of columns is the same as the target table, then\n> InputFunctionCallSafe\n> call failure will make that column values be null.\n>\n>\n> If the STDIN number of columns is not the same as the target table, then error\n> ERROR: missing data for column \\\"%s\\\"\n> ERROR: extra data after last expected column\n> which is status quo.\n\nI wanted to give it another try, but the patch does not apply ...\n\n$ git apply ~/patches/copy_on_error/v3-0001-on_error-set_to_null.patch -v\nChecking patch doc/src/sgml/ref/copy.sgml...\nChecking patch src/backend/commands/copy.c...\nChecking patch src/backend/commands/copyfrom.c...\nChecking patch src/backend/commands/copyfromparse.c...\nChecking patch src/include/commands/copy.h...\nChecking patch src/test/regress/expected/copy2.out...\nerror: while searching for:\nNOTICE: skipping row due to data type incompatibility at line 8 for\ncolumn k: \"a\"\nCONTEXT: COPY check_ign_err\nNOTICE: 6 rows were skipped due to data type incompatibility\n-- tests for on_error option with log_verbosity and null constraint via\ndomain\nCREATE DOMAIN dcheck_ign_err2 varchar(15) NOT NULL;\nCREATE TABLE check_ign_err2 (n int, m int[], k int, l dcheck_ign_err2);\n\nerror: patch failed: src/test/regress/expected/copy2.out:753\nerror: src/test/regress/expected/copy2.out: patch does not apply\nChecking patch src/test/regress/sql/copy2.sql...\n\n\n-- \nJim\n\n\n\n",
"msg_date": "Mon, 9 Sep 2024 16:33:59 +0200",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "On Mon, Sep 9, 2024 at 10:34 PM Jim Jones <jim.jones@uni-muenster.de> wrote:\n>\n>\n> Hi there\n>\n> On 26.08.24 02:00, jian he wrote:\n> > hi all.\n> > patch updated.\n> > simplified the code a lot.\n> >\n> > idea is same:\n> > COPY t_on_error_null FROM STDIN WITH (on_error set_to_null);\n> >\n> > If the STDIN number of columns is the same as the target table, then\n> > InputFunctionCallSafe\n> > call failure will make that column values be null.\n> >\n> >\n> > If the STDIN number of columns is not the same as the target table, then error\n> > ERROR: missing data for column \\\"%s\\\"\n> > ERROR: extra data after last expected column\n> > which is status quo.\n>\n> I wanted to give it another try, but the patch does not apply ...\n>\n\nhere we are.\nplease check the attached file.",
"msg_date": "Thu, 12 Sep 2024 18:13:00 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
},
{
"msg_contents": "\n\nOn 12.09.24 12:13, jian he wrote:\n> please check the attached file.\n\nv4 applies cleanly, it works as expected, and all tests pass.\n\npostgres=# \\pset null '(NULL)'\nNull display is \"(NULL)\".\n\npostgres=# CREATE TEMPORARY TABLE t2 (a int, b int);\nCREATE TABLE\n\npostgres=# COPY t2 (a,b) FROM STDIN WITH (on_error set_to_null, format csv);\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>> 1,a\n>> 2,1\n>> 3,2\n>> 4,b\n>> a,c\n>> \\.\nCOPY 5\n\npostgres=# SELECT * FROM t2;\n a | b \n--------+--------\n 1 | (NULL)\n 2 | 1\n 3 | 2\n 4 | (NULL)\n (NULL) | (NULL)\n(5 rows)\n\n\nPerhaps small changes in the docs:\n\n<literal>set_to_null</literal> means the input value will set to\n<literal>null</literal> and continue with the next one.\n\n\"will set\" -> \"will be set\"\n\"and continue with\" -> \"and will continue with\"\n\nOther than that, LGTM.\n\nThanks!\n\n-- \nJim\n\n\n\n",
"msg_date": "Mon, 16 Sep 2024 12:38:15 +0200",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Change COPY ... ON_ERROR ignore to ON_ERROR ignore_row"
}
] |
[
{
"msg_contents": "Hello hackers,\n\nCurrently a function definition must include its body inline. Because of\nthis, when storing function definitions in files, linters and syntax\nhighlighters for non-SQL languages (python, perl, tcl, etc) won't work. An\nexample can be seen on:\n\nhttps://github.com/postgres/postgres/blob/5eafacd2797dc0b04a0bde25fbf26bf79903e7c2/src/pl/plpython/sql/plpython_test.sql#L15-L24\n\nTo solve the above issue, this patch adds a psql command to create a\nfunction and obtain its body from another file. It is used as:\n\n\\create_function from ./data/max.py max(int,int) returns int LANGUAGE\nplpython3u\n\nIts design is similar to the `\\copy` command, which is a frontend version\nof the COPY statement.\n\nThis patch is at an initial stage but includes tests with plpython3u,\npltcl, plperl and tab completion.\n\nAny feedback is welcomed.\n\nBest regards,\nSteve Chavez",
"msg_date": "Fri, 26 Jan 2024 13:41:05 -0500",
"msg_from": "Steve Chavez <steve@supabase.io>",
"msg_from_op": true,
"msg_subject": "psql: add \\create_function command"
},
{
"msg_contents": "Hi\n\npá 26. 1. 2024 v 19:41 odesílatel Steve Chavez <steve@supabase.io> napsal:\n\n> Hello hackers,\n>\n> Currently a function definition must include its body inline. Because of\n> this, when storing function definitions in files, linters and syntax\n> highlighters for non-SQL languages (python, perl, tcl, etc) won't work. An\n> example can be seen on:\n>\n>\n> https://github.com/postgres/postgres/blob/5eafacd2797dc0b04a0bde25fbf26bf79903e7c2/src/pl/plpython/sql/plpython_test.sql#L15-L24\n>\n> To solve the above issue, this patch adds a psql command to create a\n> function and obtain its body from another file. It is used as:\n>\n> \\create_function from ./data/max.py max(int,int) returns int LANGUAGE\n> plpython3u\n>\n> Its design is similar to the `\\copy` command, which is a frontend version\n> of the COPY statement.\n>\n> This patch is at an initial stage but includes tests with plpython3u,\n> pltcl, plperl and tab completion.\n>\n> Any feedback is welcomed.\n>\n\nlooks a little bit obscure - why do you need to do it from psql? And how\nfrequently do you do it?\n\nI think so this is fix on wrong place - you should to fix linters, not psql\n- more without header you cannot do correct linting\n\nRegards\n\nPavel\n\n\n\n>\n> Best regards,\n> Steve Chavez\n>\n\nHipá 26. 1. 2024 v 19:41 odesílatel Steve Chavez <steve@supabase.io> napsal:Hello hackers,Currently a function definition must include its body inline. Because of this, when storing function definitions in files, linters and syntax highlighters for non-SQL languages (python, perl, tcl, etc) won't work. An example can be seen on:https://github.com/postgres/postgres/blob/5eafacd2797dc0b04a0bde25fbf26bf79903e7c2/src/pl/plpython/sql/plpython_test.sql#L15-L24To solve the above issue, this patch adds a psql command to create a function and obtain its body from another file. It is used as:\\create_function from ./data/max.py max(int,int) returns int LANGUAGE plpython3uIts design is similar to the `\\copy` command, which is a frontend version of the COPY statement.This patch is at an initial stage but includes tests with plpython3u, pltcl, plperl and tab completion.Any feedback is welcomed.looks a little bit obscure - why do you need to do it from psql? And how frequently do you do it? I think so this is fix on wrong place - you should to fix linters, not psql - more without header you cannot do correct linting RegardsPavel Best regards,Steve Chavez",
"msg_date": "Fri, 26 Jan 2024 19:51:48 +0100",
"msg_from": "Pavel Stehule <pavel.stehule@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "Pavel Stehule <pavel.stehule@gmail.com> writes:\n> pá 26. 1. 2024 v 19:41 odesílatel Steve Chavez <steve@supabase.io> napsal:\n>> To solve the above issue, this patch adds a psql command to create a\n>> function and obtain its body from another file. It is used as:\n>> \\create_function from ./data/max.py max(int,int) returns int LANGUAGE\n>> plpython3u\n\n> looks a little bit obscure - why do you need to do it from psql? And how\n> frequently do you do it?\n> I think so this is fix on wrong place - you should to fix linters, not psql\n> - more without header you cannot do correct linting\n\nIt feels wrong to me too. I'm not sure where is a better place to\nimplement something like this though. We can't support it server-side\nbecause of permissions issues, so if there's to be any merging of\nfiles it has to happen on the client side.\n\nIt strikes me though that thinking about this in terms of CREATE\nFUNCTION is thinking too small. ISTM that the requirement of\n\"grab the content of a file, quote it as a string literal, and\nembed it into a SQL command\" exists elsewhere. For one thing\nthere's CREATE PROCEDURE, but I've needed this occasionally\njust as a way of feeding data into SELECT, INSERT, etc.\n\nNow, you can do it today:\n\n\\set fbody `cat source_file.txt`\nCREATE FUNCTION foo() RETURNS whatever AS :'fbody' LANGUAGE ...;\n\nand maybe we should say that that's sufficient. It's a bit\nklugy though. One level of improvement could be to get rid\nof the dependency on \"cat\" by inventing a backslash command\nto read a file into a variable:\n\n\\file_read fbody source_file.txt\nCREATE FUNCTION foo() RETURNS whatever AS :'fbody' LANGUAGE ...;\n\n(\\file_write to go the other way seems potentially useful too.)\n\nOr we could cut out the intermediate variable altogether\nby inventing something that works like :'...' but reads\nfrom a file not a variable. That might be too specialized\nthough, and I'm not sure about good syntax for it either.\nMaybe like\n\nCREATE FUNCTION foo() RETURNS whatever AS :{source_file.txt} LANGUAGE ...;\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Fri, 26 Jan 2024 14:23:29 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "Tom Lane:\n> Or we could cut out the intermediate variable altogether\n> by inventing something that works like :'...' but reads\n> from a file not a variable. That might be too specialized\n> though, and I'm not sure about good syntax for it either.\n> Maybe like\n> \n> CREATE FUNCTION foo() RETURNS whatever AS :{source_file.txt} LANGUAGE ...;\n\nThat would indeed be very useful! I would immediately use this in a lot \nof places.\n\n\n",
"msg_date": "Fri, 26 Jan 2024 20:38:34 +0100",
"msg_from": "walther@technowledgy.de",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "Pavel Stehule:\n> looks a little bit obscure - why do you need to do it from psql? And how \n> frequently do you do it?\n\nI store all my SQL code in git and use \"psql -e\" to \"bundle\" it into an \nextension, which is then deployed to production.\n\nThe code is spread over many files, which include other files via \\ir. \nSometimes you need to include other types of files, though - for example \ncode in other languages as Steve mentioned, but I have also had cases \nfor yaml files, markdown templates, even binary assets which should \nstill be considered \"code\" and not data.\n\nSo anything in that direction would help.\n\n\n",
"msg_date": "Fri, 26 Jan 2024 20:45:16 +0100",
"msg_from": "walther@technowledgy.de",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "On Fri, Jan 26, 2024 at 12:23 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n>\n> \\set fbody `cat source_file.txt`\n> CREATE FUNCTION foo() RETURNS whatever AS :'fbody' LANGUAGE ...;\n>\n> and maybe we should say that that's sufficient.\n\n\nI really don't have a problem, and kinda prefer, using psql variables this\nway but feel much more comfortable not having to invoke a shell.\n\n\n> It's a bit\n> klugy though. One level of improvement could be to get rid\n> of the dependency on \"cat\" by inventing a backslash command\n> to read a file into a variable:\n>\n> \\file_read fbody source_file.txt\n>\n\nThis I would use to reliably read external json text files into a psql\nvariable so that I could use jsonb_to_recordset(:var) on the contents.\n\n\n> (\\file_write to go the other way seems potentially useful too.)\n>\n\nThe nearby discussions regarding trying to produce json into files would\nsupport this claim.\n\n\n> Or we could cut out the intermediate variable altogether\n> by inventing something that works like :'...' but reads\n> from a file not a variable. That might be too specialized\n> though, and I'm not sure about good syntax for it either.\n> Maybe like\n>\n> CREATE FUNCTION foo() RETURNS whatever AS :{source_file.txt} LANGUAGE ...;\n>\n>\nIMO, not enough improvement to be had over letting psql variables act as\nthe intermediary to justify the effort.\n\nDavid J.\n\nOn Fri, Jan 26, 2024 at 12:23 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\\set fbody `cat source_file.txt`\nCREATE FUNCTION foo() RETURNS whatever AS :'fbody' LANGUAGE ...;\n\nand maybe we should say that that's sufficient.I really don't have a problem, and kinda prefer, using psql variables this way but feel much more comfortable not having to invoke a shell. It's a bit\nklugy though. One level of improvement could be to get rid\nof the dependency on \"cat\" by inventing a backslash command\nto read a file into a variable:\n\n\\file_read fbody source_file.txtThis I would use to reliably read external json text files into a psql variable so that I could use jsonb_to_recordset(:var) on the contents.\n(\\file_write to go the other way seems potentially useful too.)The nearby discussions regarding trying to produce json into files would support this claim.\n\nOr we could cut out the intermediate variable altogether\nby inventing something that works like :'...' but reads\nfrom a file not a variable. That might be too specialized\nthough, and I'm not sure about good syntax for it either.\nMaybe like\n\nCREATE FUNCTION foo() RETURNS whatever AS :{source_file.txt} LANGUAGE ...;IMO, not enough improvement to be had over letting psql variables act as the intermediary to justify the effort.David J.",
"msg_date": "Fri, 26 Jan 2024 12:49:29 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "pá 26. 1. 2024 v 20:45 odesílatel <walther@technowledgy.de> napsal:\n\n> Pavel Stehule:\n> > looks a little bit obscure - why do you need to do it from psql? And how\n> > frequently do you do it?\n>\n> I store all my SQL code in git and use \"psql -e\" to \"bundle\" it into an\n> extension, which is then deployed to production.\n>\n\nthis is good way\n\n\n>\n> The code is spread over many files, which include other files via \\ir.\n> Sometimes you need to include other types of files, though - for example\n> code in other languages as Steve mentioned, but I have also had cases\n> for yaml files, markdown templates, even binary assets which should\n> still be considered \"code\" and not data.\n>\n> So anything in that direction would help.\n>\n\nbut why you need to do in psql? - you can prepare content outside and\nexecute just like echo \"CREATE FUNCTION ....\" | psql\n\npá 26. 1. 2024 v 20:45 odesílatel <walther@technowledgy.de> napsal:Pavel Stehule:\n> looks a little bit obscure - why do you need to do it from psql? And how \n> frequently do you do it?\n\nI store all my SQL code in git and use \"psql -e\" to \"bundle\" it into an \nextension, which is then deployed to production.this is good way \n\nThe code is spread over many files, which include other files via \\ir. \nSometimes you need to include other types of files, though - for example \ncode in other languages as Steve mentioned, but I have also had cases \nfor yaml files, markdown templates, even binary assets which should \nstill be considered \"code\" and not data.\n\nSo anything in that direction would help.but why you need to do in psql? - you can prepare content outside and execute just like echo \"CREATE FUNCTION ....\" | psql",
"msg_date": "Fri, 26 Jan 2024 20:50:22 +0100",
"msg_from": "Pavel Stehule <pavel.stehule@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "walther@technowledgy.de writes:\n> Pavel Stehule:\n>> looks a little bit obscure - why do you need to do it from psql? And how \n>> frequently do you do it?\n\n> I store all my SQL code in git and use \"psql -e\" to \"bundle\" it into an \n> extension, which is then deployed to production.\n\n> The code is spread over many files, which include other files via \\ir. \n\nThat reminds me: if we do either \\file_read or :{file}, we should\ndefine relative paths as working like \\ir, that is it's relative\nto the current script's directory when we're reading from a script.\nThis is almost always the behavior you want, and the principal\nfunctional problem with the `cat ...` solution is that it doesn't\nwork that way.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Fri, 26 Jan 2024 14:52:05 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "Pavel Stehule <pavel.stehule@gmail.com> writes:\n> but why you need to do in psql? - you can prepare content outside and\n> execute just like echo \"CREATE FUNCTION ....\" | psql\n\nThe bit that's probably hard if you're trying to do this in a shell\nscript is \"quote this data as a SQL string literal\". psql can get\nthat right even in the face of encoding considerations,\nstandard_conforming_strings, etc. Not sure you can build a\nfully bulletproof solution outside.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Fri, 26 Jan 2024 15:04:55 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "pá 26. 1. 2024 v 21:04 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:\n\n> Pavel Stehule <pavel.stehule@gmail.com> writes:\n> > but why you need to do in psql? - you can prepare content outside and\n> > execute just like echo \"CREATE FUNCTION ....\" | psql\n>\n> The bit that's probably hard if you're trying to do this in a shell\n> script is \"quote this data as a SQL string literal\". psql can get\n> that right even in the face of encoding considerations,\n> standard_conforming_strings, etc. Not sure you can build a\n> fully bulletproof solution outside.\n>\n\nI don't know, maybe I have a problem with the described use case. I cannot\nimagine holding the body and head of PL routines in different places and I\ndon't understand the necessity to join it.\n\nOn second hand, few years ago (if I remember well, I proposed some like\n`:{file}`. I don't remember the syntax. But it was not finished, and then I\nwrote\n\nhttps://github.com/okbob/pgimportdoc\n\nThe possibility for some simple import external data can be nice\n\n\n\n\n> regards, tom lane\n>\n\npá 26. 1. 2024 v 21:04 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:Pavel Stehule <pavel.stehule@gmail.com> writes:\n> but why you need to do in psql? - you can prepare content outside and\n> execute just like echo \"CREATE FUNCTION ....\" | psql\n\nThe bit that's probably hard if you're trying to do this in a shell\nscript is \"quote this data as a SQL string literal\". psql can get\nthat right even in the face of encoding considerations,\nstandard_conforming_strings, etc. Not sure you can build a\nfully bulletproof solution outside.I don't know, maybe I have a problem with the described use case. I cannot imagine holding the body and head of PL routines in different places and I don't understand the necessity to join it.On second hand, few years ago (if I remember well, I proposed some like `:{file}`. I don't remember the syntax. But it was not finished, and then I wrote https://github.com/okbob/pgimportdocThe possibility for some simple import external data can be nice\n\n regards, tom lane",
"msg_date": "Fri, 26 Jan 2024 21:13:39 +0100",
"msg_from": "Pavel Stehule <pavel.stehule@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "Pavel Stehule <pavel.stehule@gmail.com> writes:\n> I don't know, maybe I have a problem with the described use case. I cannot\n> imagine holding the body and head of PL routines in different places and I\n> don't understand the necessity to join it.\n\nIt seems a little weird to me too, and I would vote against accepting\n\\create_function as described because I think too few people would\nwant to use it. However, the idea of an easy way to pull in a file\nand convert it to a SQL literal seems like it has many applications.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Fri, 26 Jan 2024 15:17:46 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "pá 26. 1. 2024 v 21:17 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:\n\n> Pavel Stehule <pavel.stehule@gmail.com> writes:\n> > I don't know, maybe I have a problem with the described use case. I\n> cannot\n> > imagine holding the body and head of PL routines in different places and\n> I\n> > don't understand the necessity to join it.\n>\n> It seems a little weird to me too, and I would vote against accepting\n> \\create_function as described because I think too few people would\n> want to use it. However, the idea of an easy way to pull in a file\n> and convert it to a SQL literal seems like it has many applications.\n>\n\n+1\n\nPavel\n\n\n> regards, tom lane\n>\n\npá 26. 1. 2024 v 21:17 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:Pavel Stehule <pavel.stehule@gmail.com> writes:\n> I don't know, maybe I have a problem with the described use case. I cannot\n> imagine holding the body and head of PL routines in different places and I\n> don't understand the necessity to join it.\n\nIt seems a little weird to me too, and I would vote against accepting\n\\create_function as described because I think too few people would\nwant to use it. However, the idea of an easy way to pull in a file\nand convert it to a SQL literal seems like it has many applications.+1Pavel\n\n regards, tom lane",
"msg_date": "Fri, 26 Jan 2024 21:18:47 +0100",
"msg_from": "Pavel Stehule <pavel.stehule@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "idea: what about custom functions for (each) IDE, which calls psql -c\n\"CREATE FUNCTION ...\" when the user saves the file? (it would easy to\nprototype for emacs...)\n(obviously, this isn't a core feature...)\n\n\nOn Fri, Jan 26, 2024 at 3:19 PM Pavel Stehule <pavel.stehule@gmail.com>\nwrote:\n\n>\n>\n> pá 26. 1. 2024 v 21:17 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:\n>\n>> Pavel Stehule <pavel.stehule@gmail.com> writes:\n>> > I don't know, maybe I have a problem with the described use case. I\n>> cannot\n>> > imagine holding the body and head of PL routines in different places\n>> and I\n>> > don't understand the necessity to join it.\n>>\n>> It seems a little weird to me too, and I would vote against accepting\n>> \\create_function as described because I think too few people would\n>> want to use it. However, the idea of an easy way to pull in a file\n>> and convert it to a SQL literal seems like it has many applications.\n>>\n>\n> +1\n>\n> Pavel\n>\n>\n>> regards, tom lane\n>>\n>\n\nidea: what about custom functions for (each) IDE, which calls psql -c \"CREATE FUNCTION ...\" when the user saves the file? (it would easy to prototype for emacs...)(obviously, this isn't a core feature...)On Fri, Jan 26, 2024 at 3:19 PM Pavel Stehule <pavel.stehule@gmail.com> wrote:pá 26. 1. 2024 v 21:17 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:Pavel Stehule <pavel.stehule@gmail.com> writes:\n> I don't know, maybe I have a problem with the described use case. I cannot\n> imagine holding the body and head of PL routines in different places and I\n> don't understand the necessity to join it.\n\nIt seems a little weird to me too, and I would vote against accepting\n\\create_function as described because I think too few people would\nwant to use it. However, the idea of an easy way to pull in a file\nand convert it to a SQL literal seems like it has many applications.+1Pavel\n\n regards, tom lane",
"msg_date": "Fri, 26 Jan 2024 15:23:43 -0500",
"msg_from": "Adam S <adam.sah@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "\nOn 2024-01-26 Fr 15:17, Tom Lane wrote:\n> Pavel Stehule <pavel.stehule@gmail.com> writes:\n>> I don't know, maybe I have a problem with the described use case. I cannot\n>> imagine holding the body and head of PL routines in different places and I\n>> don't understand the necessity to join it.\n> It seems a little weird to me too, and I would vote against accepting\n> \\create_function as described because I think too few people would\n> want to use it. However, the idea of an easy way to pull in a file\n> and convert it to a SQL literal seems like it has many applications.\n>\n> \t\t\t\n\n\nYes, this proposal is far too narrow and would not cater for many use \ncases I have had in the past.\n\nI like your ideas upthread about \\file_read and :{filename}\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n",
"msg_date": "Mon, 29 Jan 2024 08:42:02 -0500",
"msg_from": "Andrew Dunstan <andrew@dunslane.net>",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "> I like your ideas upthread about \\file_read and :{filename}\n\nGreat ideas! :{filename} looks more convenient to use than \\file_read just\nbecause it's one less command to execute.\n\nHowever, :{?variable_name} is already taken by psql to test whether a\nvariable is defined or not. It might be confusing to use the same syntax.\n\nHow about using the convention of interpreting an identifier as a file path\nif it has an slash on it?\n\nThis is used in the Nix language and from experience it works very well:\nhttps://nix.dev/manual/nix/2.18/language/values#type-path\nIt also makes it very clear that you're using a file path, e.g. :{filename}\nvs :./filename. Examples:\n\nselect jsonb_to_recordset(:./contents.json);\ncreate function foo() returns text AS :/absolute/path/contents.py language\nplpython3u;\n\nAny thoughts?\n\nBest regards,\nSteve Chavez\n\nOn Mon, 29 Jan 2024 at 08:42, Andrew Dunstan <andrew@dunslane.net> wrote:\n\n>\n> On 2024-01-26 Fr 15:17, Tom Lane wrote:\n> > Pavel Stehule <pavel.stehule@gmail.com> writes:\n> >> I don't know, maybe I have a problem with the described use case. I\n> cannot\n> >> imagine holding the body and head of PL routines in different places\n> and I\n> >> don't understand the necessity to join it.\n> > It seems a little weird to me too, and I would vote against accepting\n> > \\create_function as described because I think too few people would\n> > want to use it. However, the idea of an easy way to pull in a file\n> > and convert it to a SQL literal seems like it has many applications.\n> >\n> >\n>\n>\n> Yes, this proposal is far too narrow and would not cater for many use\n> cases I have had in the past.\n>\n> I like your ideas upthread about \\file_read and :{filename}\n>\n>\n> cheers\n>\n>\n> andrew\n>\n> --\n> Andrew Dunstan\n> EDB: https://www.enterprisedb.com\n>\n>\n\n> I like your ideas upthread about \\file_read and :{filename}Great ideas! :{filename} looks more convenient to use than \\file_read just because it's one less command to execute.However, :{?variable_name} is already taken by psql to test whether a variable is defined or not. It might be confusing to use the same syntax. How about using the convention of interpreting an identifier as a file path if it has an slash on it? This is used in the Nix language and from experience it works very well: https://nix.dev/manual/nix/2.18/language/values#type-pathIt also makes it very clear that you're using a file path, e.g. :{filename} vs :./filename. Examples:select jsonb_to_recordset(:./contents.json);create function foo() returns text AS :/absolute/path/contents.py language plpython3u;Any thoughts?Best regards,Steve ChavezOn Mon, 29 Jan 2024 at 08:42, Andrew Dunstan <andrew@dunslane.net> wrote:\nOn 2024-01-26 Fr 15:17, Tom Lane wrote:\n> Pavel Stehule <pavel.stehule@gmail.com> writes:\n>> I don't know, maybe I have a problem with the described use case. I cannot\n>> imagine holding the body and head of PL routines in different places and I\n>> don't understand the necessity to join it.\n> It seems a little weird to me too, and I would vote against accepting\n> \\create_function as described because I think too few people would\n> want to use it. However, the idea of an easy way to pull in a file\n> and convert it to a SQL literal seems like it has many applications.\n>\n> \n\n\nYes, this proposal is far too narrow and would not cater for many use \ncases I have had in the past.\n\nI like your ideas upthread about \\file_read and :{filename}\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com",
"msg_date": "Mon, 29 Jan 2024 11:54:45 -0500",
"msg_from": "Steve Chavez <steve@supabase.io>",
"msg_from_op": true,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "po 29. 1. 2024 v 17:54 odesílatel Steve Chavez <steve@supabase.io> napsal:\n\n> > I like your ideas upthread about \\file_read and :{filename}\n>\n> Great ideas! :{filename} looks more convenient to use than \\file_read just\n> because it's one less command to execute.\n>\n> However, :{?variable_name} is already taken by psql to test whether a\n> variable is defined or not. It might be confusing to use the same syntax.\n>\n> How about using the convention of interpreting an identifier as a file\n> path if it has an slash on it?\n>\n> This is used in the Nix language and from experience it works very well:\n> https://nix.dev/manual/nix/2.18/language/values#type-path\n> It also makes it very clear that you're using a file path, e.g.\n> :{filename} vs :./filename. Examples:\n>\n> select jsonb_to_recordset(:./contents.json);\n> create function foo() returns text AS :/absolute/path/contents.py language\n> plpython3u;\n>\n> Any thoughts?\n>\n\nhas sense\n\nPavel\n\n\n>\n> Best regards,\n> Steve Chavez\n>\n> On Mon, 29 Jan 2024 at 08:42, Andrew Dunstan <andrew@dunslane.net> wrote:\n>\n>>\n>> On 2024-01-26 Fr 15:17, Tom Lane wrote:\n>> > Pavel Stehule <pavel.stehule@gmail.com> writes:\n>> >> I don't know, maybe I have a problem with the described use case. I\n>> cannot\n>> >> imagine holding the body and head of PL routines in different places\n>> and I\n>> >> don't understand the necessity to join it.\n>> > It seems a little weird to me too, and I would vote against accepting\n>> > \\create_function as described because I think too few people would\n>> > want to use it. However, the idea of an easy way to pull in a file\n>> > and convert it to a SQL literal seems like it has many applications.\n>> >\n>> >\n>>\n>>\n>> Yes, this proposal is far too narrow and would not cater for many use\n>> cases I have had in the past.\n>>\n>> I like your ideas upthread about \\file_read and :{filename}\n>>\n>>\n>> cheers\n>>\n>>\n>> andrew\n>>\n>> --\n>> Andrew Dunstan\n>> EDB: https://www.enterprisedb.com\n>>\n>>\n\npo 29. 1. 2024 v 17:54 odesílatel Steve Chavez <steve@supabase.io> napsal:> I like your ideas upthread about \\file_read and :{filename}Great ideas! :{filename} looks more convenient to use than \\file_read just because it's one less command to execute.However, :{?variable_name} is already taken by psql to test whether a variable is defined or not. It might be confusing to use the same syntax. How about using the convention of interpreting an identifier as a file path if it has an slash on it? This is used in the Nix language and from experience it works very well: https://nix.dev/manual/nix/2.18/language/values#type-pathIt also makes it very clear that you're using a file path, e.g. :{filename} vs :./filename. Examples:select jsonb_to_recordset(:./contents.json);create function foo() returns text AS :/absolute/path/contents.py language plpython3u;Any thoughts?has sensePavel Best regards,Steve ChavezOn Mon, 29 Jan 2024 at 08:42, Andrew Dunstan <andrew@dunslane.net> wrote:\nOn 2024-01-26 Fr 15:17, Tom Lane wrote:\n> Pavel Stehule <pavel.stehule@gmail.com> writes:\n>> I don't know, maybe I have a problem with the described use case. I cannot\n>> imagine holding the body and head of PL routines in different places and I\n>> don't understand the necessity to join it.\n> It seems a little weird to me too, and I would vote against accepting\n> \\create_function as described because I think too few people would\n> want to use it. However, the idea of an easy way to pull in a file\n> and convert it to a SQL literal seems like it has many applications.\n>\n> \n\n\nYes, this proposal is far too narrow and would not cater for many use \ncases I have had in the past.\n\nI like your ideas upthread about \\file_read and :{filename}\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com",
"msg_date": "Mon, 29 Jan 2024 18:05:42 +0100",
"msg_from": "Pavel Stehule <pavel.stehule@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "Steve Chavez <steve@supabase.io> writes:\n> However, :{?variable_name} is already taken by psql to test whether a\n> variable is defined or not. It might be confusing to use the same syntax.\n\nHmm. Maybe we could go with :{+...} or the like?\n\n> How about using the convention of interpreting an identifier as a file path\n> if it has an slash on it?\n\nSorry, that is just horrid. foo/bar means division, and \"foo/bar\"\nis simply an identifier per SQL standard, so you can't squeeze that\nin without breaking an ocean of stuff. Plus, there are many use-cases\nwhere there's no reason to put a slash in a relative filename.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Mon, 29 Jan 2024 12:11:48 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "po 29. 1. 2024 v 18:11 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:\n\n> Steve Chavez <steve@supabase.io> writes:\n> > However, :{?variable_name} is already taken by psql to test whether a\n> > variable is defined or not. It might be confusing to use the same syntax.\n>\n> Hmm. Maybe we could go with :{+...} or the like?\n>\n> > How about using the convention of interpreting an identifier as a file\n> path\n> > if it has an slash on it?\n>\n> Sorry, that is just horrid. foo/bar means division, and \"foo/bar\"\n> is simply an identifier per SQL standard, so you can't squeeze that\n> in without breaking an ocean of stuff. Plus, there are many use-cases\n> where there's no reason to put a slash in a relative filename.\n>\n\nsometimes paths starts by $ or .\n\nor maybe :{{ ... }}\n\n\n\n>\n> regards, tom lane\n>\n\npo 29. 1. 2024 v 18:11 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:Steve Chavez <steve@supabase.io> writes:\n> However, :{?variable_name} is already taken by psql to test whether a\n> variable is defined or not. It might be confusing to use the same syntax.\n\nHmm. Maybe we could go with :{+...} or the like?\n\n> How about using the convention of interpreting an identifier as a file path\n> if it has an slash on it?\n\nSorry, that is just horrid. foo/bar means division, and \"foo/bar\"\nis simply an identifier per SQL standard, so you can't squeeze that\nin without breaking an ocean of stuff. Plus, there are many use-cases\nwhere there's no reason to put a slash in a relative filename.sometimes paths starts by $ or .or maybe :{{ ... }} \n\n regards, tom lane",
"msg_date": "Mon, 29 Jan 2024 18:29:12 +0100",
"msg_from": "Pavel Stehule <pavel.stehule@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: psql: add \\create_function command"
},
{
"msg_contents": "> Maybe we could go with :{+...} or the like?\n> or maybe :{{ ... }}\n\nTab completion didn't work for :{?<var>} and I noted that the same problem\nwould arise for :{+ or :{{ (and tab completion would be more important\nhere). So I fixed that on:\n\nhttps://www.postgresql.org/message-id/flat/CAGRrpzZU48F2oV3d8eDLr=4TU9xFH5Jt9ED+qU1+X91gMH68Sw@mail.gmail.com\n\nWould be great to have the above fix reviewed/committed to keep making\nprogress here.\n\nBesides that, since :{ is already sort of a prefix for psql functions, how\nabout having `:{file(<filename>)}`? That would be clearer than :{+ or :{{.\n\nBest regards,\nSteve Chavez\n\nOn Mon, 29 Jan 2024 at 12:29, Pavel Stehule <pavel.stehule@gmail.com> wrote:\n\n>\n>\n> po 29. 1. 2024 v 18:11 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:\n>\n>> Steve Chavez <steve@supabase.io> writes:\n>> > However, :{?variable_name} is already taken by psql to test whether a\n>> > variable is defined or not. It might be confusing to use the same\n>> syntax.\n>>\n>> Hmm. Maybe we could go with :{+...} or the like?\n>>\n>> > How about using the convention of interpreting an identifier as a file\n>> path\n>> > if it has an slash on it?\n>>\n>> Sorry, that is just horrid. foo/bar means division, and \"foo/bar\"\n>> is simply an identifier per SQL standard, so you can't squeeze that\n>> in without breaking an ocean of stuff. Plus, there are many use-cases\n>> where there's no reason to put a slash in a relative filename.\n>>\n>\n> sometimes paths starts by $ or .\n>\n> or maybe :{{ ... }}\n>\n>\n>\n>>\n>> regards, tom lane\n>>\n>\n\n> Maybe we could go with :{+...} or the like?> or maybe :{{ ... }}Tab completion didn't work for :{?<var>} and I noted that the same problem would arise for :{+ or :{{ (and tab completion would be more important here). So I fixed that on:https://www.postgresql.org/message-id/flat/CAGRrpzZU48F2oV3d8eDLr=4TU9xFH5Jt9ED+qU1+X91gMH68Sw@mail.gmail.comWould be great to have the above fix reviewed/committed to keep making progress here.Besides that, since :{ is already sort of a prefix for psql functions, how about having `:{file(<filename>)}`? That would be clearer than :{+ or :{{.Best regards,Steve ChavezOn Mon, 29 Jan 2024 at 12:29, Pavel Stehule <pavel.stehule@gmail.com> wrote:po 29. 1. 2024 v 18:11 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:Steve Chavez <steve@supabase.io> writes:\n> However, :{?variable_name} is already taken by psql to test whether a\n> variable is defined or not. It might be confusing to use the same syntax.\n\nHmm. Maybe we could go with :{+...} or the like?\n\n> How about using the convention of interpreting an identifier as a file path\n> if it has an slash on it?\n\nSorry, that is just horrid. foo/bar means division, and \"foo/bar\"\nis simply an identifier per SQL standard, so you can't squeeze that\nin without breaking an ocean of stuff. Plus, there are many use-cases\nwhere there's no reason to put a slash in a relative filename.sometimes paths starts by $ or .or maybe :{{ ... }} \n\n regards, tom lane",
"msg_date": "Sun, 10 Mar 2024 18:01:21 -0500",
"msg_from": "Steve Chavez <steve@supabase.io>",
"msg_from_op": true,
"msg_subject": "Re: psql: add \\create_function command"
}
] |
[
{
"msg_contents": "Hackers,\n\nI wanted to try to customize the subdirectory for an extension. The docs[1] say:\n\n> directory (string)\n> \n> The directory containing the extension's SQL script file(s). Unless an absolute path is given, the name is relative to the installation's SHAREDIR directory. The default behavior is equivalent to specifying directory = 'extension'.\n\n\n [1]: https://www.postgresql.org/docs/16/extend-extensions.html\n\nBut it doesn’t seem to work. I tried this experiment:\n\n❯ pg_config --version\nPostgreSQL 16.1\n\n❯ git clone git@github.com:theory/kv-pair.git\n❯ cd kv-pair\n❯ echo directory = 'blah' >> pair.control\n❯ cat pair.control\n# pair extension\ncomment = 'A key/value pair data type'\ndefault_version = '0.1.2'\nmodule_pathname = '$libdir/pair'\nrelocatable = true\ndirectory = blah\n\n❯ make install\ncp sql/pair.sql sql/pair--0.1.2.sql\n/opt/homebrew/bin/gmkdir -p '/Users/david/.pgenv/pgsql-16.1/share/extension'\n/opt/homebrew/bin/gmkdir -p '/Users/david/.pgenv/pgsql-16.1/share/extension'\n/opt/homebrew/bin/gmkdir -p '/Users/david/.pgenv/pgsql-16.1/share/doc/extension'\n/opt/homebrew/bin/ginstall -c -m 644 .//pair.control '/Users/david/.pgenv/pgsql-16.1/share/extension/'\n/opt/homebrew/bin/ginstall -c -m 644 .//sql/pair--unpackaged--0.1.2.sql '/Users/david/.pgenv/pgsql-16.1/share/extension/'\n/opt/homebrew/bin/ginstall -c -m 644 .//doc/pair.md '/Users/david/.pgenv/pgsql-16.1/share/doc/extension/‘\n\n❯ find ~/.pgenv/pgsql-16.1/ -name '*pair*.*'\n/Users/david/.pgenv/pgsql-16.1//include/server/lib/pairingheap.h\n/Users/david/.pgenv/pgsql-16.1//share/extension/pair--unpackaged--0.1.2.sql\n/Users/david/.pgenv/pgsql-16.1//share/extension/pair.control\n/Users/david/.pgenv/pgsql-16.1//share/doc/extension/pair.md\n\nI see two problems:\n\n1. pair--0.1.2.sql is not installed. It does install without `directory` set.\n2. pair--unpackaged--0.1.2.sql is installed, but not in a `blah` directory. Shouldn’t it be?\n\nAm I missing something?\n\nBest,\n\nDavid\n\n\n\n",
"msg_date": "Fri, 26 Jan 2024 16:40:29 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Bug: The \"directory\" control parameter does not work"
},
{
"msg_contents": "On Jan 26, 2024, at 4:40 PM, David E. Wheeler <david@justatheory.com> wrote:\n\n> But it doesn’t seem to work. I tried this experiment:\n\nI made a simpler test case here:\n\n https://github.com/theory/test-extension-directory\n\nNot the difference between actual and expected output.\n\nBest,\n\nDavid\n\n\n\n\n",
"msg_date": "Fri, 26 Jan 2024 17:05:42 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Bug: The \"directory\" control parameter does not work"
},
{
"msg_contents": "On Jan 26, 2024, at 5:05 PM, David E. Wheeler <david@justatheory.com> wrote:\n\n> I made a simpler test case here:\n> \n> https://github.com/theory/test-extension-directory\n> \n> Not the difference between actual and expected output.\n\nBah! Need to also set `MODULEDIR = extension/click` and then it works.\n\nD\n\n\n\n",
"msg_date": "Fri, 26 Jan 2024 18:24:28 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Bug: The \"directory\" control parameter does not work"
}
] |
[
{
"msg_contents": "Hi All,\n\nI am trying to use GSSAPI (Kerberos auth) on FreeBSD.\n\nAfter several attempts I was able to build PostgreSQL 16 from FreeBSD ports with GSSAPI support. The steps were:\n1. Uninstall Heimdal\n2. Install krb5 (MIT Kerberos)\n3. Build Pg with GSSAPI support\n\nI configured pg_hba.conf to require GSSAPI authentication for one of the users.\n\nWhen trying to connect using “psql -h postgres” (postgres is the name of the host) I get:\n\npsql: error: connection to server at “postgres.[domainname]” ([ipaddress]), port 5432 failed: connection to server at “postgres.[domainname]” ([ipaddress]), port 5432 failed: server closed the connection unexpectedly\n\tThis probably means the server terminated abnormally\n\tbefore or while processing the request.\n\nConfigured Pg to debug log and here are the relevant syslog entries:\n\n\nan 27 13:33:45 postgres postgres[61605]: [36-1] 2024-01-27 13:33:45.779 CET [61605] DEBUG: forked new backend, pid=61626 socket=10\nJan 27 13:33:45 postgres postgres[61605]: [37-1] 2024-01-27 13:33:45.786 CET [61605] DEBUG: forked new backend, pid=61627 socket=10\nJan 27 13:33:45 postgres postgres[61605]: [38-1] 2024-01-27 13:33:45.786 CET [61605] DEBUG: reaping dead processes\nJan 27 13:33:45 postgres postgres[61605]: [39-1] 2024-01-27 13:33:45.787 CET [61605] DEBUG: server process (PID 61626) was terminated by signal 11: Segmentation fault\nJan 27 13:33:45 postgres postgres[61605]: [40-1] 2024-01-27 13:33:45.787 CET [61605] LOG: server process (PID 61626) was terminated by signal 11: Segmentation fault\nJan 27 13:33:45 postgres postgres[61605]: [41-1] 2024-01-27 13:33:45.787 CET [61605] LOG: terminating any other active server processes\nJan 27 13:33:45 postgres postgres[61605]: [42-1] 2024-01-27 13:33:45.787 CET [61605] DEBUG: sending SIGQUIT to process 61611\nJan 27 13:33:45 postgres postgres[61605]: [43-1] 2024-01-27 13:33:45.787 CET [61605] DEBUG: sending SIGQUIT to process 61627\nJan 27 13:33:45 postgres postgres[61605]: [44-1] 2024-01-27 13:33:45.787 CET [61605] DEBUG: sending SIGQUIT to process 61607\nJan 27 13:33:45 postgres postgres[61605]: [45-1] 2024-01-27 13:33:45.787 CET [61605] DEBUG: sending SIGQUIT to process 61606\nJan 27 13:33:45 postgres postgres[61605]: [46-1] 2024-01-27 13:33:45.787 CET [61605] DEBUG: sending SIGQUIT to process 61609\nJan 27 13:33:45 postgres postgres[61605]: [47-1] 2024-01-27 13:33:45.787 CET [61605] DEBUG: sending SIGQUIT to process 61610\nJan 27 13:33:45 postgres postgres[61605]: [48-1] 2024-01-27 13:33:45.789 CET [61605] DEBUG: reaping dead processes\nJan 27 13:33:45 postgres postgres[61605]: [49-1] 2024-01-27 13:33:45.789 CET [61605] DEBUG: server process (PID 61627) exited with exit code 2\n\n\n\nI am not familiar enough with FreeBSD to be able to gather any crash dumps or backtraces, I am afraid.\n\n--\nMichal\n\n",
"msg_date": "Sat, 27 Jan 2024 13:45:23 +0100",
"msg_from": "=?utf-8?Q?Micha=C5=82_K=C5=82eczek?= <michal@kleczek.org>",
"msg_from_op": true,
"msg_subject": "Segmentation fault on FreeBSD with GSSAPI authentication "
},
{
"msg_contents": "=?utf-8?Q?Micha=C5=82_K=C5=82eczek?= <michal@kleczek.org> writes:\n> I am trying to use GSSAPI (Kerberos auth) on FreeBSD.\n\n> After several attempts I was able to build PostgreSQL 16 from FreeBSD ports with GSSAPI support. The steps were:\n> 1. Uninstall Heimdal\n> 2. Install krb5 (MIT Kerberos)\n> 3. Build Pg with GSSAPI support\n\nWhich FreeBSD version? Which krb5 package version?\nIs this x86_64, or something else?\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Sat, 27 Jan 2024 09:43:01 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Segmentation fault on FreeBSD with GSSAPI authentication"
},
{
"msg_contents": "\n\n> On 27 Jan 2024, at 15:43, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> =?utf-8?Q?Micha=C5=82_K=C5=82eczek?= <michal@kleczek.org> writes:\n>> I am trying to use GSSAPI (Kerberos auth) on FreeBSD.\n> \n>> After several attempts I was able to build PostgreSQL 16 from FreeBSD ports with GSSAPI support. The steps were:\n>> 1. Uninstall Heimdal\n>> 2. Install krb5 (MIT Kerberos)\n>> 3. Build Pg with GSSAPI support\n> \n> Which FreeBSD version? Which krb5 package version?\n> Is this x86_64, or something else?\n\nRight, sorry:\n\n1. X86_64\n2. FreeBSD 13.2 (It is in a TrueNAS Jail if it makes any difference)\n3. krb5-1.21.2\n\n—\nMichal\n\n",
"msg_date": "Sat, 27 Jan 2024 16:20:26 +0100",
"msg_from": "=?utf-8?Q?Micha=C5=82_K=C5=82eczek?= <michal@kleczek.org>",
"msg_from_op": true,
"msg_subject": "Re: Segmentation fault on FreeBSD with GSSAPI authentication"
},
{
"msg_contents": "=?utf-8?Q?Micha=C5=82_K=C5=82eczek?= <michal@kleczek.org> writes:\n> On 27 Jan 2024, at 15:43, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Which FreeBSD version? Which krb5 package version?\n>> Is this x86_64, or something else?\n\n> Right, sorry:\n\n> 1. X86_64\n> 2. FreeBSD 13.2 (It is in a TrueNAS Jail if it makes any difference)\n> 3. krb5-1.21.2\n\nHmm. I made a desultory attempt at replicating this, using\na fully-updated FreeBSD 13.2 image. I can't find anything wrong,\nbut it's not clear to me that I duplicated your configuration.\n\nTo make sure we're on the same page: do the tests in src/test/kerberos\nin our source tree pass on your system? Read the README there for\ncaveats, then do\n\n\tmake check PG_TEST_EXTRA=kerberos\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Sat, 27 Jan 2024 13:29:26 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Segmentation fault on FreeBSD with GSSAPI authentication"
}
] |
[
{
"msg_contents": "Buildfarm member caiman has been failing build for a couple weeks now.\nThe reason turns out to be that recent libxml2 has decided to throw\na \"const\" into the signature required for custom error handlers.\n(API compatibility? What's that?)\n\nI don't mind adopting the \"const\" --- it's a good idea in isolation.\nThe trouble is in fixing our code to work with both old and new\nlibxml2 versions. We could thrash around with a configure test or\nsomething, but I think the most expedient answer is just to insert\nsome explicit casts, as shown in the attached. It's possible though\nthat some compilers will throw a cast-away-const warning. I'm\nnot seeing any, but ...\n\nAlso, I'm seeing a deprecation warning in contrib/xml2/xpath.c\nfor\n\n\txmlLoadExtDtdDefaultValue = 1;\n\nI'm not sure why that's still there, given that we disabled external\nDTD access ages ago. I propose we just remove it.\n\nIn short, I suggest the attached.\n\n\t\t\tregards, tom lane",
"msg_date": "Sat, 27 Jan 2024 14:04:22 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": true,
"msg_subject": "PG versus libxml2 2.12.x"
},
{
"msg_contents": "\nOn 2024-01-27 Sa 14:04, Tom Lane wrote:\n> Buildfarm member caiman has been failing build for a couple weeks now.\n> The reason turns out to be that recent libxml2 has decided to throw\n> a \"const\" into the signature required for custom error handlers.\n> (API compatibility? What's that?)\n>\n> I don't mind adopting the \"const\" --- it's a good idea in isolation.\n> The trouble is in fixing our code to work with both old and new\n> libxml2 versions. We could thrash around with a configure test or\n> something, but I think the most expedient answer is just to insert\n> some explicit casts, as shown in the attached. It's possible though\n> that some compilers will throw a cast-away-const warning. I'm\n> not seeing any, but ...\n>\n> Also, I'm seeing a deprecation warning in contrib/xml2/xpath.c\n> for\n>\n> \txmlLoadExtDtdDefaultValue = 1;\n>\n> I'm not sure why that's still there, given that we disabled external\n> DTD access ages ago. I propose we just remove it.\n>\n> In short, I suggest the attached.\n>\n> \t\t\t\n\n\n\nLooks reasonable.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n",
"msg_date": "Mon, 29 Jan 2024 08:30:04 -0500",
"msg_from": "Andrew Dunstan <andrew@dunslane.net>",
"msg_from_op": false,
"msg_subject": "Re: PG versus libxml2 2.12.x"
},
{
"msg_contents": "On 27.01.24 20:04, Tom Lane wrote:\n> Buildfarm member caiman has been failing build for a couple weeks now.\n> The reason turns out to be that recent libxml2 has decided to throw\n> a \"const\" into the signature required for custom error handlers.\n> (API compatibility? What's that?)\n> \n> I don't mind adopting the \"const\" --- it's a good idea in isolation.\n> The trouble is in fixing our code to work with both old and new\n> libxml2 versions. We could thrash around with a configure test or\n> something, but I think the most expedient answer is just to insert\n> some explicit casts, as shown in the attached. It's possible though\n> that some compilers will throw a cast-away-const warning. I'm\n> not seeing any, but ...\n\nIn PL/Tcl, we used to have these CONST84 and CONST86 things, for similar \nreasons. Maybe that would be another approach.\n\n\n\n",
"msg_date": "Mon, 29 Jan 2024 15:56:12 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": false,
"msg_subject": "Re: PG versus libxml2 2.12.x"
},
{
"msg_contents": "Peter Eisentraut <peter@eisentraut.org> writes:\n> On 27.01.24 20:04, Tom Lane wrote:\n>> I don't mind adopting the \"const\" --- it's a good idea in isolation.\n>> The trouble is in fixing our code to work with both old and new\n>> libxml2 versions. We could thrash around with a configure test or\n>> something, but I think the most expedient answer is just to insert\n>> some explicit casts, as shown in the attached. It's possible though\n>> that some compilers will throw a cast-away-const warning. I'm\n>> not seeing any, but ...\n\n> In PL/Tcl, we used to have these CONST84 and CONST86 things, for similar \n> reasons. Maybe that would be another approach.\n\nYeah, if the simple cast approach turns out to create warnings,\nwe'll have to fall back on using actually different declarations.\nI'm hoping to not have to go there.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Mon, 29 Jan 2024 10:19:47 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": true,
"msg_subject": "Re: PG versus libxml2 2.12.x"
},
{
"msg_contents": "I wrote:\n> Peter Eisentraut <peter@eisentraut.org> writes:\n>> In PL/Tcl, we used to have these CONST84 and CONST86 things, for similar \n>> reasons. Maybe that would be another approach.\n\n> Yeah, if the simple cast approach turns out to create warnings,\n> we'll have to fall back on using actually different declarations.\n> I'm hoping to not have to go there.\n\nActually ... what I really want to avoid is adding a configure test.\nThe alternative to that would be an #if test on LIBXML_VERSION,\nwhich I'd initially not wanted to do ... but I now notice that\nwe already have one of those for a nearby purpose (coping with a\ndifferent change in libxml2's error APIs). So adding another one\nof those doesn't seem so bad after all. I now like the attached\napproach better.\n\n\t\t\tregards, tom lane",
"msg_date": "Mon, 29 Jan 2024 10:59:06 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": true,
"msg_subject": "Re: PG versus libxml2 2.12.x"
}
] |
[
{
"msg_contents": "Hi,\n\nI happened to investigate a query involving a partitioned table, which\nled me to a couple of bottlenecks severely affecting queries dealing\nwith multiple partitions (or relations in general). After a while I came\nup with three WIP patches that improve the behavior by an order of\nmagnitude, and not just in some extreme cases.\n\n\nConsider a partitioned pgbench with 20 partitions, say:\n\n pgbench -i -s 100 --partitions 100 testdb\n\nbut let's modify the pgbench_accounts a little bit:\n\n ALTER TABLE pgbench_accounts ADD COLUMN aid_parent INT;\n UPDATE pgbench_accounts SET aid_parent = aid;\n CREATE INDEX ON pgbench_accounts(aid_parent);\n VACUUM FULL pgbench_accounts;\n\nwhich simply adds \"aid_parent\" column which is not a partition key. And\nnow let's do a query\n\n SELECT * FROM pgbench_accounts pa JOIN pgbench_branches pb\n ON (pa.bid = pb.bid) WHERE pa.aid_parent = :aid\n\nso pretty much the regular \"pgbench -S\" except that on the column that\ndoes not allow partition elimination. Now, the plan looks like this:\n\n QUERY PLAN\n----------------------------------------------------------------------\n Hash Join (cost=1.52..34.41 rows=10 width=465)\n Hash Cond: (pa.bid = pb.bid)\n -> Append (cost=0.29..33.15 rows=10 width=101)\n \t-> Index Scan using pgbench_accounts_1_aid_parent_idx on\npgbench_accounts_1 pa_1 (cost=0.29..3.31 rows=1 width=101)\n \tIndex Cond: (aid_parent = 3489734)\n \t-> Index Scan using pgbench_accounts_2_aid_parent_idx on\npgbench_accounts_2 pa_2 (cost=0.29..3.31 rows=1 width=101)\n \tIndex Cond: (aid_parent = 3489734)\n \t-> Index Scan using pgbench_accounts_3_aid_parent_idx on\npgbench_accounts_3 pa_3 (cost=0.29..3.31 rows=1 width=101)\n \tIndex Cond: (aid_parent = 3489734)\n \t-> Index Scan using pgbench_accounts_4_aid_parent_idx on\npgbench_accounts_4 pa_4 (cost=0.29..3.31 rows=1 width=101)\n \tIndex Cond: (aid_parent = 3489734)\n \t-> ...\n -> Hash (cost=1.10..1.10 rows=10 width=364)\n \t-> Seq Scan on pgbench_branches pb (cost=0.00..1.10 rows=10\nwidth=364)\n\n\nSo yeah, scanning all 100 partitions. Not great, but no partitioning\nscheme is perfect for all queries. Anyway, let's see how this works on a\nbig AMD EPYC machine with 96/192 cores - with \"-M simple\" we get:\n\nparts 1 8 16 32 64 96 160 224\n-----------------------------------------------------------------------\n0 13877 105732 210890 410452 709509 844683 1050658 1163026\n100 653 3957 7120 12022 12707 11813 10349 9633\n1000 20 142 270 474 757 808 567 427\n\nThese are transactions per second, for different number of clients\n(numbers in the header). With -M prepared the story doesn't change - the\nnumbers are higher, but the overall behavior is pretty much the same.\n\nFirstly, with no partitions (first row), the throughput by ~13k/client\ninitially, then it gradually levels off. But it grows all the time.\n\nBut with 100 or 1000 partitions, it peaks and then starts dropping\nagain. And moreover, the throughput with 100 or 1000 partitions is just\na tiny fraction of the non-partitioned value. The difference is roughly\nequal to the number of partitions - for example with 96 clients, the\ndifference between 0 and 1000 partitions is 844683/808 = 1045.\n\nI could demonstrate the same behavior with fewer partitions - e.g. with\n10 partitions you get ~10x difference, and so on.\n\nAnother thing I'd mention is that this is not just about partitioning.\nImagine a star schema with a fact table and dimensions - you'll get the\nsame behavior depending on the number of dimensions you need to join\nwith. With \"-M simple\" you may get this, for example:\n\ndims 1 8 16 32 64 96 160 224\n----------------------------------------------------------------------\n1 11737 92925 183678 361497 636598 768956 958679 1042799\n10 462 3558 7086 13889 25367 29503 25353 24030\n100 4 31 61 122 231 292 292 288\n\nSo, similar story - significant slowdown as we're adding dimensions.\n\n\nNow, what could be causing this? Clearly, there's a bottleneck of some\nkind, and we're hitting it. Some of this may be simply due to execution\ndoing more stuff (more index scans, more initialization, ...) but maybe\nnot - one of the reasons why I started looking into this was not using\nall the CPU even for small scales - the CPU was maybe 60% utilized.\n\nSo I started poking at things. The first thing that I thought about was\nlocking, obviously. That's consistent with the limited CPU utilization\n(waiting on a lock = not running), and it's somewhat expected when using\nmany partitions - we need to lock all of them, and if we have 100 or\n1000 of them, that's potentially lot of locks.\n\n From past experiments I've known about two places where such bottleneck\ncould be - NUM_LOCK_PARTITIONS and fast-path locking. So I decided to\ngive it a try, increase these values and see what happens.\n\nFor NUM_LOCK_PARTITIONS this is pretty simple (see 0001 patch). The\nLWLock table has 16 partitions by default - it's quite possible that on\nmachine with many cores and/or many partitions, we can easily hit this.\nSo I bumped this 4x to 64 partitions.\n\nFor fast-path locking the changes are more complicated (see 0002). We\nallow keeping 16 relation locks right in PGPROC, and only when this gets\nfull we promote them to the actual lock table. But with enough\npartitions we're guaranteed to fill these 16 slots, of course. But\nincreasing the number of slots is not simple - firstly, the information\nis split between an array of 16 OIDs and UINT64 serving as a bitmap.\nIncreasing the size of the OID array is simple, but it's harder for the\nauxiliary bitmap. But there's more problems - with more OIDs a simple\nlinear search won't do. But a simple hash table is not a good idea too,\nbecause of poor locality and the need to delete stuff ...\n\nWhat I ended up doing is having a hash table of 16-element arrays. There\nare 64 \"pieces\", each essentially the (16 x OID + UINT64 bitmap) that we\nhave now. Each OID is mapped to exactly one of these parts as if in a\nhash table, and in each of those 16-element parts we do exactly the same\nthing we do now (linear search, removal, etc.). This works great, the\nlocality is great, etc. The one disadvantage is this makes PGPROC\nlarger, but I did a lot of benchmarks and I haven't seen any regression\nthat I could attribute to this. (More about this later.)\n\nUnfortunately, for the pgbench join this does not make much difference.\nBut for the \"star join\" (with -M prepared) it does this:\n\n 1 8 16 32 64 96 160 224\n------------------------------------------------------------------------\nmaster 21610 137450 247541 300902 270932 229692 191454 189233\npatched 21664 151695 301451 594615 1036424 1211716 1480953 1656203\nspeedup 1.0 1.1 1.2 2.0 3.8 5.3 7.7 8.8\n\nThat's a pretty nice speedup, I think.\n\nHowever, why doesn't the partitioned join improve (at not very much)?\nWell, perf profile says stuff like this:\n\n\n9.16%\t0.77% postgres \t[kernel.kallsyms] \t[k] asm_exc_page_fault\n \t| \t\n \t--8.39%--asm_exc_page_fault\n \t| \t\n \t--7.52%--exc_page_fault\n \t| \t\n \t--7.13%--do_user_addr_fault\n \t| \t\n \t--6.64%--handle_mm_fault\n \t| \t\n \t--6.29%--__handle_mm_fault\n \t| \t\n \t|--2.17%--__mem_cgroup_charge\n \t| \t| \t\n \t| \t|--1.25%--charge_memcg\n \t| \t| \t| \t\n \t| \t| \t--0.57%-- ...\n \t| \t| \t\n \t| \t--0.67%-- ...\n \t| \t\n \t|--2.04%--vma_alloc_folio\n\nAfter investigating this for a bit, I came to the conclusion this may be\nsome sort of a scalability problem in glibc/malloc. I decided to try if\nthe \"memory pool\" patch (which I've mentioned in the memory limit thread\nas an alternative way to introduce backend-level accounting/limit) could\nserve as a backend-level malloc cache, and how would that work. So I\ncleaned up the PoC patch I already had (see 0003), and gave it a try.\n\nAnd with both patches applied, the results for the partitioned join with\n100 partitions look like this:\n\n-M simple\n\n 1 8 16 32 64 96 160 224\n------------------------------------------------------------------------\nmaster 653 3957 7120 12022 12707 11813 10349 9633\nboth patches 954 7356 14580 28259 51552 65278 70607 69598\nspeedup 1.5 1.9 2.0 2.4 4.1 5.5 6.8 7.2\n\n\n-M prepared\n\n 1 8 16 32 64 96 160 224\n------------------------------------------------------------------------\nmaster 1639 8273 14138 14746 13446 14001 11129 10136\nboth patches 4792 30102 62208 122157 220984 267763 315632 323567\nspeedup 2.9 3.6 4.4 8.3 16.4 19.1 28.4 31.9\n\n\nThat's pretty nice, I think. And I've seen many such improvements, it's\nnot a cherry-picked example. For the star join, the improvements are\nvery similar.\n\nI'm attaching PDF files with a table visualizing results for these two\nbenchmarks - there's results for different number of partitions/scales,\nand different builds (master, one or both of the patches). There's also\na comparison to master, with color scale \"red = slower, green = faster\"\n(but there's no red anywhere, not even for low client counts).\n\nIt's also interesting that with just the 0003 patch applied, the change\nis much smaller. It's as if the two bottlenecks (locking and malloc) are\nin balance - if you only address one one, you don't get much. But if you\naddress both, it flies.\n\nFWIW where does the malloc overhead come from? For one, while we do have\nsome caching of malloc-ed memory in memory contexts, that doesn't quite\nwork cross-query, because we destroy the contexts at the end of the\nquery. We attempt to cache the memory contexts too, but in this case\nthat can't help because the allocations come from btbeginscan() where we\ndo this:\n\n so = (BTScanOpaque) palloc(sizeof(BTScanOpaqueData));\n\nand BTScanOpaqueData is ~27kB, which means it's an oversized chunk and\nthus always allocated using a separate malloc() call. Maybe we could\nbreak it into smaller/cacheable parts, but I haven't tried, and I doubt\nit's the only such allocation.\n\nI don't want to get into too much detail about the memory pool, but I\nthink it's something we should consider doing - I'm sure there's stuff\nto improve, but caching the malloc may clearly be very beneficial. The\nbasic idea is to have a cache that is \"adaptive\" (i.e. adjusts to\ncaching blocks of sizes needed by the workload) but also cheap. The\npatch is PoC/WIP and needs more work, but I think it works quite well.\nIf anyone wants to take a look or have a chat at FOSDEM, for example,\nI'm available.\n\nFWIW I was wondering if this is a glibc-specific malloc bottleneck, so I\ntried running the benchmarks with LD_PRELOAD=jemalloc, and that improves\nthe behavior a lot - it gets us maybe ~80% of the mempool benefits.\nWhich is nice, it confirms it's glibc-specific (I wonder if there's a\nway to tweak glibc to address this), and it also means systems using\njemalloc (e.g. FreeBSD, right?) don't have this problem. But it also\nsays the mempool has ~20% benefit on top of jemalloc.\n\nFWIW there's another bottleneck people may not realize, and that's the\nnumber of file descriptors. Once you get to >1000 relations, you can\neasily get into situation like this:\n\n\n54.18%\t0.48% postgres \t[kernel.kallsyms] \t[k]\nentry_SYSCALL_64_after_hwframe\n \t| \t\n \t--53.70%--entry_SYSCALL_64_after_hwframe\n \t| \t\n \t--53.03%--do_syscall_64\n \t| \t\n \t|--28.29%--__x64_sys_openat\n \t| \t| \t\n \t| \t--28.14%--do_sys_openat2\n \t| \t| \t\n \t| \t|--23.14%--do_filp_open\n \t| \t| \t| \t\n \t| \t| \t--22.72%--path_openat\n\n\nThat's pretty bad, it means we're closing/opening file descriptors like\ncrazy, because every query needs the files. If I increase the number of\nfile descriptors (both in ulimit and max_files_per_process) to prevent\nthis trashing, I can increase the throughput ~5x. Of course, this is not\na bottleneck that we can \"fix\" in code, it's simply a consequence of not\nhaving enough file descriptors etc. But I wonder if we might make it\neasier to monitor this, e.g. by tracking the fd cache hit ratio, or\nsomething like that ...\n\n\nThere's a more complete set of benchmarking scripts and results for\nthese and other tests, in various formats (PDF, ODS, ...) at\n\n https://github.com/tvondra/scalability-patches\n\nThere's results from multiple machines - not just the big epyc machine,\nbut also smaller intel machines (4C and 16C), and even two rpi5 (yes, it\nhelps even on rpi5, quite a bit).\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company",
"msg_date": "Sun, 28 Jan 2024 22:57:02 +0100",
"msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>",
"msg_from_op": true,
"msg_subject": "scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "Le dimanche 28 janvier 2024, 22:57:02 CET Tomas Vondra a écrit :\n\nHi Tomas !\n\nI'll comment on glibc-malloc part as I studied that part last year, and \nproposed some things here: https://www.postgresql.org/message-id/\n3424675.QJadu78ljV%40aivenlaptop\n\n\n> FWIW where does the malloc overhead come from? For one, while we do have\n> some caching of malloc-ed memory in memory contexts, that doesn't quite\n> work cross-query, because we destroy the contexts at the end of the\n> query. We attempt to cache the memory contexts too, but in this case\n> that can't help because the allocations come from btbeginscan() where we\n> do this:\n> \n> so = (BTScanOpaque) palloc(sizeof(BTScanOpaqueData));\n> \n> and BTScanOpaqueData is ~27kB, which means it's an oversized chunk and\n> thus always allocated using a separate malloc() call. Maybe we could\n> break it into smaller/cacheable parts, but I haven't tried, and I doubt\n> > > > it's the only such allocation.\n\nDid you try running an strace on the process ? That may give you some \nhindsights into what malloc is doing. A more sophisticated approach would be \nusing stap and plugging it into the malloc probes, for example \nmemory_sbrk_more and memory_sbrk_less. \n\nAn important part of glibc's malloc behaviour in that regard comes from the \nadjustment of the mmap and free threshold. By default, mmap adjusts them \ndynamically and you can poke into that using the \nmemory_mallopt_free_dyn_thresholds probe.\n\n> \n> FWIW I was wondering if this is a glibc-specific malloc bottleneck, so I\n> tried running the benchmarks with LD_PRELOAD=jemalloc, and that improves\n> the behavior a lot - it gets us maybe ~80% of the mempool benefits.\n> Which is nice, it confirms it's glibc-specific (I wonder if there's a\n> way to tweak glibc to address this), and it also means systems using\n> jemalloc (e.g. FreeBSD, right?) don't have this problem. But it also\n> says the mempool has ~20% benefit on top of jemalloc.\n\nGLIBC's malloc offers some tuning for this. In particular, setting either \nM_MMAP_THRESHOLD or M_TRIM_THRESHOLD will disable the unpredictable \"auto \nadjustment\" beheviour and allow you to control what it's doing. \n\nBy setting a bigger M_TRIM_THRESHOLD, one can make sure memory allocated using \nsbrk isn't freed as easily, and you don't run into a pattern of moving the \nsbrk pointer up and down repeatedly. The automatic trade off between the mmap \nand trim thresholds is supposed to prevent that, but the way it is incremented \nmeans you can end in a bad place depending on your particular allocation \npatttern.\n\nBest regards,\n\n--\nRonan Dunklau\n\n\n\n\n\n",
"msg_date": "Mon, 29 Jan 2024 09:53:23 +0100",
"msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On 1/29/24 09:53, Ronan Dunklau wrote:\n> Le dimanche 28 janvier 2024, 22:57:02 CET Tomas Vondra a écrit :\n> \n> Hi Tomas !\n> \n> I'll comment on glibc-malloc part as I studied that part last year, and \n> proposed some things here: https://www.postgresql.org/message-id/\n> 3424675.QJadu78ljV%40aivenlaptop\n> \n\nThanks for reminding me. I'll re-read that thread.\n\n> \n>> FWIW where does the malloc overhead come from? For one, while we do have\n>> some caching of malloc-ed memory in memory contexts, that doesn't quite\n>> work cross-query, because we destroy the contexts at the end of the\n>> query. We attempt to cache the memory contexts too, but in this case\n>> that can't help because the allocations come from btbeginscan() where we\n>> do this:\n>>\n>> so = (BTScanOpaque) palloc(sizeof(BTScanOpaqueData));\n>>\n>> and BTScanOpaqueData is ~27kB, which means it's an oversized chunk and\n>> thus always allocated using a separate malloc() call. Maybe we could\n>> break it into smaller/cacheable parts, but I haven't tried, and I doubt\n>>>>> it's the only such allocation.\n> \n> Did you try running an strace on the process ? That may give you some \n> hindsights into what malloc is doing. A more sophisticated approach would be \n> using stap and plugging it into the malloc probes, for example \n> memory_sbrk_more and memory_sbrk_less. \n> \n\nNo, I haven't tried that. In my experience strace is pretty expensive,\nand if the issue is in glibc itself (before it does the syscalls),\nstrace won't really tell us much. Not sure, ofc.\n\n> An important part of glibc's malloc behaviour in that regard comes from the \n> adjustment of the mmap and free threshold. By default, mmap adjusts them \n> dynamically and you can poke into that using the \n> memory_mallopt_free_dyn_thresholds probe.\n> \n\nThanks, I'll take a look at that.\n\n>>\n>> FWIW I was wondering if this is a glibc-specific malloc bottleneck, so I\n>> tried running the benchmarks with LD_PRELOAD=jemalloc, and that improves\n>> the behavior a lot - it gets us maybe ~80% of the mempool benefits.\n>> Which is nice, it confirms it's glibc-specific (I wonder if there's a\n>> way to tweak glibc to address this), and it also means systems using\n>> jemalloc (e.g. FreeBSD, right?) don't have this problem. But it also\n>> says the mempool has ~20% benefit on top of jemalloc.\n> \n> GLIBC's malloc offers some tuning for this. In particular, setting either \n> M_MMAP_THRESHOLD or M_TRIM_THRESHOLD will disable the unpredictable \"auto \n> adjustment\" beheviour and allow you to control what it's doing. \n> \n> By setting a bigger M_TRIM_THRESHOLD, one can make sure memory allocated using \n> sbrk isn't freed as easily, and you don't run into a pattern of moving the \n> sbrk pointer up and down repeatedly. The automatic trade off between the mmap \n> and trim thresholds is supposed to prevent that, but the way it is incremented \n> means you can end in a bad place depending on your particular allocation \n> patttern.\n> \n\nSo, what values would you recommend for these parameters?\n\nMy concern is increasing those value would lead to (much) higher memory\nusage, with little control over it. With the mempool we keep more\nblocks, ofc, but we have control over freeing the memory.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n",
"msg_date": "Mon, 29 Jan 2024 13:17:07 +0100",
"msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>",
"msg_from_op": true,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "Le lundi 29 janvier 2024, 13:17:07 CET Tomas Vondra a écrit :\n> > Did you try running an strace on the process ? That may give you some\n> > hindsights into what malloc is doing. A more sophisticated approach would\n> > be using stap and plugging it into the malloc probes, for example\n> > memory_sbrk_more and memory_sbrk_less.\n> \n> No, I haven't tried that. In my experience strace is pretty expensive,\n> and if the issue is in glibc itself (before it does the syscalls),\n> strace won't really tell us much. Not sure, ofc.\n\nIt would tell you how malloc actually performs your allocations, and how often \nthey end up translated into syscalls. The main issue with glibc would be that \nit releases the memory too agressively to the OS, IMO.\n\n> \n> > An important part of glibc's malloc behaviour in that regard comes from\n> > the\n> > adjustment of the mmap and free threshold. By default, mmap adjusts them\n> > dynamically and you can poke into that using the\n> > memory_mallopt_free_dyn_thresholds probe.\n> \n> Thanks, I'll take a look at that.\n> \n> >> FWIW I was wondering if this is a glibc-specific malloc bottleneck, so I\n> >> tried running the benchmarks with LD_PRELOAD=jemalloc, and that improves\n> >> the behavior a lot - it gets us maybe ~80% of the mempool benefits.\n> >> Which is nice, it confirms it's glibc-specific (I wonder if there's a\n> >> way to tweak glibc to address this), and it also means systems using\n> >> jemalloc (e.g. FreeBSD, right?) don't have this problem. But it also\n> >> says the mempool has ~20% benefit on top of jemalloc.\n> > \n> > GLIBC's malloc offers some tuning for this. In particular, setting either\n> > M_MMAP_THRESHOLD or M_TRIM_THRESHOLD will disable the unpredictable \"auto\n> > adjustment\" beheviour and allow you to control what it's doing.\n> > \n> > By setting a bigger M_TRIM_THRESHOLD, one can make sure memory allocated\n> > using sbrk isn't freed as easily, and you don't run into a pattern of\n> > moving the sbrk pointer up and down repeatedly. The automatic trade off\n> > between the mmap and trim thresholds is supposed to prevent that, but the\n> > way it is incremented means you can end in a bad place depending on your\n> > particular allocation patttern.\n> \n> So, what values would you recommend for these parameters?\n> \n> My concern is increasing those value would lead to (much) higher memory\n> usage, with little control over it. With the mempool we keep more\n> blocks, ofc, but we have control over freeing the memory.\n\nRight now depending on your workload (especially if you use connection \npooling) you can end up with something like 32 or 64MB of dynamically adjusted \ntrim-threshold which will never be released back. \n\nThe first heurstic I had in mind was to set it to work_mem, up to a \n\"reasonable\" limit I guess. One can argue that it is expected for a backend to \nuse work_mem frequently, and as such it shouldn't be released back. By setting \nwork_mem to a lower value, we could ask glibc at the same time to trim the \nexcess kept memory. That could be useful when a long-lived connection is \npooled, and sees a spike in memory usage only once. Currently that could well \nend up with 32MB \"wasted\" permanently but tuning it ourselves could allow us \nto releaase it back. \n\nSince it was last year I worked on this, I'm a bit fuzzy on the details but I \nhope this helps.\n\n\n\n\n\n",
"msg_date": "Mon, 29 Jan 2024 15:15:25 +0100",
"msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "\n\nOn 1/29/24 15:15, Ronan Dunklau wrote:\n> Le lundi 29 janvier 2024, 13:17:07 CET Tomas Vondra a écrit :\n>>> Did you try running an strace on the process ? That may give you some\n>>> hindsights into what malloc is doing. A more sophisticated approach would\n>>> be using stap and plugging it into the malloc probes, for example\n>>> memory_sbrk_more and memory_sbrk_less.\n>>\n>> No, I haven't tried that. In my experience strace is pretty expensive,\n>> and if the issue is in glibc itself (before it does the syscalls),\n>> strace won't really tell us much. Not sure, ofc.\n> \n> It would tell you how malloc actually performs your allocations, and how often \n> they end up translated into syscalls. The main issue with glibc would be that \n> it releases the memory too agressively to the OS, IMO.\n> \n>>\n>>> An important part of glibc's malloc behaviour in that regard comes from\n>>> the\n>>> adjustment of the mmap and free threshold. By default, mmap adjusts them\n>>> dynamically and you can poke into that using the\n>>> memory_mallopt_free_dyn_thresholds probe.\n>>\n>> Thanks, I'll take a look at that.\n>>\n>>>> FWIW I was wondering if this is a glibc-specific malloc bottleneck, so I\n>>>> tried running the benchmarks with LD_PRELOAD=jemalloc, and that improves\n>>>> the behavior a lot - it gets us maybe ~80% of the mempool benefits.\n>>>> Which is nice, it confirms it's glibc-specific (I wonder if there's a\n>>>> way to tweak glibc to address this), and it also means systems using\n>>>> jemalloc (e.g. FreeBSD, right?) don't have this problem. But it also\n>>>> says the mempool has ~20% benefit on top of jemalloc.\n>>>\n>>> GLIBC's malloc offers some tuning for this. In particular, setting either\n>>> M_MMAP_THRESHOLD or M_TRIM_THRESHOLD will disable the unpredictable \"auto\n>>> adjustment\" beheviour and allow you to control what it's doing.\n>>>\n>>> By setting a bigger M_TRIM_THRESHOLD, one can make sure memory allocated\n>>> using sbrk isn't freed as easily, and you don't run into a pattern of\n>>> moving the sbrk pointer up and down repeatedly. The automatic trade off\n>>> between the mmap and trim thresholds is supposed to prevent that, but the\n>>> way it is incremented means you can end in a bad place depending on your\n>>> particular allocation patttern.\n>>\n>> So, what values would you recommend for these parameters?\n>>\n>> My concern is increasing those value would lead to (much) higher memory\n>> usage, with little control over it. With the mempool we keep more\n>> blocks, ofc, but we have control over freeing the memory.\n> \n> Right now depending on your workload (especially if you use connection \n> pooling) you can end up with something like 32 or 64MB of dynamically adjusted \n> trim-threshold which will never be released back. \n> \n\nOK, so let's say I expect each backend to use ~90MB of memory (allocated\nat once through memory contexts). How would you set the two limits? By\ndefault it's set to 128kB, which means blocks larger than 128kB are\nmmap-ed and released immediately.\n\nBut there's very few such allocations - a vast majority of blocks in the\nbenchmark workloads is <= 8kB or ~27kB (those from btbeginscan).\n\nSo I'm thinking about leaving M_TRIM_THRESHOLD as is, but increasing the\nM_TRIM_THRESHOLD value to a couple MBs. But I doubt that'll really help,\nbecause what I expect to happen is we execute a query and it allocates\nall memory up to a high watermark of ~90MB. And then the query\ncompletes, and we release almost all of it. And even with trim threshold\nset to e.g. 8MB we'll free almost all of it, no?\n\nWhat we want to do is say - hey, we needed 90MB, and now we need 8MB. We\ncould free 82MB, but maybe let's wait a bit and see if we need that\nmemory again. And that's pretty much what the mempool does, but I don't\nsee how to do that using the mmap options.\n\n> The first heurstic I had in mind was to set it to work_mem, up to a \n> \"reasonable\" limit I guess. One can argue that it is expected for a backend to \n> use work_mem frequently, and as such it shouldn't be released back. By setting \n> work_mem to a lower value, we could ask glibc at the same time to trim the \n> excess kept memory. That could be useful when a long-lived connection is \n> pooled, and sees a spike in memory usage only once. Currently that could well \n> end up with 32MB \"wasted\" permanently but tuning it ourselves could allow us \n> to releaase it back. \n> \n\nI'm not sure work_mem is a good parameter to drive this. It doesn't say\nhow much memory we expect the backend to use - it's a per-operation\nlimit, so it doesn't work particularly well with partitioning (e.g. with\n100 partitions, we may get 100 nodes, which is completely unrelated to\nwhat work_mem says). A backend running the join query with 1000\npartitions uses ~90MB (judging by data reported by the mempool), even\nwith work_mem=4MB. So setting the trim limit to 4MB is pretty useless.\n\nThe mempool could tell us how much memory we need (but we could track\nthis in some other way too, probably). And we could even adjust the mmap\nparameters regularly, based on current workload.\n\nBut there's then there's the problem that the mmap parameters don't tell\nus how much memory to keep, but how large chunks to release.\n\nLet's say we want to keep the 90MB (to allocate the memory once and then\nreuse it). How would you do that? We could set MMAP_TRIM_TRESHOLD 100MB,\nbut then it takes just a little bit of extra memory to release all the\nmemory, or something.\n\n> Since it was last year I worked on this, I'm a bit fuzzy on the details but I \n> hope this helps.\n> \n\nThanks for the feedback / insights!\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n",
"msg_date": "Mon, 29 Jan 2024 15:59:04 +0100",
"msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>",
"msg_from_op": true,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "Le lundi 29 janvier 2024, 15:59:04 CET Tomas Vondra a écrit :\n> I'm not sure work_mem is a good parameter to drive this. It doesn't say\n> how much memory we expect the backend to use - it's a per-operation\n> limit, so it doesn't work particularly well with partitioning (e.g. with\n> 100 partitions, we may get 100 nodes, which is completely unrelated to\n> what work_mem says). A backend running the join query with 1000\n> partitions uses ~90MB (judging by data reported by the mempool), even\n> with work_mem=4MB. So setting the trim limit to 4MB is pretty useless.\n\nI understand your point, I was basing my previous observations on what a \nbackend typically does during the execution.\n\n> \n> The mempool could tell us how much memory we need (but we could track\n> this in some other way too, probably). And we could even adjust the mmap\n> parameters regularly, based on current workload.\n> \n> But there's then there's the problem that the mmap parameters don't tell\n> If we > > us how much memory to keep, but how large chunks to release.\n> \n> Let's say we want to keep the 90MB (to allocate the memory once and then\n> reuse it). How would you do that? We could set MMAP_TRIM_TRESHOLD 100MB,\n> but then it takes just a little bit of extra memory to release all the\n> memory, or something.\n\nFor doing this you can set M_TOP_PAD using glibc malloc. Which makes sure a \ncertain amount of memory is always kept. \n\nBut the way the dynamic adjustment works makes it sort-of work like this. \nMMAP_THRESHOLD and TRIM_THRESHOLD start with low values, meaning we don't \nexpect to keep much memory around. \n\nSo even \"small\" memory allocations will be served using mmap at first. Once \nmmaped memory is released, glibc's consider it a benchmark for \"normal\" \nallocations that can be routinely freed, and adjusts mmap_threshold to the \nreleased mmaped region size, and trim threshold to two times that. \n\nIt means over time the two values will converge either to the max value (32MB \nfor MMAP_THRESHOLD, 64 for trim threshold) or to something big enough to \naccomodate your released memory, since anything bigger than half trim \nthreshold will be allocated using mmap. \n\nSetting any parameter disable that.\n\nBut I'm not arguing against the mempool, just chiming in with glibc's malloc \ntuning possibilities :-)\n\n\n\n\n",
"msg_date": "Mon, 29 Jan 2024 16:42:27 +0100",
"msg_from": "Ronan Dunklau <ronan.dunklau@aiven.io>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On 1/29/24 16:42, Ronan Dunklau wrote:\n> Le lundi 29 janvier 2024, 15:59:04 CET Tomas Vondra a écrit :\n>> I'm not sure work_mem is a good parameter to drive this. It doesn't say\n>> how much memory we expect the backend to use - it's a per-operation\n>> limit, so it doesn't work particularly well with partitioning (e.g. with\n>> 100 partitions, we may get 100 nodes, which is completely unrelated to\n>> what work_mem says). A backend running the join query with 1000\n>> partitions uses ~90MB (judging by data reported by the mempool), even\n>> with work_mem=4MB. So setting the trim limit to 4MB is pretty useless.\n> \n> I understand your point, I was basing my previous observations on what a \n> backend typically does during the execution.\n> \n>>\n>> The mempool could tell us how much memory we need (but we could track\n>> this in some other way too, probably). And we could even adjust the mmap\n>> parameters regularly, based on current workload.\n>>\n>> But there's then there's the problem that the mmap parameters don't tell\n>> If we > > us how much memory to keep, but how large chunks to release.\n>>\n>> Let's say we want to keep the 90MB (to allocate the memory once and then\n>> reuse it). How would you do that? We could set MMAP_TRIM_TRESHOLD 100MB,\n>> but then it takes just a little bit of extra memory to release all the\n>> memory, or something.\n> \n> For doing this you can set M_TOP_PAD using glibc malloc. Which makes sure a \n> certain amount of memory is always kept. \n> \n> But the way the dynamic adjustment works makes it sort-of work like this. \n> MMAP_THRESHOLD and TRIM_THRESHOLD start with low values, meaning we don't \n> expect to keep much memory around. \n> \n> So even \"small\" memory allocations will be served using mmap at first. Once \n> mmaped memory is released, glibc's consider it a benchmark for \"normal\" \n> allocations that can be routinely freed, and adjusts mmap_threshold to the \n> released mmaped region size, and trim threshold to two times that. \n> \n> It means over time the two values will converge either to the max value (32MB \n> for MMAP_THRESHOLD, 64 for trim threshold) or to something big enough to \n> accomodate your released memory, since anything bigger than half trim \n> threshold will be allocated using mmap. \n> \n> Setting any parameter disable that.\n> \n\nThanks. I gave this a try, and I started the tests with this setting:\n\nexport MALLOC_TOP_PAD_=$((64*1024*1024))\nexport MALLOC_MMAP_THRESHOLD_=$((1024*1024))\nexport MALLOC_TRIM_THRESHOLD_=$((1024*1024))\n\nwhich I believe means that:\n\n1) we'll keep 64MB \"extra\" memory on top of heap, serving as a cache for\nfuture allocations\n\n2) everything below 1MB (so most of the blocks we allocate for contexts)\nwill be allocated on heap (hence from the cache)\n\n3) we won't trim heap unless there's at least 1MB of free contiguous\nspace (I wonder if this should be the same as MALLOC_TOP_PAD)\n\nThose are mostly arbitrary values / guesses, and I don't have complete\nresults yet. But from the results I have it seems this has almost the\nsame effect as the mempool thing - see the attached PDF, with results\nfor the \"partitioned join\" benchmark.\n\nfirst column - \"master\" (17dev) with no patches, default glibc\n\nsecond column - 17dev + locking + mempool, default glibc\n\nthird column - 17dev + locking, tuned glibc\n\nThe color scale on the right is throughput comparison (third/second), as\na percentage with e.g. 90% meaning tuned glibc is 10% slower than the\nmempool results. Most of the time it's slower but very close to 100%,\nsometimes it's a bit faster. So overall it's roughly the same.\n\nThe color scales below the results is a comparison of each branch to the\nmaster (without patches), showing comparison to current performance.\nIt's almost the same, although the tuned glibc has a couple regressions\nthat the mempool does not have.\n\n> But I'm not arguing against the mempool, just chiming in with glibc's malloc \n> tuning possibilities :-)\n> \n\nYeah. I think the main problem with the glibc parameters is that it's\nvery implementation-specific and also static - the mempool is more\nadaptive, I think. But it's an interesting experiment.\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company",
"msg_date": "Wed, 31 Jan 2024 19:25:54 +0100",
"msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>",
"msg_from_op": true,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On Sun, Jan 28, 2024 at 4:57 PM Tomas Vondra\n<tomas.vondra@enterprisedb.com> wrote:\n> For NUM_LOCK_PARTITIONS this is pretty simple (see 0001 patch). The\n> LWLock table has 16 partitions by default - it's quite possible that on\n> machine with many cores and/or many partitions, we can easily hit this.\n> So I bumped this 4x to 64 partitions.\n\nI think this probably makes sense. I'm a little worried that we're\njust kicking the can down the road here where maybe we should be\nsolving the problem in some more fundamental way, and I'm also a\nlittle worried that we might be reducing single-core performance. But\nit's probably fine.\n\n> What I ended up doing is having a hash table of 16-element arrays. There\n> are 64 \"pieces\", each essentially the (16 x OID + UINT64 bitmap) that we\n> have now. Each OID is mapped to exactly one of these parts as if in a\n> hash table, and in each of those 16-element parts we do exactly the same\n> thing we do now (linear search, removal, etc.). This works great, the\n> locality is great, etc. The one disadvantage is this makes PGPROC\n> larger, but I did a lot of benchmarks and I haven't seen any regression\n> that I could attribute to this. (More about this later.)\n\nI think this is a reasonable approach. Some comments:\n\n- FastPathLocalUseInitialized seems unnecessary to me; the contents of\nan uninitialized local variable are undefined, but an uninitialized\nglobal variable always starts out zeroed.\n\n- You need comments in various places, including here, where someone\nis certain to have questions about the algorithm and choice of\nconstants:\n\n+#define FAST_PATH_LOCK_REL_GROUP(rel) (((uint64) (rel) * 7883 + 4481)\n% FP_LOCK_GROUPS_PER_BACKEND)\n\nWhen I originally coded up the fast-path locking stuff, I supposed\nthat we couldn't make the number of slots too big because the\nalgorithm requires a linear search of the whole array. But with this\none trick (a partially-associative cache), there's no real reason that\nI can think of why you can't make the number of slots almost\narbitrarily large. At some point you're going to use too much memory,\nand probably before that point you're going to make the cache big\nenough that it doesn't fit in the CPU cache of an individual core, at\nwhich point possibly it will stop working as well. But honestly ... I\ndon't quite see why this approach couldn't be scaled quite far.\n\nLike, if we raised FP_LOCK_GROUPS_PER_BACKEND from your proposed value\nof 64 to say 65536, would that still perform well? I'm not saying we\nshould do that, because that's probably a silly amount of memory to\nuse for this, but the point is that when you start to have enough\npartitions that you run out of lock slots, performance is going to\ndegrade, so you can imagine wanting to try to have enough lock groups\nto make that unlikely. Which leads me to wonder if there's any\nparticular number of lock groups that is clearly \"too many\" or whether\nit's just about how much memory we want to use.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n",
"msg_date": "Mon, 24 Jun 2024 11:05:23 -0400",
"msg_from": "Robert Haas <robertmhaas@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "\n\nOn 6/24/24 17:05, Robert Haas wrote:\n> On Sun, Jan 28, 2024 at 4:57 PM Tomas Vondra\n> <tomas.vondra@enterprisedb.com> wrote:\n>> For NUM_LOCK_PARTITIONS this is pretty simple (see 0001 patch). The\n>> LWLock table has 16 partitions by default - it's quite possible that on\n>> machine with many cores and/or many partitions, we can easily hit this.\n>> So I bumped this 4x to 64 partitions.\n> \n> I think this probably makes sense. I'm a little worried that we're\n> just kicking the can down the road here where maybe we should be\n> solving the problem in some more fundamental way, and I'm also a\n> little worried that we might be reducing single-core performance. But\n> it's probably fine.\n> \n\nYeah, I haven't seen this causing any regressions - the sensitive paths\ntypically lock only one partition, so having more of them does not\naffect that. Or if it does, it's likely a reasonable trade off as it\nreduces the risk of lock contention.\n\nThat being said, I don't recall benchmarking this patch in isolation,\nonly with the other patches. Maybe I should do that ...\n\n>> What I ended up doing is having a hash table of 16-element arrays. There\n>> are 64 \"pieces\", each essentially the (16 x OID + UINT64 bitmap) that we\n>> have now. Each OID is mapped to exactly one of these parts as if in a\n>> hash table, and in each of those 16-element parts we do exactly the same\n>> thing we do now (linear search, removal, etc.). This works great, the\n>> locality is great, etc. The one disadvantage is this makes PGPROC\n>> larger, but I did a lot of benchmarks and I haven't seen any regression\n>> that I could attribute to this. (More about this later.)\n> \n> I think this is a reasonable approach. Some comments:\n> \n> - FastPathLocalUseInitialized seems unnecessary to me; the contents of\n> an uninitialized local variable are undefined, but an uninitialized\n> global variable always starts out zeroed.\n> \n\nOK. I didn't realize global variables start a zero.\n\n> - You need comments in various places, including here, where someone\n> is certain to have questions about the algorithm and choice of\n> constants:\n> \n> +#define FAST_PATH_LOCK_REL_GROUP(rel) (((uint64) (rel) * 7883 + 4481)\n> % FP_LOCK_GROUPS_PER_BACKEND)\n> \n\nYeah, definitely needs comment explaining this.\n\nI admit those numbers are pretty arbitrary primes, to implement a\ntrivial hash function. That was good enough for a PoC patch, but maybe\nfor a \"proper\" version this should use a better hash function. It needs\nto be fast, and maybe it doesn't matter that much if it's not perfect.\n\n> When I originally coded up the fast-path locking stuff, I supposed\n> that we couldn't make the number of slots too big because the\n> algorithm requires a linear search of the whole array. But with this\n> one trick (a partially-associative cache), there's no real reason that\n> I can think of why you can't make the number of slots almost\n> arbitrarily large. At some point you're going to use too much memory,\n> and probably before that point you're going to make the cache big\n> enough that it doesn't fit in the CPU cache of an individual core, at\n> which point possibly it will stop working as well. But honestly ... I\n> don't quite see why this approach couldn't be scaled quite far.\n> \n\nI don't think I've heard the term \"partially-associative cache\" before,\nbut now that I look at the approach again, it very much reminds me how\nset-associative caches work (e.g. with cachelines in CPU caches). It's a\n16-way associative cache, assigning each entry into one of 16 slots.\n\nI must have been reading some papers in this area shortly before the PoC\npatch, and the idea came from there, probably. Which is good, because it\nmeans it's a well-understood and widely-used approach.\n\n> Like, if we raised FP_LOCK_GROUPS_PER_BACKEND from your proposed value\n> of 64 to say 65536, would that still perform well? I'm not saying we\n> should do that, because that's probably a silly amount of memory to\n> use for this, but the point is that when you start to have enough\n> partitions that you run out of lock slots, performance is going to\n> degrade, so you can imagine wanting to try to have enough lock groups\n> to make that unlikely. Which leads me to wonder if there's any\n> particular number of lock groups that is clearly \"too many\" or whether\n> it's just about how much memory we want to use.\n> \n\nThat's an excellent question. I don't know.\n\nI agree 64 groups is pretty arbitrary, and having 1024 may not be enough\neven with a modest number of partitions. When I was thinking about using\na higher value, my main concern was that it'd made the PGPROC entry\nlarger. Each \"fast-path\" group is ~72B, so 64 groups is ~4.5kB, and that\nfelt like quite a bit.\n\nBut maybe it's fine and we could make it much larger - L3 caches tend to\nbe many MBs these days, although AFAIK it's shared by threads running on\nthe CPU.\n\nI'll see if I can do some more testing of this, and see if there's a\nvalue where it stops improving / starts degrading, etc.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n",
"msg_date": "Tue, 25 Jun 2024 12:04:14 +0200",
"msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>",
"msg_from_op": true,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On Tue, Jun 25, 2024 at 6:04 AM Tomas Vondra\n<tomas.vondra@enterprisedb.com> wrote:\n> Yeah, definitely needs comment explaining this.\n>\n> I admit those numbers are pretty arbitrary primes, to implement a\n> trivial hash function. That was good enough for a PoC patch, but maybe\n> for a \"proper\" version this should use a better hash function. It needs\n> to be fast, and maybe it doesn't matter that much if it's not perfect.\n\nRight. My guess is that if we try too hard to make the hash function\ngood, there will be a performance hit. Unlike, say, strings that come\nfrom the user, we have no reason to believe that relfilenumbers will\nhave any particular structure or pattern to them, so a low-quality,\nfast function seems like a good trade-off to me. But I'm *far* from a\nhashing expert, so I'm prepared for someone who is to tell me that I'm\nfull of garbage.\n\n> I don't think I've heard the term \"partially-associative cache\" before\n> That's an excellent question. I don't know.\n>\n> I agree 64 groups is pretty arbitrary, and having 1024 may not be enough\n> even with a modest number of partitions. When I was thinking about using\n> a higher value, my main concern was that it'd made the PGPROC entry\n> larger. Each \"fast-path\" group is ~72B, so 64 groups is ~4.5kB, and that\n> felt like quite a bit.\n>\n> But maybe it's fine and we could make it much larger - L3 caches tend to\n> be many MBs these days, although AFAIK it's shared by threads running on\n> the CPU.\n>\n> I'll see if I can do some more testing of this, and see if there's a\n> value where it stops improving / starts degrading, etc.\n\nSounds good.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n",
"msg_date": "Tue, 25 Jun 2024 16:13:51 -0400",
"msg_from": "Robert Haas <robertmhaas@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "Hi,\n\nOn 6/25/24 12:04, Tomas Vondra wrote:\n> \n> \n> On 6/24/24 17:05, Robert Haas wrote:\n>> On Sun, Jan 28, 2024 at 4:57 PM Tomas Vondra\n>> <tomas.vondra@enterprisedb.com> wrote:\n>>> For NUM_LOCK_PARTITIONS this is pretty simple (see 0001 patch). The\n>>> LWLock table has 16 partitions by default - it's quite possible that on\n>>> machine with many cores and/or many partitions, we can easily hit this.\n>>> So I bumped this 4x to 64 partitions.\n>>\n>> I think this probably makes sense. I'm a little worried that we're\n>> just kicking the can down the road here where maybe we should be\n>> solving the problem in some more fundamental way, and I'm also a\n>> little worried that we might be reducing single-core performance. But\n>> it's probably fine.\n>>\n> \n> Yeah, I haven't seen this causing any regressions - the sensitive paths\n> typically lock only one partition, so having more of them does not\n> affect that. Or if it does, it's likely a reasonable trade off as it\n> reduces the risk of lock contention.\n> \n> That being said, I don't recall benchmarking this patch in isolation,\n> only with the other patches. Maybe I should do that ...\n> \n>>> What I ended up doing is having a hash table of 16-element arrays. There\n>>> are 64 \"pieces\", each essentially the (16 x OID + UINT64 bitmap) that we\n>>> have now. Each OID is mapped to exactly one of these parts as if in a\n>>> hash table, and in each of those 16-element parts we do exactly the same\n>>> thing we do now (linear search, removal, etc.). This works great, the\n>>> locality is great, etc. The one disadvantage is this makes PGPROC\n>>> larger, but I did a lot of benchmarks and I haven't seen any regression\n>>> that I could attribute to this. (More about this later.)\n>>\n>> I think this is a reasonable approach. Some comments:\n>>\n>> - FastPathLocalUseInitialized seems unnecessary to me; the contents of\n>> an uninitialized local variable are undefined, but an uninitialized\n>> global variable always starts out zeroed.\n>>\n> \n> OK. I didn't realize global variables start a zero.\n> \n\nI haven't fixed this yet, but it's pretty clear the \"init\" is not really \nneeded, because it did the memset() wrong:\n\nmemset(FastPathLocalUseCounts, 0, sizeof(FastPathLocalUseInitialized));\n\nThis only resets one byte of the array, yet it still worked correctly.\n\n>> - You need comments in various places, including here, where someone\n>> is certain to have questions about the algorithm and choice of\n>> constants:\n>>\n>> +#define FAST_PATH_LOCK_REL_GROUP(rel) (((uint64) (rel) * 7883 + 4481)\n>> % FP_LOCK_GROUPS_PER_BACKEND)\n>>\n> \n> Yeah, definitely needs comment explaining this.\n> \n> I admit those numbers are pretty arbitrary primes, to implement a\n> trivial hash function. That was good enough for a PoC patch, but maybe\n> for a \"proper\" version this should use a better hash function. It needs\n> to be fast, and maybe it doesn't matter that much if it's not perfect.\n> \n>> When I originally coded up the fast-path locking stuff, I supposed\n>> that we couldn't make the number of slots too big because the\n>> algorithm requires a linear search of the whole array. But with this\n>> one trick (a partially-associative cache), there's no real reason that\n>> I can think of why you can't make the number of slots almost\n>> arbitrarily large. At some point you're going to use too much memory,\n>> and probably before that point you're going to make the cache big\n>> enough that it doesn't fit in the CPU cache of an individual core, at\n>> which point possibly it will stop working as well. But honestly ... I\n>> don't quite see why this approach couldn't be scaled quite far.\n>>\n> \n> I don't think I've heard the term \"partially-associative cache\" before,\n> but now that I look at the approach again, it very much reminds me how\n> set-associative caches work (e.g. with cachelines in CPU caches). It's a\n> 16-way associative cache, assigning each entry into one of 16 slots.\n> \n> I must have been reading some papers in this area shortly before the PoC\n> patch, and the idea came from there, probably. Which is good, because it\n> means it's a well-understood and widely-used approach.\n> \n>> Like, if we raised FP_LOCK_GROUPS_PER_BACKEND from your proposed value\n>> of 64 to say 65536, would that still perform well? I'm not saying we\n>> should do that, because that's probably a silly amount of memory to\n>> use for this, but the point is that when you start to have enough\n>> partitions that you run out of lock slots, performance is going to\n>> degrade, so you can imagine wanting to try to have enough lock groups\n>> to make that unlikely. Which leads me to wonder if there's any\n>> particular number of lock groups that is clearly \"too many\" or whether\n>> it's just about how much memory we want to use.\n>>\n> \n> That's an excellent question. I don't know.\n> \n> I agree 64 groups is pretty arbitrary, and having 1024 may not be enough\n> even with a modest number of partitions. When I was thinking about using\n> a higher value, my main concern was that it'd made the PGPROC entry\n> larger. Each \"fast-path\" group is ~72B, so 64 groups is ~4.5kB, and that\n> felt like quite a bit.\n> \n> But maybe it's fine and we could make it much larger - L3 caches tend to\n> be many MBs these days, although AFAIK it's shared by threads running on\n> the CPU.\n> \n> I'll see if I can do some more testing of this, and see if there's a\n> value where it stops improving / starts degrading, etc.\n> \n\nI finally got to do those experiments. The scripts and results (both raw \nand summarized) are too big to attach everything here, available at\n\n https://github.com/tvondra/scalability-tests\n\nThe initial patch used 64 (which means 1024 fast-path slots), I ran the \ntests with 0, 1, 8, 32, 128, 512, 1024 (so up to 16k locks). I thought \nabout testing with ~64k groups, but I didn't go with the extreme value \nbecause I don't quite see the point.\n\nIt would only matter for cases with a truly extreme number of partitions \n(64k groups is ~1M fast-path slots), and just creating enough partitions \nwould take a lot of time. Moreover, with that many partitions we seems \nto have various other bottlenecks, and improving this does not make it \nreally practical. And it's so slow the benchmark results are somewhat \nbogus too.\n\nBecause if we achieve 50 tps with 1000 partitions, does it really matter \na patch changes that to 25 of 100 tps? I doubt that, especially if going \nto 100 partitions gives you 2000 tps. Now imagine you have 10k or 100k \npartitions - how fast is that going to be?\n\nSo I think stopping at 1024 groups is sensible, and if there are some \ninefficiencies / costs, I'd expect those to gradually show up even at \nthose lower sizes.\n\nBut if you look at results, for example from the \"join\" test:\n\n https://github.com/tvondra/scalability-tests/blob/main/join.pdf\n\nthere's no such negative effect. the table shows results for different \ncombinations of parameters, with the first group of columns being on \nregular glibc, the second one has glibc tuning (see [1] for details). \nAnd the values are for different number of fast-path groups (0 means the \npatch was not applied).\n\nAnd the color scale on the show the impact of increasing the number of \ngroups. So for example when a column for \"32 groups\" says 150%, it means \ngoing from 8 to 32 groups improved throughput to 1.5x. As usual, green \nis \"good\" and red is \"bad\".\n\nBut if you look at the tables, there's very little change - most of the \nvalues are close to 100%. This might seem a bit strange, considering the \npromise of these patches is to improve throughput, and \"no change\" is an \nabsence of that. But that's because the charts illustrate effect of \nchanging the group count with other parameters fixed. It never compares \nruns with/without glibc runing, and that's an important part of the \nimprovement. Doing the pivot table a bit differently would still show a \nsubstantial 2-3x improvement.\n\nThere's a fair amount of noise - especially for the rpi5 machines (not \nthe right hw for sensitive benchmarks), but also on some i5/xeon runs. I \nattribute this to only doing one short run (10s) for each combinations \nof parameters. I'll do more runs next time.\n\nAnyway, I think these results show a couple things:\n\n1) There's no systemic negative effect of increasing the number of \ngroups. We could go with 32k or 64k groups, and it doesn't seem like \nthere would be a problem.\n\n2) But there's not much point in doing that, because we run into various \nother bottlenecks well before having that many locks. By the results, it \ndoesn't seem going beyond 32 or 64 groups would give us much.\n\n3) The memory allocation caching (be it the mempool patch, or the glibc \ntuning like in this test round) is a crucial piece for this. Not doing \nthat means some tests get no improvement at all, or a much smaller one.\n\n4) The increase of NUM_LOCK_PARTITIONS has very limited effect, or \nperhaps even no effect at all.\n\n\nBased on this, my plan is to polish the patch adding fast-path groups, \nwith either 32 or 64 groups, which seems to be reasonable values. Then \nin the future, if/when the other bottlenecks get addressed, we can \nrethink and increase this.\n\nThis however reminds me that all those machines are pretty small. Which \nis good for showing it doesn't break existing/smaller systems, but the \ninitial goal of the patch was to improve behavior on big boxes. I don't \nhave access to the original box at the moment, so if someone could \nprovide an access to one of those big epyc/xeon machines with 100+ cores \nfor a couple days, that would be helpful.\n\n\nThat being said, I think it's pretty clear how serious the issue with \nmemory allocation overhead can be, especially in cases when the existing \nmemory context caching is ineffective (like for the btree palloc). I'm \nnot sure what to do about that. The mempool patch shared in this thread \ndoes the trick, it's fairly complex/invasive. I still like it, but maybe \ndoing something with the glibc tuning would be enough - it's not as \neffective, but 80% of the improvement is better than no improvement.\n\n\n\nregards\n\n\n[1] \nhttps://www.postgresql.org/message-id/0da51f67-c88b-497e-bb89-d5139309eb9c@enterprisedb.com\n\n-- \nTomas Vondra\n\n\n",
"msg_date": "Mon, 5 Aug 2024 13:38:31 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "Hi,\n\nWhile discussing this patch with Robert off-list, one of the questions\nhe asked was is there's some size threshold after which it starts to\nhave negative impact. I didn't have a good answer to that - I did have\nsome intuition (that making it too large would not hurt), but I haven't\ndone any tests with \"extreme\" sizes of the fast-path structs.\n\nSo I ran some more tests, with up to 4096 \"groups\" (which means 64k\nfast-path slots). And no matter how I slice the results, there's no\nclear regression points, beyond which the performance would start to\ndecline (even just slowly). It's the same for all benchmarks, client\ncounts, query mode, and so on.\n\nI'm attaching two PDFs with results for the \"join\" benchmark I described\nearlier (query with a join on many partitions) from EPYC 7763 (64/128c).\nThe first one is with \"raw\" data (throughput = tps), the second one is\nrelative throughput to the first column (which is pretty much current\nmaster, with no optimizations applied).\n\nThe complete results including some nice .odp spreadsheets and scripts\nare available here:\n\n https://github.com/tvondra/pg-lock-scalability-results\n\nThere's often a very clear point where the performance significantly\nimproves - this is usually when all the relation locks start to fit into\nthe fast-path array. With 1000 relations that's ~64 groups, and so on.\nBut there's no point where it would start declining.\n\nMy explanation is that the PGPROC (where the fast-path array is) is so\nlarge already (close to 1kB), that making it large does not really cause\nany additional cache misses, etc. And if it does, it's far out-weighted\nby cost of accessing (or not having to) the shared lock table.\n\nSo I don't think there's any point at which point we'd start to regress,\nat least not because of cache misses, CPU etc. It stops improving, but\nthat's just a sign that we've hit some other bottleneck - that's not a\nfault of this patch.\n\n\nBut that's not the whole story, of course. Because if there were no\nissues, why not to just make the fast-path array insanely large? In\nanother off-list discussion Andres asked me about the memory this would\nneed, and after looking at the numbers I think that's a strong argument\nto keep the numbers reasonable.\n\nI did a quick experiment to see the per-connection memory requirements,\nand how would it be affected by this patch. I simply logged the amount\nof shared memory CalculateShmemSize(), started the server with 100 and\n1000 connections, and did a bit of math to calculate how much memory we\nneed \"per connection\".\n\nFor master and different numbers of fast-path groups I got this:\n\n master 64 1024 32765\n ---------------------------------\n 47668 52201 121324 2406892\n\nSo by default we need ~48kB / connection, with 64 groups we need ~52kB\n(which makes sense because that's 1024 x 4B slots), and then with 1024\nslots we get to 120kB etc and with 32k ~2.5MB.\n\nI guess those higher values seem a bit insane - we don't want to just\nincrease the per-connection memory requirements 50x for everyone, right?\n\nBut what about the people who actually want this many locks? Let's bump\nthe max_locks_per_transactions from 64 to 1024, and we get this:\n\n master 64 1024 32765\n -------------------------------------\n 419367 423909 493022 2778590\n\nSuddenly, the differences are much smaller, especially for the 64\ngroups, which is roughly the same number of fast-path slots as the max\nlocks per transactions. That shrunk to ~1% difference. But wen for 1024\ngroups it's now just ~20%, which I think it well worth the benefits.\n\nAnd likely something the system should have available - with 1000\nconnections that's ~80MB. And if you run with 1000 connections, 80MB\nshould be rounding error, IMO.\n\nOf course, it does not seem great to force everyone to pay this price,\neven if they don't need that many locks (and so there's no benefit). So\nhow would we improve that?\n\nI don't think that's possible with hard-coded size of the array - that\nallocates the memory for everyone. We'd need to make it variable-length,\nand while doing those benchmarks I think we actually already have a GUC\nfor that - max_locks_per_transaction tells us exactly what we need to\nknow, right? I mean, if I know I'll need ~1000 locks, why not to make\nthe fast-path array large enough for that?\n\nOf course, the consequence of this would be making PGPROC variable\nlength, or having to point to a memory allocated separately (I prefer\nthe latter option, I think). I haven't done any experiments, but it\nseems fairly doable - of course, not sure if it might be more expensive\ncompared to compile-time constants.\n\n\nAt this point I think it's fairly clear we have significant bottlenecks\nwhen having to lock many relations - and that won't go away, thanks to\npartitioning etc. We're already fixing various other bottlenecks for\nthese workloads, which will just increase pressure on locking.\n\nFundamentally, I think we'll need to either evolve the fast-path system\nto handle more relations (the limit of 16 was always rather quite low),\nor invent some entirely new thing that does something radical (say,\nlocking a \"group\" of relations instead of locking them one by one).\n\nThis patch is doing the first thing, and IMHO the increased memory\nconsumption is a sensible / acceptable trade off. I'm not sure of any\nproposal for the second approach, and I don't have any concrete idea how\nit might work.\n\n\n\nregards\n\n-- \nTomas Vondra",
"msg_date": "Sun, 1 Sep 2024 21:30:27 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On Sun, Sep 1, 2024 at 3:30 PM Tomas Vondra <tomas@vondra.me> wrote:\n> I don't think that's possible with hard-coded size of the array - that\n> allocates the memory for everyone. We'd need to make it variable-length,\n> and while doing those benchmarks I think we actually already have a GUC\n> for that - max_locks_per_transaction tells us exactly what we need to\n> know, right? I mean, if I know I'll need ~1000 locks, why not to make\n> the fast-path array large enough for that?\n\nI really like this idea. I'm not sure about exactly how many fast path\nslots you should get for what value of max_locks_per_transaction, but\ncoupling the two things together in some way sounds smart.\n\n> Of course, the consequence of this would be making PGPROC variable\n> length, or having to point to a memory allocated separately (I prefer\n> the latter option, I think). I haven't done any experiments, but it\n> seems fairly doable - of course, not sure if it might be more expensive\n> compared to compile-time constants.\n\nI agree that this is a potential problem but it sounds like the idea\nworks well enough that we'd probably still come out quite far ahead\neven with a bit more overhead.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n",
"msg_date": "Sun, 1 Sep 2024 19:53:39 -0400",
"msg_from": "Robert Haas <robertmhaas@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On 9/2/24 01:53, Robert Haas wrote:\n> On Sun, Sep 1, 2024 at 3:30 PM Tomas Vondra <tomas@vondra.me> wrote:\n>> I don't think that's possible with hard-coded size of the array - that\n>> allocates the memory for everyone. We'd need to make it variable-length,\n>> and while doing those benchmarks I think we actually already have a GUC\n>> for that - max_locks_per_transaction tells us exactly what we need to\n>> know, right? I mean, if I know I'll need ~1000 locks, why not to make\n>> the fast-path array large enough for that?\n> \n> I really like this idea. I'm not sure about exactly how many fast path\n> slots you should get for what value of max_locks_per_transaction, but\n> coupling the two things together in some way sounds smart.\n> \n\nI think we should keep that simple and make the cache large enough for\nmax_locks_per_transaction locks. That's the best information about\nexpected number of locks we have. If the GUC is left at the default\nvalue, that probably means they backends need that many locks on\naverage. Yes, maybe there's an occasional spike in one of the backends,\nbut then that means other backends need fewer locks, and so there's less\ncontention for the shared lock table.\n\nOf course, it's possible to construct counter-examples to this. Say a\nsingle backend that needs a lot of these locks. But how's that different\nfrom every other fixed-size cache with eviction?\n\nThe one argument to not tie this to max_locks_per_transaction is the\nvastly different \"per element\" memory requirements. If you add one entry\nto max_locks_per_transaction, that adds LOCK which is a whopping 152B.\nOTOH one fast-path entry is ~5B, give or take. That's a pretty big\ndifference, and it if the locks fit into the shared lock table, but\nyou'd like to allow more fast-path locks, having to increase\nmax_locks_per_transaction is not great - pretty wastefull.\n\nOTOH I'd really hate to just add another GUC and hope the users will\nmagically know how to set it correctly. That's pretty unlikely, IMO. I\nmyself wouldn't know what a good value is, I think.\n\nBut say we add a GUC and set it to -1 by default, in which case it just\ninherits the max_locks_per_transaction value. And then also provide some\nbasic metric about this fast-path cache, so that people can tune this?\n\nI think just knowing the \"hit ratio\" would be enough, i.e. counters for\nhow often it fits into the fast-path array, and how often we had to\npromote it to the shared lock table would be enough, no?\n\n>> Of course, the consequence of this would be making PGPROC variable\n>> length, or having to point to a memory allocated separately (I prefer\n>> the latter option, I think). I haven't done any experiments, but it\n>> seems fairly doable - of course, not sure if it might be more expensive\n>> compared to compile-time constants.\n> \n> I agree that this is a potential problem but it sounds like the idea\n> works well enough that we'd probably still come out quite far ahead\n> even with a bit more overhead.\n> \n\nOK, I did some quick tests on this, and I don't see any regressions.\n\nAttached are 4 patches:\n\n1) 0001 - original patch, with some minor fixes (remove init, which is\n not necessary, that sort of thing)\n\n2) 0002 - a bit of reworks, improving comments, structuring the macros a\n little bit better, etc. But still compile-time constants.\n\n3) 0003 - dynamic sizing, based on max_locks_pet_transaction. It's a bit\n ugly, because the size is calculated during shmem allocation - it\n should happen earlier, but good enough for PoC.\n\n4) 0004 - introduce a separate GUC, this is mostly to allow testing of\n different values without changing max_locks_per_transaction\n\n\nI've only did that on my smaller 32-core machine, but for three simple\ntests it looks like this (throughput using 16 clients):\n\n mode test master 1 2 3 4\n ----------------------------------------------------------------\n prepared count 1460 1477 1488 1490 1491\n join 15556 24451 26044 25026 24237\n pgbench 148187 151192 151688 150389 152681\n ----------------------------------------------------------------\n simple count 1341 1351 1373 1374 1370\n join 4643 5439 5459 5393 5345\n pgbench 139763 141267 142796 141207 142600\n\nThose are some simple benchmarks on 100 partitions, where the regular\npgbench and count(*) are expected to not be improved, and the join is\nthe partitioned join this thread started with. 1-4 are the attached\npatches, to see the impact for each of them.\n\nTranslated to results relative to\n\n mode test 1 2 3 4\n -------------------------------------------------\n prepared count 101% 102% 102% 102%\n join 157% 167% 161% 156%\n pgbench 102% 102% 101% 103%\n -------------------------------------------------\n simple count 101% 102% 102% 102%\n join 117% 118% 116% 115%\n pgbench 101% 102% 101% 102%\n\nSo pretty much no difference between the patches. A bit of noise, but\nthat's what I'd expect on this machine.\n\nI'll do more testing on the bit EPYC machine once it gets available, but\nfrom these results it seems pretty promising.\n\n\nregards\n\n-- \nTomas Vondra",
"msg_date": "Mon, 2 Sep 2024 19:46:21 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On Mon, Sep 2, 2024 at 1:46 PM Tomas Vondra <tomas@vondra.me> wrote:\n> The one argument to not tie this to max_locks_per_transaction is the\n> vastly different \"per element\" memory requirements. If you add one entry\n> to max_locks_per_transaction, that adds LOCK which is a whopping 152B.\n> OTOH one fast-path entry is ~5B, give or take. That's a pretty big\n> difference, and it if the locks fit into the shared lock table, but\n> you'd like to allow more fast-path locks, having to increase\n> max_locks_per_transaction is not great - pretty wastefull.\n>\n> OTOH I'd really hate to just add another GUC and hope the users will\n> magically know how to set it correctly. That's pretty unlikely, IMO. I\n> myself wouldn't know what a good value is, I think.\n>\n> But say we add a GUC and set it to -1 by default, in which case it just\n> inherits the max_locks_per_transaction value. And then also provide some\n> basic metric about this fast-path cache, so that people can tune this?\n\nAll things being equal, I would prefer not to add another GUC for\nthis, but we might need it.\n\nDoing some worst case math, suppose somebody has max_connections=1000\n(which is near the upper limit of what I'd consider a sane setting)\nand max_locks_per_transaction=10000 (ditto). The product is 10\nmillion, so every 10 bytes of storage each a gigabyte of RAM. Chewing\nup 15GB of RAM when you could have chewed up only 0.5GB certainly\nisn't too great. On the other hand, those values are kind of pushing\nthe limits of what is actually sane. If you imagine\nmax_locks_per_transaction=2000 rather than\nmax_locks_per_connection=10000, then it's only 3GB and that's\nhopefully not a lot on the hopefully-giant machine where you're\nrunning this.\n\n> I think just knowing the \"hit ratio\" would be enough, i.e. counters for\n> how often it fits into the fast-path array, and how often we had to\n> promote it to the shared lock table would be enough, no?\n\nYeah, probably. I mean, that won't tell you how big it needs to be,\nbut it will tell you whether it's big enough.\n\nI wonder if we should be looking at further improvements in the lock\nmanager of some kind. For instance, imagine if we allocated storage\nvia DSM or DSA for cases where we need a really large number of Lock\nentries. The downside of that is that we might run out of memory for\nlocks at runtime, which would perhaps suck, but you'd probably use\nsignificantly less memory on average. Or, maybe we need an even bigger\nrethink where we reconsider the idea that we take a separate lock for\nevery single partition instead of having some kind of hierarchy-aware\nlock manager. I don't know. But this feels like very old, crufty tech.\nThere's probably something more state of the art that we could or\nshould be doing.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n",
"msg_date": "Tue, 3 Sep 2024 11:06:32 -0400",
"msg_from": "Robert Haas <robertmhaas@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On 9/3/24 17:06, Robert Haas wrote:\n> On Mon, Sep 2, 2024 at 1:46 PM Tomas Vondra <tomas@vondra.me> wrote:\n>> The one argument to not tie this to max_locks_per_transaction is the\n>> vastly different \"per element\" memory requirements. If you add one entry\n>> to max_locks_per_transaction, that adds LOCK which is a whopping 152B.\n>> OTOH one fast-path entry is ~5B, give or take. That's a pretty big\n>> difference, and it if the locks fit into the shared lock table, but\n>> you'd like to allow more fast-path locks, having to increase\n>> max_locks_per_transaction is not great - pretty wastefull.\n>>\n>> OTOH I'd really hate to just add another GUC and hope the users will\n>> magically know how to set it correctly. That's pretty unlikely, IMO. I\n>> myself wouldn't know what a good value is, I think.\n>>\n>> But say we add a GUC and set it to -1 by default, in which case it just\n>> inherits the max_locks_per_transaction value. And then also provide some\n>> basic metric about this fast-path cache, so that people can tune this?\n> \n> All things being equal, I would prefer not to add another GUC for\n> this, but we might need it.\n> \n\nAgreed.\n\n> Doing some worst case math, suppose somebody has max_connections=1000\n> (which is near the upper limit of what I'd consider a sane setting)\n> and max_locks_per_transaction=10000 (ditto). The product is 10\n> million, so every 10 bytes of storage each a gigabyte of RAM. Chewing\n> up 15GB of RAM when you could have chewed up only 0.5GB certainly\n> isn't too great. On the other hand, those values are kind of pushing\n> the limits of what is actually sane. If you imagine\n> max_locks_per_transaction=2000 rather than\n> max_locks_per_connection=10000, then it's only 3GB and that's\n> hopefully not a lot on the hopefully-giant machine where you're\n> running this.\n> \n\nYeah, although I don't quite follow the math. With 1000/10000 settings,\nwhy would that eat 15GB of RAM? I mean, that's 1.5GB, right?\n\nFWIW the actual cost is somewhat higher, because we seem to need ~400B\nfor every lock (not just the 150B for the LOCK struct). At least based\non a quick experiment. (Seems a bit high, right?).\n\nAnyway, I agree this might be acceptable. If your transactions use this\nmany locks regularly, you probably need this setting anyway. If you only\nneed this many locks occasionally (so that you can keep the locks/xact\nvalue low), it probably does not matter that much.\n\nAnd if you're running massively-partitioned table on a tiny box, well, I\ndon't really think that's a particularly sane idea.\n\nSo I think I'm OK with just tying this to max_locks_per_transaction.\n\n>> I think just knowing the \"hit ratio\" would be enough, i.e. counters for\n>> how often it fits into the fast-path array, and how often we had to\n>> promote it to the shared lock table would be enough, no?\n> \n> Yeah, probably. I mean, that won't tell you how big it needs to be,\n> but it will tell you whether it's big enough.\n> \n\nTrue, but that applies to all \"cache hit ratio\" metrics (like for our\nshared buffers). It'd be great to have something better, enough to tell\nyou how large the cache needs to be. But we don't :-(\n\n> I wonder if we should be looking at further improvements in the lock\n> manager of some kind. For instance, imagine if we allocated storage\n> via DSM or DSA for cases where we need a really large number of Lock\n> entries. The downside of that is that we might run out of memory for\n> locks at runtime, which would perhaps suck, but you'd probably use\n> significantly less memory on average. Or, maybe we need an even bigger\n> rethink where we reconsider the idea that we take a separate lock for\n> every single partition instead of having some kind of hierarchy-aware\n> lock manager. I don't know. But this feels like very old, crufty tech.\n> There's probably something more state of the art that we could or\n> should be doing.\n> \n\nPerhaps. I agree we'll probably need something more radical soon, not\njust changes that aim to fix some rare exceptional case (which may be\nannoying, but not particularly harmful for the complete workload).\n\nFor example, if we did what you propose, that might help when very few\ntransactions need a lot of locks. I don't mind saving memory in that\ncase, ofc. but is it a problem if those rare cases are a bit slower?\nShouldn't we focus more on cases where many locks are common? Because\npeople are simply going to use partitioning, a lot of indexes, etc?\n\nSo yeah, I agree we probably need a more fundamental rethink. I don't\nthink we can just keep optimizing the current approach, there's a limit\nof fast it can be. Whether it's not locking individual partitions, or\nnot locking some indexes, ... I don't know.\n\n\nregards\n\n-- \nTomas Vondra\n\n\n",
"msg_date": "Tue, 3 Sep 2024 18:19:45 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "Hi Tomas!\n\nOn Tue, Sep 3, 2024 at 6:20 PM Tomas Vondra <tomas@vondra.me> wrote:\n>\n> On 9/3/24 17:06, Robert Haas wrote:\n> > On Mon, Sep 2, 2024 at 1:46 PM Tomas Vondra <tomas@vondra.me> wrote:\n> >> The one argument to not tie this to max_locks_per_transaction is the\n> >> vastly different \"per element\" memory requirements. If you add one entry\n> >> to max_locks_per_transaction, that adds LOCK which is a whopping 152B.\n> >> OTOH one fast-path entry is ~5B, give or take. That's a pretty big\n> >> difference, and it if the locks fit into the shared lock table, but\n> >> you'd like to allow more fast-path locks, having to increase\n> >> max_locks_per_transaction is not great - pretty wastefull.\n> >>\n> >> OTOH I'd really hate to just add another GUC and hope the users will\n> >> magically know how to set it correctly. That's pretty unlikely, IMO. I\n> >> myself wouldn't know what a good value is, I think.\n> >>\n> >> But say we add a GUC and set it to -1 by default, in which case it just\n> >> inherits the max_locks_per_transaction value. And then also provide some\n> >> basic metric about this fast-path cache, so that people can tune this?\n> >\n> > All things being equal, I would prefer not to add another GUC for\n> > this, but we might need it.\n> >\n>\n> Agreed.\n>\n> [..]\n>\n> So I think I'm OK with just tying this to max_locks_per_transaction.\n\nIf that matters then the SLRU configurability effort added 7 GUCs\n(with 3 scaling up based on shared_buffers) just to give high-end\nusers some relief, so here 1 new shouldn't be that such a deal. We\ncould add to the LWLock/lock_manager wait event docs to recommend just\nusing known-to-be-good certain values from this $thread (or ask the\nuser to benchmark it himself).\n\n> >> I think just knowing the \"hit ratio\" would be enough, i.e. counters for\n> >> how often it fits into the fast-path array, and how often we had to\n> >> promote it to the shared lock table would be enough, no?\n> >\n> > Yeah, probably. I mean, that won't tell you how big it needs to be,\n> > but it will tell you whether it's big enough.\n> >\n>\n> True, but that applies to all \"cache hit ratio\" metrics (like for our\n> shared buffers). It'd be great to have something better, enough to tell\n> you how large the cache needs to be. But we don't :-(\n\nMy $0.02 cents: the originating case that triggered those patches,\nactually started with LWLock/lock_manager waits being the top#1. The\noperator can cross check (join) that with a group by pg_locks.fastpath\n(='f'), count(*). So, IMHO we have good observability in this case\n(rare thing to say!)\n\n> > I wonder if we should be looking at further improvements in the lock\n> > manager of some kind. [..]\n>\n> Perhaps. I agree we'll probably need something more radical soon, not\n> just changes that aim to fix some rare exceptional case (which may be\n> annoying, but not particularly harmful for the complete workload).\n>\n> For example, if we did what you propose, that might help when very few\n> transactions need a lot of locks. I don't mind saving memory in that\n> case, ofc. but is it a problem if those rare cases are a bit slower?\n> Shouldn't we focus more on cases where many locks are common? Because\n> people are simply going to use partitioning, a lot of indexes, etc?\n>\n> So yeah, I agree we probably need a more fundamental rethink. I don't\n> think we can just keep optimizing the current approach, there's a limit\n> of fast it can be.\n\nPlease help me understand: so are You both discussing potential far\nfuture further improvements instead of this one ? My question is\nreally about: is the patchset good enough or are you considering some\nother new effort instead?\n\nBTW some other random questions:\nQ1. I've been lurking into\nhttps://github.com/tvondra/pg-lock-scalability-results and those\nshouldn't be used anymore for further discussions, as they contained\nearlier patches (including\n0003-Add-a-memory-pool-with-adaptive-rebalancing.patch) and they were\nreplaced by benchmark data in this $thread, right?\nQ2. Earlier attempts did contain a mempool patch to get those nice\nnumbers (or was that jemalloc or glibc tuning). So were those recent\nresults in [1] collected with still 0003 or you have switched\ncompletely to glibc/jemalloc tuning?\n\n-J.\n\n[1] - https://www.postgresql.org/message-id/b8c43eda-0c3f-4cb4-809b-841fa5c40ada%40vondra.me\n\n\n",
"msg_date": "Wed, 4 Sep 2024 11:29:48 +0200",
"msg_from": "Jakub Wartak <jakub.wartak@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On 9/4/24 11:29, Jakub Wartak wrote:\n> Hi Tomas!\n> \n> On Tue, Sep 3, 2024 at 6:20 PM Tomas Vondra <tomas@vondra.me> wrote:\n>>\n>> On 9/3/24 17:06, Robert Haas wrote:\n>>> On Mon, Sep 2, 2024 at 1:46 PM Tomas Vondra <tomas@vondra.me> wrote:\n>>>> The one argument to not tie this to max_locks_per_transaction is the\n>>>> vastly different \"per element\" memory requirements. If you add one entry\n>>>> to max_locks_per_transaction, that adds LOCK which is a whopping 152B.\n>>>> OTOH one fast-path entry is ~5B, give or take. That's a pretty big\n>>>> difference, and it if the locks fit into the shared lock table, but\n>>>> you'd like to allow more fast-path locks, having to increase\n>>>> max_locks_per_transaction is not great - pretty wastefull.\n>>>>\n>>>> OTOH I'd really hate to just add another GUC and hope the users will\n>>>> magically know how to set it correctly. That's pretty unlikely, IMO. I\n>>>> myself wouldn't know what a good value is, I think.\n>>>>\n>>>> But say we add a GUC and set it to -1 by default, in which case it just\n>>>> inherits the max_locks_per_transaction value. And then also provide some\n>>>> basic metric about this fast-path cache, so that people can tune this?\n>>>\n>>> All things being equal, I would prefer not to add another GUC for\n>>> this, but we might need it.\n>>>\n>>\n>> Agreed.\n>>\n>> [..]\n>>\n>> So I think I'm OK with just tying this to max_locks_per_transaction.\n> \n> If that matters then the SLRU configurability effort added 7 GUCs\n> (with 3 scaling up based on shared_buffers) just to give high-end\n> users some relief, so here 1 new shouldn't be that such a deal. We\n> could add to the LWLock/lock_manager wait event docs to recommend just\n> using known-to-be-good certain values from this $thread (or ask the\n> user to benchmark it himself).\n> \n\nTBH I'm skeptical we'll be able to tune those GUCs. Maybe it was the\nright thing for the SLRU thread, I don't know - I haven't been following\nthat very closely. But my impression is that we often add a GUC when\nwe're not quite sure how to pick a good value. So we just shift the\nresponsibility to someone else, who however also doesn't know.\n\nI'd very much prefer not to do that here. Of course, it's challenging\nbecause we can't easily resize these arrays, so even if we had some nice\nheuristics to calculate the \"optimal\" number of fast-path slots, what\nwould we do with it ...\n\n>>>> I think just knowing the \"hit ratio\" would be enough, i.e. counters for\n>>>> how often it fits into the fast-path array, and how often we had to\n>>>> promote it to the shared lock table would be enough, no?\n>>>\n>>> Yeah, probably. I mean, that won't tell you how big it needs to be,\n>>> but it will tell you whether it's big enough.\n>>>\n>>\n>> True, but that applies to all \"cache hit ratio\" metrics (like for our\n>> shared buffers). It'd be great to have something better, enough to tell\n>> you how large the cache needs to be. But we don't :-(\n> \n> My $0.02 cents: the originating case that triggered those patches,\n> actually started with LWLock/lock_manager waits being the top#1. The\n> operator can cross check (join) that with a group by pg_locks.fastpath\n> (='f'), count(*). So, IMHO we have good observability in this case\n> (rare thing to say!)\n> \n\nThat's a good point. So if you had to give some instructions to users\nwhat to measure / monitor, and how to adjust the GUC based on that, what\nwould your instructions be?\n\n>>> I wonder if we should be looking at further improvements in the lock\n>>> manager of some kind. [..]\n>>\n>> Perhaps. I agree we'll probably need something more radical soon, not\n>> just changes that aim to fix some rare exceptional case (which may be\n>> annoying, but not particularly harmful for the complete workload).\n>>\n>> For example, if we did what you propose, that might help when very few\n>> transactions need a lot of locks. I don't mind saving memory in that\n>> case, ofc. but is it a problem if those rare cases are a bit slower?\n>> Shouldn't we focus more on cases where many locks are common? Because\n>> people are simply going to use partitioning, a lot of indexes, etc?\n>>\n>> So yeah, I agree we probably need a more fundamental rethink. I don't\n>> think we can just keep optimizing the current approach, there's a limit\n>> of fast it can be.\n> \n> Please help me understand: so are You both discussing potential far\n> future further improvements instead of this one ? My question is\n> really about: is the patchset good enough or are you considering some\n> other new effort instead?\n> \n\nI think it was mostly a brainstorming about alternative / additional\nimprovements in locking. The proposed patch does not change the locking\nin any fundamental way, it merely optimizes one piece - we still acquire\nexactly the same set of locks, exactly the same way.\n\nAFAICS there's an agreement the current approach has limits, and with\nthe growing number of partitions we're hitting them already. That may\nneed rethinking the fundamental approach, but I think that should not\nblock improvements to the current approach.\n\nNot to mention there's no proposal for such \"fundamental rework\" yet.\n\n> BTW some other random questions:\n> Q1. I've been lurking into\n> https://github.com/tvondra/pg-lock-scalability-results and those\n> shouldn't be used anymore for further discussions, as they contained\n> earlier patches (including\n> 0003-Add-a-memory-pool-with-adaptive-rebalancing.patch) and they were\n> replaced by benchmark data in this $thread, right?\n\nThe github results are still valid, I've only shared them 3 days ago. It\ndoes test both the mempool and glibc tuning, to assess (and compare) the\nbenefits of that, but why would that make it obsolete?\n\nBy \"results in this thread\" I suppose you mean the couple numbers I\nshared on September 2? Those were just very limited benchmarks to asses\nif making the arrays variable-length (based on GUC) would make things\nslower. And it doesn't, so the \"full\" github results still apply.\n\n> Q2. Earlier attempts did contain a mempool patch to get those nice\n> numbers (or was that jemalloc or glibc tuning). So were those recent\n> results in [1] collected with still 0003 or you have switched\n> completely to glibc/jemalloc tuning?\n> \n\nThe results pushed to github are all with glibc, and test four cases:\n\na) mempool patch not applied, no glibc tuning\nb) mempool patch applied, no glibc tuning\nc) mempool patch not applied, glibc tuning\nd) mempool patch applied, glibc tuning\n\nThese are the 4 \"column groups\" in some of the pivot tables, to allow\ncomparing those cases. My interpretation of the results are\n\n1) The mempool / glibc tuning have significant benefits, at least for\nsome workloads (where the locking patch alone does help much).\n\n2) There's very little difference between the mempool / glibc tuning.\nThe mempool does seem to have a small advantage.\n\n3) The mempool / glibc tuning is irrelevant for non-glibc systems (e.g.\nfor FreeBSD which I think uses jemalloc or something like that).\n\nI think the mempool might be interesting and useful for other reasons\n(e.g. I initially wrote it to enforce a per-backend memory limit), but\nyou can get mostly the same caching benefits by tuning the glibc parameters.\n\nSo I'm focusing on the locking stuff.\n\n\nregards\n\n-- \nTomas Vondra\n\n\n",
"msg_date": "Wed, 4 Sep 2024 13:15:49 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On Tue, 3 Sept 2024 at 18:20, Tomas Vondra <tomas@vondra.me> wrote:\n> FWIW the actual cost is somewhat higher, because we seem to need ~400B\n> for every lock (not just the 150B for the LOCK struct).\n\nWe do indeed allocate two PROCLOCKs for every LOCK, and allocate those\ninside dynahash tables. That amounts to (152+2*64+3*16=) 328 bytes in\ndynahash elements, and (3 * 8-16) = 24-48 bytes for the dynahash\nbuckets/segments, resulting in 352-376 bytes * NLOCKENTS() being\nused[^1]. Does that align with your usage numbers, or are they\nsignificantly larger?\n\n> At least based on a quick experiment. (Seems a bit high, right?).\n\nYeah, that does seem high, thanks for nerd-sniping me.\n\nThe 152 bytes of LOCK are mostly due to a combination of two\nMAX_LOCKMODES-sized int[]s that are used to keep track of the number\nof requested/granted locks of each level. As MAX_LOCKMODES = 10, these\narrays use a total of 2*4*10=80 bytes, with the remaining 72 spent on\ntracking. MAX_BACKENDS sadly doesn't fit in int16, so we'll have to\nkeep using int[]s, but that doesn't mean we can't improve this size:\n\nISTM that MAX_LOCKMODES is 2 larger than it has to be: LOCKMODE=0 is\nNoLock, which is never used or counted in these shared structures, and\nthe max lock mode supported by any of the supported lock methods is\nAccessExclusiveLock (8). We can thus reduce MAX_LOCKMODES to 8,\nreducing size of the LOCK struct by 16 bytes.\n\nIf some struct- and field packing is OK, then we could further reduce\nthe size of LOCK by an additional 8 bytes by resizing the LOCKMASK\ntype from int to int16 (we only use the first MaxLockMode (8) + 1\nbits), and then storing the grant/waitMask fields (now 4 bytes total)\nin the padding that's present at the end of the waitProcs struct. This\nwould depend on dclist not writing in its padding space, but I\ncouldn't find any user that did so, and most critically dclist_init\ndoesn't scribble in the padding with memset.\n\nIf these are both implemented, it would save 24 bytes, reducing the\nstruct to 128 bytes. :) [^2]\n\nI also checked PROCLOCK: If it is worth further packing the struct, we\nshould probably look at whether it's worth replacing the PGPROC* typed\nfields with ProcNumber -based ones, potentially in both PROCLOCK and\nPROCLOCKTAG. When combined with int16-typed LOCKMASKs, either one of\nthese fields being replaced with ProcNumber would allow a reduction in\nsize by one MAXALIGN quantum, reducing the struct to 56 bytes, the\nsmallest I could get it to without ignoring type alignments.\n\nFurther shmem savings can be achieved by reducing the \"10% safety\nmargin\" added at the end of LockShmemSize, as I'm fairly sure the\nmemory used in shared hashmaps doesn't exceed the estimated amount,\nand if it did then we should probably fix that part, rather than\nrequesting that (up to) 10% overhead here.\n\nAlltogether that'd save 40 bytes/lock entry on size, and ~35\nbytes/lock on \"safety margin\", for a saving of (up to) 19% of our\ncurrent allocation. I'm not sure if these tricks would benefit with\nperformance or even be a demerit, apart from smaller structs usually\nbeing better at fitting better in CPU caches.\n\n\nKind regards,\n\nMatthias van de Meent\nNeon (https://neon.tech)\n\n[^1] NLOCKENTS() benefits from being a power of 2, or slightly below\none, as it's rounded up to a power of 2 when dynahash decides its\nnumber of buckets to allocate.\n[^2] Sadly this 2-cachelines alignment is lost due to dynahash's\nHASHELEMENT prefix of elements. :(\n\n\n",
"msg_date": "Wed, 4 Sep 2024 16:25:31 +0200",
"msg_from": "Matthias van de Meent <boekewurm+postgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On Wed, 4 Sept 2024 at 03:06, Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> On Mon, Sep 2, 2024 at 1:46 PM Tomas Vondra <tomas@vondra.me> wrote:\n> > But say we add a GUC and set it to -1 by default, in which case it just\n> > inherits the max_locks_per_transaction value. And then also provide some\n> > basic metric about this fast-path cache, so that people can tune this?\n>\n> All things being equal, I would prefer not to add another GUC for\n> this, but we might need it.\n\nI think driving the array size from max_locks_per_transaction is a\ngood idea (rounded up to the next multiple of 16?). If someone comes\nalong one day and shows us a compelling case where some backend needs\nmore than its fair share of locks and performance is bad because of\nthat, then maybe we can consider adding a GUC then. Certainly, it's\nmuch easier to add a GUC later if someone convinces us that it's a\ngood idea than it is to add it now and try to take it away in the\nfuture if we realise it's not useful enough to keep.\n\nDavid\n\n\n",
"msg_date": "Thu, 5 Sep 2024 03:12:48 +1200",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On 9/4/24 16:25, Matthias van de Meent wrote:\n> On Tue, 3 Sept 2024 at 18:20, Tomas Vondra <tomas@vondra.me> wrote:\n>> FWIW the actual cost is somewhat higher, because we seem to need ~400B\n>> for every lock (not just the 150B for the LOCK struct).\n> \n> We do indeed allocate two PROCLOCKs for every LOCK, and allocate those\n> inside dynahash tables. That amounts to (152+2*64+3*16=) 328 bytes in\n> dynahash elements, and (3 * 8-16) = 24-48 bytes for the dynahash\n> buckets/segments, resulting in 352-376 bytes * NLOCKENTS() being\n> used[^1]. Does that align with your usage numbers, or are they\n> significantly larger?\n> \n\nI see more like ~470B per lock. If I patch CalculateShmemSize to log the\nshmem allocated, I get this:\n\n max_connections=100 max_locks_per_transaction=1000 => 194264001\n max_connections=100 max_locks_per_transaction=2000 => 241756967\n\nand (((241756967-194264001)/100/1000)) = 474\n\nCould be alignment of structs or something, not sure.\n\n>> At least based on a quick experiment. (Seems a bit high, right?).\n> \n> Yeah, that does seem high, thanks for nerd-sniping me.\n> \n> The 152 bytes of LOCK are mostly due to a combination of two\n> MAX_LOCKMODES-sized int[]s that are used to keep track of the number\n> of requested/granted locks of each level. As MAX_LOCKMODES = 10, these\n> arrays use a total of 2*4*10=80 bytes, with the remaining 72 spent on\n> tracking. MAX_BACKENDS sadly doesn't fit in int16, so we'll have to\n> keep using int[]s, but that doesn't mean we can't improve this size:\n> \n> ISTM that MAX_LOCKMODES is 2 larger than it has to be: LOCKMODE=0 is\n> NoLock, which is never used or counted in these shared structures, and\n> the max lock mode supported by any of the supported lock methods is\n> AccessExclusiveLock (8). We can thus reduce MAX_LOCKMODES to 8,\n> reducing size of the LOCK struct by 16 bytes.\n> \n> If some struct- and field packing is OK, then we could further reduce\n> the size of LOCK by an additional 8 bytes by resizing the LOCKMASK\n> type from int to int16 (we only use the first MaxLockMode (8) + 1\n> bits), and then storing the grant/waitMask fields (now 4 bytes total)\n> in the padding that's present at the end of the waitProcs struct. This\n> would depend on dclist not writing in its padding space, but I\n> couldn't find any user that did so, and most critically dclist_init\n> doesn't scribble in the padding with memset.\n> \n> If these are both implemented, it would save 24 bytes, reducing the\n> struct to 128 bytes. :) [^2]\n> \n> I also checked PROCLOCK: If it is worth further packing the struct, we\n> should probably look at whether it's worth replacing the PGPROC* typed\n> fields with ProcNumber -based ones, potentially in both PROCLOCK and\n> PROCLOCKTAG. When combined with int16-typed LOCKMASKs, either one of\n> these fields being replaced with ProcNumber would allow a reduction in\n> size by one MAXALIGN quantum, reducing the struct to 56 bytes, the\n> smallest I could get it to without ignoring type alignments.\n> \n> Further shmem savings can be achieved by reducing the \"10% safety\n> margin\" added at the end of LockShmemSize, as I'm fairly sure the\n> memory used in shared hashmaps doesn't exceed the estimated amount,\n> and if it did then we should probably fix that part, rather than\n> requesting that (up to) 10% overhead here.\n> \n> Alltogether that'd save 40 bytes/lock entry on size, and ~35\n> bytes/lock on \"safety margin\", for a saving of (up to) 19% of our\n> current allocation. I'm not sure if these tricks would benefit with\n> performance or even be a demerit, apart from smaller structs usually\n> being better at fitting better in CPU caches.\n> \n\nNot sure either, but it seems worth exploring. If you do an experimental\npatch for the LOCK size reduction, I can get some numbers.\n\nI'm not sure about the safety margins. 10% sure seems like quite a bit\nof memory (it might not have in the past, but as the instances are\ngrowing, that probably changed).\n\n\nregards\n\n-- \nTomas Vondra\n\n\n",
"msg_date": "Wed, 4 Sep 2024 17:32:55 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "\n\n\nOn 9/4/24 17:12, David Rowley wrote:\n> On Wed, 4 Sept 2024 at 03:06, Robert Haas <robertmhaas@gmail.com> wrote:\n>>\n>> On Mon, Sep 2, 2024 at 1:46 PM Tomas Vondra <tomas@vondra.me> wrote:\n>>> But say we add a GUC and set it to -1 by default, in which case it just\n>>> inherits the max_locks_per_transaction value. And then also provide some\n>>> basic metric about this fast-path cache, so that people can tune this?\n>>\n>> All things being equal, I would prefer not to add another GUC for\n>> this, but we might need it.\n> \n> I think driving the array size from max_locks_per_transaction is a\n> good idea (rounded up to the next multiple of 16?).\n\nMaybe, although I was thinking we'd just use the regular doubling, to\nget nice \"round\" numbers. It will likely overshoot a little bit (unless\npeople set the GUC to exactly 2^N), but I don't think that's a problem.\n\n> If someone comes along one day and shows us a compelling case where\n> some backend needs more than its fair share of locks and performance\n> is bad because of that, then maybe we can consider adding a GUC then.\n> Certainly, it's much easier to add a GUC later if someone convinces\n> us that it's a good idea than it is to add it now and try to take it\n> away in the future if we realise it's not useful enough to keep.\n> \n\nYeah, I agree with this.\n\n\n\nregards\n\n-- \nTomas Vondra\n\n\n",
"msg_date": "Wed, 4 Sep 2024 17:37:24 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On Tue, Sep 3, 2024 at 12:19 PM Tomas Vondra <tomas@vondra.me> wrote:\n> > Doing some worst case math, suppose somebody has max_connections=1000\n> > (which is near the upper limit of what I'd consider a sane setting)\n> > and max_locks_per_transaction=10000 (ditto). The product is 10\n> > million, so every 10 bytes of storage each a gigabyte of RAM. Chewing\n> > up 15GB of RAM when you could have chewed up only 0.5GB certainly\n> > isn't too great. On the other hand, those values are kind of pushing\n> > the limits of what is actually sane. If you imagine\n> > max_locks_per_transaction=2000 rather than\n> > max_locks_per_connection=10000, then it's only 3GB and that's\n> > hopefully not a lot on the hopefully-giant machine where you're\n> > running this.\n>\n> Yeah, although I don't quite follow the math. With 1000/10000 settings,\n> why would that eat 15GB of RAM? I mean, that's 1.5GB, right?\n\nOh, right.\n\n> FWIW the actual cost is somewhat higher, because we seem to need ~400B\n> for every lock (not just the 150B for the LOCK struct). At least based\n> on a quick experiment. (Seems a bit high, right?).\n\nHmm, yes, that's unpleasant.\n\n> Perhaps. I agree we'll probably need something more radical soon, not\n> just changes that aim to fix some rare exceptional case (which may be\n> annoying, but not particularly harmful for the complete workload).\n>\n> For example, if we did what you propose, that might help when very few\n> transactions need a lot of locks. I don't mind saving memory in that\n> case, ofc. but is it a problem if those rare cases are a bit slower?\n> Shouldn't we focus more on cases where many locks are common? Because\n> people are simply going to use partitioning, a lot of indexes, etc?\n>\n> So yeah, I agree we probably need a more fundamental rethink. I don't\n> think we can just keep optimizing the current approach, there's a limit\n> of fast it can be. Whether it's not locking individual partitions, or\n> not locking some indexes, ... I don't know.\n\nI don't know, either. We don't have to decide right now; it's just\nsomething to keep in mind.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n",
"msg_date": "Thu, 5 Sep 2024 12:25:27 -0400",
"msg_from": "Robert Haas <robertmhaas@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "Hi,\n\nHere's a bit more polished version of this patch series. I only propose\n0001 and 0002 for eventual commit, the two other bits are just stuff to\nhelp with benchmarking etc.\n\n0001\n----\nincreases the size of the arrays, but uses hard-coded number of groups\n(64, so 1024 locks) and leaves everything in PGPROC\n\n0002\n----\nAllocates that separately from PGPROC, and sets the number based on\nmax_locks_per_transactions\n\nI think 0001 and 0002 should be in fairly good shape, IMO. There's a\ncouple cosmetic things that bother me (e.g. the way it Asserts after\neach FAST_PATH_LOCK_REL_GROUP seems distracting).\n\nBut other than that I think it's fine, so a review / opinions would be\nvery welcome.\n\n\n0003\n----\nAdds a separate GUC to make benchmarking easier (without the impact of\nchanging the size of the lock table).\n\nI think the agreement is to not have a new GUC, unless it turns out to\nbe necessary in the future. So 0003 was just to make benchmarking a bit\neasier.\n\n\n0004\n----\nThis was a quick attempt to track the fraction of fast-path locks, and\nadding the infrastructure is mostly mechanical thing. But it turns out\nit's not quite trivial to track why a lock did not use fast-path. It\nmight have been because it wouldn't fit, or maybe it's not eligible, or\nmaybe there's a stronger lock. It's not obvious how to count these to\nhelp with evaluating the number of fast-path slots.\n\n\nregards\n\n-- \nTomas Vondra",
"msg_date": "Thu, 5 Sep 2024 19:21:01 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On 9/4/24 13:15, Tomas Vondra wrote:\n> On 9/4/24 11:29, Jakub Wartak wrote:\n>> Hi Tomas!\n>>\n>> ...\n>>\n>> My $0.02 cents: the originating case that triggered those patches,\n>> actually started with LWLock/lock_manager waits being the top#1. The\n>> operator can cross check (join) that with a group by pg_locks.fastpath\n>> (='f'), count(*). So, IMHO we have good observability in this case\n>> (rare thing to say!)\n>>\n> \n> That's a good point. So if you had to give some instructions to users\n> what to measure / monitor, and how to adjust the GUC based on that, what\n> would your instructions be?\n> \n\nAfter thinking about this a bit more, I'm actually wondering if this is\nsource of information is sufficient. Firstly, it's just a snapshot of a\nsingle instance, and it's not quite trivial to get some summary for\nlonger time period (people would have to sample it often enough, etc.).\nDoable, but much less convenient than the cumulative counters.\n\nBut for the sampling, doesn't this produce skewed data? Imagine you have\na workload with very short queries (which is when fast-path matters), so\nyou're likely to see the backend while it's obtaining the locks. If the\nfast-path locks take much faster acquire (kinda the whole point), we're\nmore likely to see the backend while it's obtaining the regular locks.\n\nLet's say the backend needs 1000 locks, and 500 of those fit into the\nfast-path array. We're likely to see the 500 fast-path locks already\nacquired, and a random fraction of the 500 non-fast-path locks. So in\nthe end you'll se backends needing 500 fast-path locks and 250 regular\nlocks. That doesn't seem terrible, but I guess the difference can be\nmade even larger.\n\n\nregards\n\n-- \nTomas Vondra\n\n\n",
"msg_date": "Thu, 5 Sep 2024 19:33:42 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On Thu, Sep 5, 2024 at 7:33 PM Tomas Vondra <tomas@vondra.me> wrote:\n\n>>> My $0.02 cents: the originating case that triggered those patches,\n>>> actually started with LWLock/lock_manager waits being the top#1. The\n>>> operator can cross check (join) that with a group by pg_locks.fastpath\n>>> (='f'), count(*). So, IMHO we have good observability in this case\n>>> (rare thing to say!)\n>>>\n>>\n>> That's a good point. So if you had to give some instructions to users\n>> what to measure / monitor, and how to adjust the GUC based on that, what\n>> would your instructions be?\n>>\n>\n> After thinking about this a bit more, I'm actually wondering if this is\n> source of information is sufficient. Firstly, it's just a snapshot of a\n> single instance, and it's not quite trivial to get some summary for\n> longer time period (people would have to sample it often enough, etc.).\n> Doable, but much less convenient than the cumulative counters.\n\nOK, so answering previous question:\n\nProbably just monitor pg_stat_activty (group on wait events count(*))\nwith pg_locks with group by on per-pid and fastpath . Even simple\nobservations with \\watch 0.1 are good enough to confirm/deny the\nroot-cause in practice even for short bursts while it is happening.\nWhile deploying monitoring for a longer time (with say sample of 1s),\nyou sooner or later would get the __high water mark__ and possibly\nallow up to that many fastpaths as starting point as there are locks\noccuring for affected PIDs (or double the amount).\n\n> But for the sampling, doesn't this produce skewed data? Imagine you have\n> a workload with very short queries (which is when fast-path matters), so\n> you're likely to see the backend while it's obtaining the locks. If the\n> fast-path locks take much faster acquire (kinda the whole point), we're\n> more likely to see the backend while it's obtaining the regular locks.\n>\n> Let's say the backend needs 1000 locks, and 500 of those fit into the\n> fast-path array. We're likely to see the 500 fast-path locks already\n> acquired, and a random fraction of the 500 non-fast-path locks. So in\n> the end you'll se backends needing 500 fast-path locks and 250 regular\n> locks. That doesn't seem terrible, but I guess the difference can be\n> made even larger.\n\n... it doesn't need to perfect data to act, right? We may just need\ninformation that it is happening (well we do). Maybe it's too\npragmatic point of view, but wasting some bits of memory for this, but\nstill being allowed to control it how much it allocates in the end --\nis much better situation than today, without any control where we are\nwasting crazy CPU time on all those futex() syscalls and context\nswitches\n\nAnother angle is that if you see the SQL causing it, it is most often\ngoing to be attributed to partitioning and people ending up accessing\nway too many partitions (thousands) without proper partition pruning -\nsometimes it even triggers re-partitioning of the said tables. So\nmaybe the realistic \"fastpath sizing\" should assume something that\nsupports:\na) usual number of tables in JOINs (just few of them are fine like today) -> ok\nb) interval 1 month partitions for let's say 5 years (12*5 = 60),\njoined to some other table like that gives like what, max 120? -> so\nif you have users doing SELECT * FROM such_table , they will already\nhave set the max_locks_per_xact probably to something higher.\nc) HASH partitioning up to VCPU-that-are-in-the-wild count? (say 64 or\n128? so it sounds same as above?)\nd) probably we should not care here at all if somebody wants daily\npartitioning across years with HASH (sub)partitions without partition\npruning -> it has nothing to do with being \"fast\" anyway\n\nJudging from the current reports, people have configured\nmax_locks_per_xact like this: ~75% have it at default (64), 10% has\n1024, 5% has 128 and the rest (~10%) is having between 100..thousands,\nwith extreme one-offs @ 25k (wild misconfiguration judging from the\nother specs).\n\nBTW: you probably need to register this $thread into CF for others to\nsee too (it's not there?)\n\n-J.\n\n\n",
"msg_date": "Fri, 6 Sep 2024 13:56:58 +0200",
"msg_from": "Jakub Wartak <jakub.wartak@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "Hi,\n\nI've spent quite a bit of time trying to identify cases where having\nmore fast-path lock slots could be harmful, without any luck. I started\nwith the EPYC machine I used for the earlier tests, but found nothing,\nexcept for a couple cases unrelated to this patch, because it affects\neven cases without the patch applied at all. More like random noise or\nmaybe some issue with the VM (or differences to the VM used earlier). I\npushed the results to githus [1] anyway, if anyone wants to look.\n\nSo I switched to my smaller machines, and ran a simple test on master,\nwith the hard-coded arrays, and with the arrays moves out of PGPROC (and\nsized per max_locks_per_transaction).\n\nI was looking for regressions, so I wanted to test a case that can't\nbenefit from fast-path locking, while paying the costs. So I decided to\ndo pgbench -S with 4 partitions, because that fits into the 16 slots we\nhad before, and scale 1 to keep everything in memory. And then did a\ncouple read-only runs, first with 64 locks/transaction (default), then\nwith 1024 locks/transaction.\n\nAttached is a shell script I used to collect this - it creates and\nremoves clusters, so be careful. Should be fairly obvious what it tests\nand how.\n\nThe results for max_locks_per_transaction=64 look like this (the numbers\nare throughput):\n\n\n machine mode clients master built-in with-guc\n ---------------------------------------------------------\n i5 prepared 1 14970 14991 14981\n 4 51638 51615 51388\n simple 1 14042 14136 14008\n 4 48705 48572 48457\n ------------------------------------------------------\n xeon prepared 1 13213 13330 13170\n 4 49280 49191 49263\n 16 151413 152268 151560\n simple 1 12250 12291 12316\n 4 45910 46148 45843\n 16 141774 142165 142310\n\nAnd compared to master\n\n machine mode clients built-in with-guc\n -------------------------------------------------\n i5 prepared 1 100.14% 100.08%\n 4 99.95% 99.51%\n simple 1 100.67% 99.76%\n 4 99.73% 99.49%\n ----------------------------------------------\n xeon prepared 1 100.89% 99.68%\n 4 99.82% 99.97%\n 16 100.56% 100.10%\n simple 1 100.34% 100.54%\n 4 100.52% 99.85%\n 16 100.28% 100.38%\n\nSo, no difference whatsoever - it's +/- 0.5%, well within random noise.\nAnd with max_locks_per_transaction=1024 the story is exactly the same:\n\n machine mode clients master built-in with-guc\n ---------------------------------------------------------\n i5 prepared 1 15000 14928 14948\n 4 51498 51351 51504\n simple 1 14124 14092 14065\n 4 48531 48517 48351\n xeon prepared 1 13384 13325 13290\n 4 49257 49309 49345\n 16 151668 151940 152201\n simple 1 12357 12351 12363\n 4 46039 46126 46201\n 16 141851 142402 142427\n\n\n machine mode clients built-in with-guc\n -------------------------------------------------\n i5 prepared 1 99.52% 99.65%\n 4 99.71% 100.01%\n simple 1 99.77% 99.58%\n 4 99.97% 99.63%\n xeon prepared 1 99.56% 99.30%\n 4 100.11% 100.18%\n 16 100.18% 100.35%\n simple 1 99.96% 100.05%\n 4 100.19% 100.35%\n 16 100.39% 100.41%\n\nwith max_locks_per_transaction=1024, it's fair to expect the fast-path\nlocking to be quite beneficial. Of course, it's possible the GUC is set\nthis high because of some rare issue (say, to run pg_dump, which needs\nto lock everything).\n\nI did look at docs if anything needs updating, but I don't think so. The\nSGML docs only talk about fast-path locking at fairly high level, not\nabout how many we have etc. Same for src/backend/storage/lmgr/README,\nwhich is focusing on the correctness of fast-path locking, and that's\nnot changed by this patch.\n\nI also cleaned up (removed) some of the Asserts checking that we got a\nvalid group / slot index. I don't think this really helped in practice,\nonce I added asserts to the macros.\n\n\nAnyway, at this point I'm quite happy with this improvement. I didn't\nhave any clear plan when to commit this, but I'm considering doing so\nsometime next week, unless someone objects or asks for some additional\nbenchmarks etc.\n\nOne thing I'm not quite sure about yet is whether to commit this as a\nsingle change, or the way the attached patches do that, with the first\npatch keeping the larger array in PGPROC and the second patch making it\nseparate and sized on max_locks_per_transaction ... Opinions?\n\n\n\nregards\n\n[1] https://github.com/tvondra/pg-lock-scalability-results\n\n-- \nTomas Vondra",
"msg_date": "Thu, 12 Sep 2024 23:40:47 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "Turns out there was a bug in EXEC_BACKEND mode, causing failures on the\nWindows machine in CI. AFAIK the reason is pretty simple - the backends\ndon't see the number of fast-path groups postmaster calculated from\nmax_locks_per_transaction.\n\nFixed that by calculating it again in AttachSharedMemoryStructs, which\nseems to have done the trick. With this the CI builds pass just fine,\nbut I'm not sure if EXEC_BACKENDS may have some other issues with the\nPGPROC changes. Could it happen that the shared memory gets mapped\ndifferently, in which case the pointers might need to be adjusted?\n\n\nregards\n\n-- \nTomas Vondra",
"msg_date": "Fri, 13 Sep 2024 01:44:58 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On Fri, Sep 13, 2024 at 1:45 AM Tomas Vondra <tomas@vondra.me> wrote:\n\n> [..]\n\n> Anyway, at this point I'm quite happy with this improvement. I didn't\n> have any clear plan when to commit this, but I'm considering doing so\n> sometime next week, unless someone objects or asks for some additional\n> benchmarks etc.\n\nThank you very much for working on this :)\n\nThe only fact that comes to my mind is that we could blow up L2\ncaches. Fun fact, so if we are growing PGPROC by 6.3x, that's going to\nbe like one or two 2MB huge pages more @ common max_connections=1000\nx86_64 (830kB -> ~5.1MB), and indeed:\n\n# without patch:\npostgres@hive:~$ /usr/pgsql18/bin/postgres -D /tmp/pg18 -C\nshared_memory_size_in_huge_pages\n177\n\n# with patch:\npostgres@hive:~$ /usr/pgsql18/bin/postgres -D /tmp/pg18 -C\nshared_memory_size_in_huge_pages\n178\n\nSo playing Devil's advocate , the worst situation that could possibly\nhurt (?) could be:\n* memory size of PGPROC working set >> L2_cache (thus very high\nmax_connections),\n* insane number of working sessions on CPU (sessions >> VCPU) - sadly\nhappens to some,\n* those sessions wouldn't have to be competing for the same Oids -\njust fetching this new big fpLockBits[] structure - so probing a lot\nfor lots of Oids, but *NOT* having to use futex() syscall [so not that\nsyscall price]\n* no huge pages (to cause dTLB misses)\n\nthen maybe(?) one could observe further degradation of dTLB misses in\nthe perf-stat counter under some microbenchmark, but measuring that\nrequires isolated and physical hardware. Maybe that would be actually\nnoise due to overhead of context-switches itself. Just trying to think\nout loud, what big PGPROC could cause here. But this is already an\nunhealthy and non-steady state of the system, so IMHO we are good,\nunless someone comes up with a better (more evil) idea.\n\n>> I did look at docs if anything needs updating, but I don't think so. The\nSGML docs only talk about fast-path locking at fairly high level, not\nabout how many we have etc.\n\nWell the only thing I could think of was to add to the\ndoc/src/sgml/config.sgml / \"max_locks_per_transaction\" GUC, that \"it\nis also used as advisory for the number of groups used in\nlockmanager's fast-path implementation\" (that is, without going into\nfurther discussion, as even pg_locks discussion\ndoc/src/sgml/system-views.sgml simply uses that term).\n\n-J.\n\n\n",
"msg_date": "Mon, 16 Sep 2024 15:11:31 +0200",
"msg_from": "Jakub Wartak <jakub.wartak@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "\n\nOn 9/16/24 15:11, Jakub Wartak wrote:\n> On Fri, Sep 13, 2024 at 1:45 AM Tomas Vondra <tomas@vondra.me> wrote:\n> \n>> [..]\n> \n>> Anyway, at this point I'm quite happy with this improvement. I didn't\n>> have any clear plan when to commit this, but I'm considering doing so\n>> sometime next week, unless someone objects or asks for some additional\n>> benchmarks etc.\n> \n> Thank you very much for working on this :)\n> \n> The only fact that comes to my mind is that we could blow up L2\n> caches. Fun fact, so if we are growing PGPROC by 6.3x, that's going to\n> be like one or two 2MB huge pages more @ common max_connections=1000\n> x86_64 (830kB -> ~5.1MB), and indeed:\n> \n> # without patch:\n> postgres@hive:~$ /usr/pgsql18/bin/postgres -D /tmp/pg18 -C\n> shared_memory_size_in_huge_pages\n> 177\n> \n> # with patch:\n> postgres@hive:~$ /usr/pgsql18/bin/postgres -D /tmp/pg18 -C\n> shared_memory_size_in_huge_pages\n> 178\n> \n> So playing Devil's advocate , the worst situation that could possibly\n> hurt (?) could be:\n> * memory size of PGPROC working set >> L2_cache (thus very high\n> max_connections),\n> * insane number of working sessions on CPU (sessions >> VCPU) - sadly\n> happens to some,\n> * those sessions wouldn't have to be competing for the same Oids -\n> just fetching this new big fpLockBits[] structure - so probing a lot\n> for lots of Oids, but *NOT* having to use futex() syscall [so not that\n> syscall price]\n> * no huge pages (to cause dTLB misses)\n> \n> then maybe(?) one could observe further degradation of dTLB misses in\n> the perf-stat counter under some microbenchmark, but measuring that\n> requires isolated and physical hardware. Maybe that would be actually\n> noise due to overhead of context-switches itself. Just trying to think\n> out loud, what big PGPROC could cause here. But this is already an\n> unhealthy and non-steady state of the system, so IMHO we are good,\n> unless someone comes up with a better (more evil) idea.\n> \n\nI've been thinking about such cases too, but I don't think it can really\nhappen in practice, because:\n\n- How likely is it that the sessions will need a lot of OIDs, but not\nthe same ones? Also, why would it matter that the OIDs are not the same,\nI don't think it matters unless one of the sessions needs an exclusive\nlock, at which point the optimization doesn't really matter.\n\n- If having more fast-path slots means it doesn't fit into L2 cache,\nwould we fit into L2 without it? I don't think so - if there really are\nthat many locks, we'd have to add those into the shared lock table, and\nthere's a lot of extra stuff to keep in memory (relcaches, ...).\n\nThis is pretty much one of the cases I focused on in my benchmarking,\nand I'm yet to see any regression.\n\n\n>>> I did look at docs if anything needs updating, but I don't think so. The\n> SGML docs only talk about fast-path locking at fairly high level, not\n> about how many we have etc.\n> \n> Well the only thing I could think of was to add to the\n> doc/src/sgml/config.sgml / \"max_locks_per_transaction\" GUC, that \"it\n> is also used as advisory for the number of groups used in\n> lockmanager's fast-path implementation\" (that is, without going into\n> further discussion, as even pg_locks discussion\n> doc/src/sgml/system-views.sgml simply uses that term).\n> \n\nThanks, I'll consider mentioning this in max_locks_per_transaction.\nAlso, I think there's a place calculating the amount of per-connection\nmemory, so maybe that needs to be updated too.\n\n\nregards\n\n-- \nTomas Vondra\n\n\n",
"msg_date": "Mon, 16 Sep 2024 16:19:29 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "I've spent the last couple days doing all kinds of experiments trying to\nfind regressions caused by the patch, but no success. Which is good.\n\nAttached is a script that just does a simple pgbench on a tiny table,\nwith no or very few partitions. The idea is that this will will fit into\nshared buffers (thus no I/O), and will fit into the 16 fast-path slots\nwe have now. It can't benefit from the patch - it can only get worse, if\nhaving more fast-path slots hurts.\n\nI ran this on my two machines, and in both cases the results are +/- 1%\nfrom the master for all combinations of parameters (clients, mode,\nnumber of partitions, ..). In most cases it's actually much closer,\nparticularly with the default max_locks_per_transaction value.\n\nFor higher values of the GUC, I think it's fine too - the differences\nare perhaps a bit larger (~1.5%), but it's clearly hardware specific (i5\ngets a bit faster, xeon a bit slower). And I'm pretty sure people who\nincreased that GUC value likely did that because of locking many rels,\nand so will actually benefit from the increased fast-path capacity.\n\n\nAt this point I'm pretty happy and confident the patch is fine. Unless\nsomeone objects, I'll get it committed after going over over it one more\ntime. I decided to commit that as as a single change - it would be weird\nto have an intermediate state with larger arrays in PGPROC, when that's\nnot something we actually want.\n\nI still haven't found any places in the docs that should mention this,\nexcept for the bit about max_locks_per_transaction GUC. There's nothing\nin SGML mentioning details of fast-path locking. I thought we have some\nformula to calculate per-connection memory, but I think I confused that\nwith the shmmem formulas we had in \"Managing Kernel Resources\". But even\nthat no longer mentions max_connections in master.\n\n\n\nregards\n\n-- \nTomas Vondra",
"msg_date": "Tue, 17 Sep 2024 22:16:04 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "Hi,\n\nI've finally pushed this, after many rounds of careful testing to ensure\nno regressions, and polishing. All changes since the version shared on\nSeptember 13 are only cosmetic - renaming a macro to keep it consistent\nwith the other ones, clarifying a couple comments etc. Nothing major.\n\nI ended up squashing the two parts into a single commit. I thought about\nkeeping the two steps, but it seemed pointless - the first part inflated\nthe PGPROC struct, which I didn't like to commit, even if only as an\nintermediate WIP state.\n\nSo far buildfarm didn't blew up, so let's hope it will stay that way.\n\nI just realized there's no CF entry for this - sorry about that :-( I\nstarted the thread a year ago to discuss an experimental patche, and it\nnever made it to CFA. But there was a discussion spanning a year, so\nhopefully that's enough.\n\n\nregards\n\n-- \nTomas Vondra\n\n\n",
"msg_date": "Sat, 21 Sep 2024 20:33:49 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On Sat, 21 Sept 2024 at 21:33, Tomas Vondra <tomas@vondra.me> wrote:\n> I've finally pushed this, after many rounds of careful testing to ensure\n> no regressions, and polishing. All changes since the version shared on\n> September 13 are only cosmetic - renaming a macro to keep it consistent\n> with the other ones, clarifying a couple comments etc. Nothing major.\n\nGreat work on this, I have seen multiple customers hitting fast path\ncapacity related LockManager contention. They will certainly be glad\nto have a fix available when they eventually upgrade. Regretfully I\ndid not find the time to participate in this discussion during\ndevelopment. But I did have some thoughts that I wanted to unload to\nthe list, not as a criticism, but in case it turns out follow up work\nis needed.\n\nDriving the array sizing from max_locks_per_transaction seems like a\ngood idea. The one major difference from the lock table is that while\nthe lock table is partitioned dynamically between backends, the fast\npath array has a static size per backend. One case where that\ndistinction matters is when only a fraction of backends try to lock\nlarge numbers of relations. This fraction will still fall back to main\nlock tables, but at least the contention should be limited by virtue\nof not having too many of those backends. The other case is when\nmax_connections is much higher than the number of backends actually\nused. Then backends may be consuming well over\nmax_locks_per_transaction without running into lock table capacity\nissues.\n\nIn both cases users will have the simple workaround of just increasing\nthe max_locks_per_transaction setting. Still, I'm sure they would be\nhappier if things just worked without any tuning. So I tried to figure\nout some scheme to get dynamic allocation of fast path locks.\n\nThe best data structure I came up with was to have a shared fast path\nlock array. Still partitioned as a 16-way associative cache, but\nindexed by hash(BackendId, RelationId). fpLockBits can be stuffed into\nthe high byte of BackendId thanks to MAX_BACKENDS. Locking could be\nhandled by one lock per way, or at least on cursory glance it\nshouldn't be too difficult to convert the whole fast path acquisition\nto be lock free.\n\nEither way, it feels like structuring the array this way could result\nin a large amount of false sharing of cache lines. Current static\nallocation means that each process needs to touch only a small set of\ncache lines only referenced by itself - quite probable to keep those\nlines in CPU local L2 in exclusive mode. In a shared array a larger\nnumber of cache lines are needed and they will be concurrently written\nto by other backends - lots of invalidation messages and cache line\nbouncing. I don't know how large this effect will be without doing a\nprototype and running it on a large machine with high core-to-core\nlatencies.\n\nIt would be possible to create a hybrid approach of a small local FP\narray servicing the majority of acquisitions with a larger shared\nvictim cache for exceptional cases. But it doesn't feel like it is\nworth the complexity. At least not without seeing some example\nworkloads where it would help. And even then, maybe using hierarchical\nlocking to do less work is the better approach.\n\nBeing optimistic, perhaps the current patch was enough to resolve the issue.\n\n--\nAnts Aasma\nSenior Database Engineer\nwww.cybertec-postgresql.com\n\n\n",
"msg_date": "Sun, 22 Sep 2024 11:50:31 +0300",
"msg_from": "Ants Aasma <ants.aasma@cybertec.at>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "\n\nOn 9/22/24 10:50, Ants Aasma wrote:\n> On Sat, 21 Sept 2024 at 21:33, Tomas Vondra <tomas@vondra.me> wrote:\n>> I've finally pushed this, after many rounds of careful testing to ensure\n>> no regressions, and polishing. All changes since the version shared on\n>> September 13 are only cosmetic - renaming a macro to keep it consistent\n>> with the other ones, clarifying a couple comments etc. Nothing major.\n> \n> Great work on this, I have seen multiple customers hitting fast path\n> capacity related LockManager contention. They will certainly be glad\n> to have a fix available when they eventually upgrade. Regretfully I\n> did not find the time to participate in this discussion during\n> development. But I did have some thoughts that I wanted to unload to\n> the list, not as a criticism, but in case it turns out follow up work\n> is needed.\n> \n> Driving the array sizing from max_locks_per_transaction seems like a\n> good idea. The one major difference from the lock table is that while\n> the lock table is partitioned dynamically between backends, the fast\n> path array has a static size per backend. One case where that\n> distinction matters is when only a fraction of backends try to lock\n> large numbers of relations. This fraction will still fall back to main\n> lock tables, but at least the contention should be limited by virtue\n> of not having too many of those backends. The other case is when\n> max_connections is much higher than the number of backends actually\n> used. Then backends may be consuming well over\n> max_locks_per_transaction without running into lock table capacity\n> issues.\n> \n\nI agree. I don't think the case with a couple lock-hungry backends\nmatters too much, because as you say there can't be too many of them, so\nthe contention should not be too bad. At least that was my reasoning.\n\nRegarding the case with very high max_connection values - I doubt we\nwant to optimize for that very much. Extremely high max_connection\nvalues are a clear anti-pattern (IMO), and if you choose to do that\nanyway, you simply have to accept that connections have costs. The\nmemory for fast-path locking is one of those costs.\n\nI'm not against improving that, ofc, but I think we should only do that\nif it doesn't hurt the \"reasonable\" setups.\n\n> In both cases users will have the simple workaround of just increasing\n> the max_locks_per_transaction setting. Still, I'm sure they would be\n> happier if things just worked without any tuning. So I tried to figure\n> out some scheme to get dynamic allocation of fast path locks.\n> \n\nI agree with the premise that less tuning is better. Which is why we\ntied this to max_locks_per_transaction.\n\n> The best data structure I came up with was to have a shared fast path\n> lock array. Still partitioned as a 16-way associative cache, but\n> indexed by hash(BackendId, RelationId). fpLockBits can be stuffed into\n> the high byte of BackendId thanks to MAX_BACKENDS. Locking could be\n> handled by one lock per way, or at least on cursory glance it\n> shouldn't be too difficult to convert the whole fast path acquisition\n> to be lock free.\n> \n> Either way, it feels like structuring the array this way could result\n> in a large amount of false sharing of cache lines. Current static\n> allocation means that each process needs to touch only a small set of\n> cache lines only referenced by itself - quite probable to keep those\n> lines in CPU local L2 in exclusive mode. In a shared array a larger\n> number of cache lines are needed and they will be concurrently written\n> to by other backends - lots of invalidation messages and cache line\n> bouncing. I don't know how large this effect will be without doing a\n> prototype and running it on a large machine with high core-to-core\n> latencies.\n> \n\nI don't have a very good intuition regarding cachelines. Ideally, the\nbackends would access disjunct parts of the array, so there should not\nbe a lot of false sharing. But maybe I'm wrong, hard to say without an\nexperimental patch.\n\n> It would be possible to create a hybrid approach of a small local FP\n> array servicing the majority of acquisitions with a larger shared\n> victim cache for exceptional cases. But it doesn't feel like it is\n> worth the complexity. At least not without seeing some example\n> workloads where it would help. And even then, maybe using hierarchical\n> locking to do less work is the better approach.\n> \n\nNot sure. My intuition would be to keep this as simple a possible.\nHaving a shared lock table and also a separate fast-path cache is\nalready sufficiently complex, adding cache for a cache seems a bit too\nmuch to me.\n\n> Being optimistic, perhaps the current patch was enough to resolve the issue.\n> \n\nIt's an improvement. But if you want to give the shared fast-path cache\na try, go ahead - if you write a patch, I promise to review it.\n\n\nregards\n\n-- \nTomas Vondra\n\n\n",
"msg_date": "Sun, 22 Sep 2024 14:14:21 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "Tomas Vondra <tomas@vondra.me> writes:\n> I've finally pushed this, after many rounds of careful testing to ensure\n> no regressions, and polishing.\n\nCoverity is not terribly happy with this. \"Assert(fpPtr = fpEndPtr);\"\nis very clearly not doing what you presumably intended. The others\nlook like overaggressive assertion checking. If you don't want those\nmacros to assume that the argument is unsigned, you could force the\nissue, say with\n\n #define FAST_PATH_GROUP(index)\t\\\n-\t(AssertMacro(((index) >= 0) && ((index) < FP_LOCK_SLOTS_PER_BACKEND)), \\\n+\t(AssertMacro((uint32) (index) < FP_LOCK_SLOTS_PER_BACKEND), \\\n \t ((index) / FP_LOCK_SLOTS_PER_GROUP))\n\n\n________________________________________________________________________________________________________\n*** CID 1619664: Incorrect expression (ASSERT_SIDE_EFFECT)\n/srv/coverity/git/pgsql-git/postgresql/src/backend/storage/lmgr/proc.c: 325 in InitProcGlobal()\n319 \t\tpg_atomic_init_u32(&(proc->procArrayGroupNext), INVALID_PROC_NUMBER);\n320 \t\tpg_atomic_init_u32(&(proc->clogGroupNext), INVALID_PROC_NUMBER);\n321 \t\tpg_atomic_init_u64(&(proc->waitStart), 0);\n322 \t}\n323 \n324 \t/* Should have consumed exactly the expected amount of fast-path memory. */\n>>> CID 1619664: Incorrect expression (ASSERT_SIDE_EFFECT)\n>>> Assignment \"fpPtr = fpEndPtr\" has a side effect. This code will work differently in a non-debug build.\n325 \tAssert(fpPtr = fpEndPtr);\n326 \n327 \t/*\n328 \t * Save pointers to the blocks of PGPROC structures reserved for auxiliary\n329 \t * processes and prepared transactions.\n330 \t */\n\n________________________________________________________________________________________________________\n*** CID 1619662: Integer handling issues (NO_EFFECT)\n/srv/coverity/git/pgsql-git/postgresql/src/backend/storage/lmgr/lock.c: 3731 in GetLockStatusData()\n3725 \n3726 \t\tLWLockAcquire(&proc->fpInfoLock, LW_SHARED);\n3727 \n3728 \t\tfor (f = 0; f < FP_LOCK_SLOTS_PER_BACKEND; ++f)\n3729 \t\t{\n3730 \t\t\tLockInstanceData *instance;\n>>> CID 1619662: Integer handling issues (NO_EFFECT)\n>>> This greater-than-or-equal-to-zero comparison of an unsigned value is always true. \"f >= 0U\".\n3731 \t\t\tuint32\t\tlockbits = FAST_PATH_GET_BITS(proc, f);\n3732 \n3733 \t\t\t/* Skip unallocated slots. */\n3734 \t\t\tif (!lockbits)\n3735 \t\t\t\tcontinue;\n3736 \n\n________________________________________________________________________________________________________\n*** CID 1619661: Integer handling issues (NO_EFFECT)\n/srv/coverity/git/pgsql-git/postgresql/src/backend/storage/lmgr/lock.c: 2696 in FastPathGrantRelationLock()\n2690 \tuint32\t\tgroup = FAST_PATH_REL_GROUP(relid);\n2691 \n2692 \t/* Scan for existing entry for this relid, remembering empty slot. */\n2693 \tfor (i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)\n2694 \t{\n2695 \t\t/* index into the whole per-backend array */\n>>> CID 1619661: Integer handling issues (NO_EFFECT)\n>>> This greater-than-or-equal-to-zero comparison of an unsigned value is always true. \"group >= 0U\".\n2696 \t\tuint32\t\tf = FAST_PATH_SLOT(group, i);\n2697 \n2698 \t\tif (FAST_PATH_GET_BITS(MyProc, f) == 0)\n2699 \t\t\tunused_slot = f;\n2700 \t\telse if (MyProc->fpRelId[f] == relid)\n2701 \t\t{\n\n________________________________________________________________________________________________________\n*** CID 1619660: Integer handling issues (NO_EFFECT)\n/srv/coverity/git/pgsql-git/postgresql/src/backend/storage/lmgr/lock.c: 2813 in FastPathTransferRelationLocks()\n2807 \n2808 \t\tfor (j = 0; j < FP_LOCK_SLOTS_PER_GROUP; j++)\n2809 \t\t{\n2810 \t\t\tuint32\t\tlockmode;\n2811 \n2812 \t\t\t/* index into the whole per-backend array */\n>>> CID 1619660: Integer handling issues (NO_EFFECT)\n>>> This greater-than-or-equal-to-zero comparison of an unsigned value is always true. \"group >= 0U\".\n2813 \t\t\tuint32\t\tf = FAST_PATH_SLOT(group, j);\n2814 \n2815 \t\t\t/* Look for an allocated slot matching the given relid. */\n2816 \t\t\tif (relid != proc->fpRelId[f] || FAST_PATH_GET_BITS(proc, f) == 0)\n2817 \t\t\t\tcontinue;\n2818 \n\n________________________________________________________________________________________________________\n*** CID 1619659: Integer handling issues (NO_EFFECT)\n/srv/coverity/git/pgsql-git/postgresql/src/backend/storage/lmgr/lock.c: 3067 in GetLockConflicts()\n3061 \n3062 \t\t\tfor (j = 0; j < FP_LOCK_SLOTS_PER_GROUP; j++)\n3063 \t\t\t{\n3064 \t\t\t\tuint32\t\tlockmask;\n3065 \n3066 \t\t\t\t/* index into the whole per-backend array */\n>>> CID 1619659: Integer handling issues (NO_EFFECT)\n>>> This greater-than-or-equal-to-zero comparison of an unsigned value is always true. \"group >= 0U\".\n3067 \t\t\t\tuint32\t\tf = FAST_PATH_SLOT(group, j);\n3068 \n3069 \t\t\t\t/* Look for an allocated slot matching the given relid. */\n3070 \t\t\t\tif (relid != proc->fpRelId[f])\n3071 \t\t\t\t\tcontinue;\n3072 \t\t\t\tlockmask = FAST_PATH_GET_BITS(proc, f);\n\n________________________________________________________________________________________________________\n*** CID 1619658: Integer handling issues (NO_EFFECT)\n/srv/coverity/git/pgsql-git/postgresql/src/backend/storage/lmgr/lock.c: 2739 in FastPathUnGrantRelationLock()\n2733 \tuint32\t\tgroup = FAST_PATH_REL_GROUP(relid);\n2734 \n2735 \tFastPathLocalUseCounts[group] = 0;\n2736 \tfor (i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)\n2737 \t{\n2738 \t\t/* index into the whole per-backend array */\n>>> CID 1619658: Integer handling issues (NO_EFFECT)\n>>> This greater-than-or-equal-to-zero comparison of an unsigned value is always true. \"group >= 0U\".\n2739 \t\tuint32\t\tf = FAST_PATH_SLOT(group, i);\n2740 \n2741 \t\tif (MyProc->fpRelId[f] == relid\n2742 \t\t\t&& FAST_PATH_CHECK_LOCKMODE(MyProc, f, lockmode))\n2743 \t\t{\n2744 \t\t\tAssert(!result);\n\n________________________________________________________________________________________________________\n*** CID 1619657: Integer handling issues (NO_EFFECT)\n/srv/coverity/git/pgsql-git/postgresql/src/backend/storage/lmgr/lock.c: 2878 in FastPathGetRelationLockEntry()\n2872 \n2873 \tfor (i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)\n2874 \t{\n2875 \t\tuint32\t\tlockmode;\n2876 \n2877 \t\t/* index into the whole per-backend array */\n>>> CID 1619657: Integer handling issues (NO_EFFECT)\n>>> This greater-than-or-equal-to-zero comparison of an unsigned value is always true. \"group >= 0U\".\n2878 \t\tuint32\t\tf = FAST_PATH_SLOT(group, i);\n2879 \n2880 \t\t/* Look for an allocated slot matching the given relid. */\n2881 \t\tif (relid != MyProc->fpRelId[f] || FAST_PATH_GET_BITS(MyProc, f) == 0)\n2882 \t\t\tcontinue;\n2883 \n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Sun, 22 Sep 2024 11:45:59 -0400",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On 9/22/24 17:45, Tom Lane wrote:\n> Tomas Vondra <tomas@vondra.me> writes:\n>> I've finally pushed this, after many rounds of careful testing to ensure\n>> no regressions, and polishing.\n> \n> Coverity is not terribly happy with this. \"Assert(fpPtr = fpEndPtr);\"\n> is very clearly not doing what you presumably intended. The others\n> look like overaggressive assertion checking. If you don't want those\n> macros to assume that the argument is unsigned, you could force the\n> issue, say with\n> \n> #define FAST_PATH_GROUP(index)\t\\\n> -\t(AssertMacro(((index) >= 0) && ((index) < FP_LOCK_SLOTS_PER_BACKEND)), \\\n> +\t(AssertMacro((uint32) (index) < FP_LOCK_SLOTS_PER_BACKEND), \\\n> \t ((index) / FP_LOCK_SLOTS_PER_GROUP))\n> \n\nAh, you're right. I'll fix those asserts tomorrow.\n\nThe first is clearly wrong, of course.\n\nFor the (x >= 0) asserts, doing it this way relies on negative values\nwrapping to large positive ones, correct? AFAIK it's guaranteed to be a\nvery large value, so it can't accidentally be less than the slot count.\n\n\nregards\n\n-- \nTomas Vondra\n\n\n",
"msg_date": "Mon, 23 Sep 2024 00:50:41 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "Tomas Vondra <tomas@vondra.me> writes:\n> On 9/22/24 17:45, Tom Lane wrote:\n>> #define FAST_PATH_GROUP(index)\t\\\n>> -\t(AssertMacro(((index) >= 0) && ((index) < FP_LOCK_SLOTS_PER_BACKEND)), \\\n>> +\t(AssertMacro((uint32) (index) < FP_LOCK_SLOTS_PER_BACKEND), \\\n>> ((index) / FP_LOCK_SLOTS_PER_GROUP))\n\n> For the (x >= 0) asserts, doing it this way relies on negative values\n> wrapping to large positive ones, correct? AFAIK it's guaranteed to be a\n> very large value, so it can't accidentally be less than the slot count.\n\nRight, any negative value would wrap to something more than\nINT32_MAX.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Sun, 22 Sep 2024 19:06:46 -0400",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On Mon, Sep 16, 2024 at 4:19 PM Tomas Vondra <tomas@vondra.me> wrote:\n> On 9/16/24 15:11, Jakub Wartak wrote:\n> > On Fri, Sep 13, 2024 at 1:45 AM Tomas Vondra <tomas@vondra.me> wrote:\n> >\n> >> [..]\n> >\n> >> Anyway, at this point I'm quite happy with this improvement. I didn't\n> >> have any clear plan when to commit this, but I'm considering doing so\n> >> sometime next week, unless someone objects or asks for some additional\n> >> benchmarks etc.\n> >\n> > Thank you very much for working on this :)\n> >\n> > The only fact that comes to my mind is that we could blow up L2\n> > caches. Fun fact, so if we are growing PGPROC by 6.3x, that's going to\n> > be like one or two 2MB huge pages more @ common max_connections=1000\n> > x86_64 (830kB -> ~5.1MB), and indeed:\n[..]\n> > then maybe(?) one could observe further degradation of dTLB misses in\n> > the perf-stat counter under some microbenchmark, but measuring that\n> > requires isolated and physical hardware. Maybe that would be actually\n> > noise due to overhead of context-switches itself. Just trying to think\n> > out loud, what big PGPROC could cause here. But this is already an\n> > unhealthy and non-steady state of the system, so IMHO we are good,\n> > unless someone comes up with a better (more evil) idea.\n> >\n>\n> I've been thinking about such cases too, but I don't think it can really\n> happen in practice, because:\n>\n> - How likely is it that the sessions will need a lot of OIDs, but not\n> the same ones? Also, why would it matter that the OIDs are not the same,\n> I don't think it matters unless one of the sessions needs an exclusive\n> lock, at which point the optimization doesn't really matter.\n>\n> - If having more fast-path slots means it doesn't fit into L2 cache,\n> would we fit into L2 without it? I don't think so - if there really are\n> that many locks, we'd have to add those into the shared lock table, and\n> there's a lot of extra stuff to keep in memory (relcaches, ...).\n>\n> This is pretty much one of the cases I focused on in my benchmarking,\n> and I'm yet to see any regression.\n\nSorry for answering this so late. Just for context here: I was\nimagining a scenario with high max_connections about e.g. schema-based\nmulti-tenancy and no partitioning (so all would be fine without this\n$thread/commit ; so under 16 (fast)locks would be taken). The OIDs\nneed to be different to avoid contention: so that futex() does not end\nup really in syscall (just user-space part). My theory was that a much\nsmaller PGPROC should be doing much less (data) cache-line fetches\nthan with-the-patch. That hash() % prime , hits various parts of a\nlarger array - so without patch should be quicker as it wouldn't be\nrandomly hitting some larger array[], but it might be noise as you\nstate. It was a theoretical attempt at crafting the worst possible\nconditions for the patch, so feel free to disregard as it already\nassumes some anti-pattern (big & all active max_connections).\n\n> > Well the only thing I could think of was to add to the\n> > doc/src/sgml/config.sgml / \"max_locks_per_transaction\" GUC, that \"it\n> > is also used as advisory for the number of groups used in\n> > lockmanager's fast-path implementation\" (that is, without going into\n> > further discussion, as even pg_locks discussion\n> > doc/src/sgml/system-views.sgml simply uses that term).\n> >\n>\n> Thanks, I'll consider mentioning this in max_locks_per_transaction.\n> Also, I think there's a place calculating the amount of per-connection\n> memory, so maybe that needs to be updated too.\n>\n\nI couldn't find it in current versions, but maybe that's helpful/reaffirming:\n- up to 9.2. there were exact formulas used, see \"(1800 + 270 *\nmax_locks_per_transaction) * max_connections\" [1] , that's a long time\ngone now.\n- if anything then Andres might want to improve a little his blog\nentry: [1] (my take is that is seems to be the most accurate and\nauthoritative technical information that we have online)\n\n-J.\n\n[1] - https://www.postgresql.org/docs/9.2/kernel-resources.html\n[2] - https://blog.anarazel.de/2020/10/07/measuring-the-memory-overhead-of-a-postgres-connection/\n\n\n",
"msg_date": "Mon, 23 Sep 2024 12:02:24 +0200",
"msg_from": "Jakub Wartak <jakub.wartak@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "On 9/23/24 01:06, Tom Lane wrote:\n> Tomas Vondra <tomas@vondra.me> writes:\n>> On 9/22/24 17:45, Tom Lane wrote:\n>>> #define FAST_PATH_GROUP(index)\t\\\n>>> -\t(AssertMacro(((index) >= 0) && ((index) < FP_LOCK_SLOTS_PER_BACKEND)), \\\n>>> +\t(AssertMacro((uint32) (index) < FP_LOCK_SLOTS_PER_BACKEND), \\\n>>> ((index) / FP_LOCK_SLOTS_PER_GROUP))\n> \n>> For the (x >= 0) asserts, doing it this way relies on negative values\n>> wrapping to large positive ones, correct? AFAIK it's guaranteed to be a\n>> very large value, so it can't accidentally be less than the slot count.\n> \n> Right, any negative value would wrap to something more than\n> INT32_MAX.\n> \n\nThanks. Pushed a fix for these issues, hopefully coverity will be happy.\n\nBTW is the coverity report accessible somewhere? I know someone\nmentioned that in the past, but I don't recall the details. Maybe we\nshould have a list of all these resources, useful for committers,\nsomewhere on the wiki?\n\n\nregards\n\n-- \nTomas Vondra\n\n\n",
"msg_date": "Mon, 23 Sep 2024 12:26:40 +0200",
"msg_from": "Tomas Vondra <tomas@vondra.me>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
},
{
"msg_contents": "Tomas Vondra <tomas@vondra.me> writes:\n> Thanks. Pushed a fix for these issues, hopefully coverity will be happy.\n\nThanks.\n\n> BTW is the coverity report accessible somewhere? I know someone\n> mentioned that in the past, but I don't recall the details. Maybe we\n> should have a list of all these resources, useful for committers,\n> somewhere on the wiki?\n\nCurrently those reports only go to the security team. Perhaps\nwe should rethink that?\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Mon, 23 Sep 2024 10:37:16 -0400",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: scalability bottlenecks with (many) partitions (and more)"
}
] |
[
{
"msg_contents": "In [1] we've reached a conclusion that for a MATERIALIZED CTE it's okay\nto 'allow our statistics or guesses for the sub-query to subsequently\ninfluence what the upper planner does'. Commit f7816aec23 exposes\ncolumn statistics to the upper planner. In the light of that, here is a\npatch that exposes info about the ordering of the CTE result to the\nupper planner.\n\nThis patch was initially posted in that same thread and has received\nsome comments from Tom in [2]. Due to the presence of multiple patches\nin that thread, it has led to confusion. So fork a new thread here\nspecifically dedicated to discussing the patch about exposing pathkeys\nfrom CTEs to the upper planner.\n\nComments/thoughts?\n\n[1] https://www.postgresql.org/message-id/482957.1700192299%40sss.pgh.pa.us\n[2] https://www.postgresql.org/message-id/1339607.1700502358%40sss.pgh.pa.us\n\nThanks\nRichard",
"msg_date": "Mon, 29 Jan 2024 11:18:51 +0800",
"msg_from": "Richard Guo <guofenglinux@gmail.com>",
"msg_from_op": true,
"msg_subject": "Propagate pathkeys from CTEs up to the outer query"
},
{
"msg_contents": "On 29/1/2024 10:18, Richard Guo wrote:\n> In [1] we've reached a conclusion that for a MATERIALIZED CTE it's okay\n> to 'allow our statistics or guesses for the sub-query to subsequently\n> influence what the upper planner does'. Commit f7816aec23 exposes\n> column statistics to the upper planner. In the light of that, here is a\n> patch that exposes info about the ordering of the CTE result to the\n> upper planner.\n> \n> This patch was initially posted in that same thread and has received\n> some comments from Tom in [2]. Due to the presence of multiple patches\n> in that thread, it has led to confusion. So fork a new thread here\n> specifically dedicated to discussing the patch about exposing pathkeys\n> from CTEs to the upper planner.\nI like this approach. It looks good initially, but such features need \nmore opinions/views/time to analyse corner cases.\nIt goes alongside my current backburner - pull parameterisation through \nthe GROUP-BY and the query block fence up to the JOIN searching code of \nthe parent query.\n\n-- \nregards,\nAndrei Lepikhov\nPostgres Professional\n\n\n\n",
"msg_date": "Wed, 14 Feb 2024 13:18:02 +0700",
"msg_from": "Andrei Lepikhov <a.lepikhov@postgrespro.ru>",
"msg_from_op": false,
"msg_subject": "Re: Propagate pathkeys from CTEs up to the outer query"
},
{
"msg_contents": "Richard Guo <guofenglinux@gmail.com> writes:\n> This patch was initially posted in that same thread and has received\n> some comments from Tom in [2]. Due to the presence of multiple patches\n> in that thread, it has led to confusion. So fork a new thread here\n> specifically dedicated to discussing the patch about exposing pathkeys\n> from CTEs to the upper planner.\n\nI got around to looking at this finally. I was a bit surprised by\nyour choice of data structure. You made a per-CTE-item cte_paths\nlist paralleling cte_plan_ids, but what I had had in mind was a\nper-subplan list of paths paralleling glob->subplans and subroots.\nThis would mean that the code for ordinary SubqueryScans would\nalso need to fill in that list, but surely that's a trivial cost\ncompared to everything else we do to prepare a subplan. I don't\nthink that we have any immediate need to remember that info for\nan ordinary SubqueryScan, but it seems plausible that we will\nin future. Also, I'm not sure that a Path is fully interpretable\nwithout the associated PlannerInfo (subroot), so keeping it\nbeside the list of subroots seems more future-proof than dissociating\nit from that. This approach would also be more amenable to postponing\ncreation of the subplans, as we speculated about earlier. (I have\nno near-term desire to actually do that, but maybe someday it will\nhappen.)\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Mon, 25 Mar 2024 13:39:18 -0400",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Propagate pathkeys from CTEs up to the outer query"
},
{
"msg_contents": "On Tue, Mar 26, 2024 at 1:39 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> I got around to looking at this finally. I was a bit surprised by\n> your choice of data structure. You made a per-CTE-item cte_paths\n> list paralleling cte_plan_ids, but what I had had in mind was a\n> per-subplan list of paths paralleling glob->subplans and subroots.\n> This would mean that the code for ordinary SubqueryScans would\n> also need to fill in that list, but surely that's a trivial cost\n> compared to everything else we do to prepare a subplan. I don't\n> think that we have any immediate need to remember that info for\n> an ordinary SubqueryScan, but it seems plausible that we will\n> in future. Also, I'm not sure that a Path is fully interpretable\n> without the associated PlannerInfo (subroot), so keeping it\n> beside the list of subroots seems more future-proof than dissociating\n> it from that. This approach would also be more amenable to postponing\n> creation of the subplans, as we speculated about earlier. (I have\n> no near-term desire to actually do that, but maybe someday it will\n> happen.)\n\n\nI agree with your points. Previously I was thinking that CTEs were the\nonly scenario where we needed to remember the best path and only\nrequired the best path's pathkeys. However, considering potential\nfuture use cases as you mentioned, I concur that having a per-subplan\nlist of paths would be more future-proof. Please see attached v4 patch.\n\nThanks\nRichard",
"msg_date": "Tue, 26 Mar 2024 14:27:37 +0800",
"msg_from": "Richard Guo <guofenglinux@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Propagate pathkeys from CTEs up to the outer query"
},
{
"msg_contents": "Richard Guo <guofenglinux@gmail.com> writes:\n> I agree with your points. Previously I was thinking that CTEs were the\n> only scenario where we needed to remember the best path and only\n> required the best path's pathkeys. However, considering potential\n> future use cases as you mentioned, I concur that having a per-subplan\n> list of paths would be more future-proof. Please see attached v4 patch.\n\nHm, well, you didn't actually fill in the paths for the other\nsubqueries. I agree that it's not worth doing so in\nSS_make_initplan_from_plan, but a comment explaining that decision\nseems in order. Also, there's nothing stopping us from saving the\npath for subplans made in build_subplan, except adding a parameter\nto pass them down. So I did that, and made a couple other cosmetic\nchanges, and pushed it.\n\nOne thing I noticed while testing is that while your regression-test\nquery successfully propagates the pathkeys:\n\nregression=# explain with x as materialized (select unique1 from tenk1 b order by unique1)\nselect count(*) from tenk1 a\n where unique1 in (select * from x);\n QUERY PLAN \n----------------------------------------------------------------------------------------------------\n Aggregate (cost=915.55..915.56 rows=1 width=8)\n CTE x\n -> Index Only Scan using tenk1_unique1 on tenk1 b (cost=0.29..270.29 rows=10000 width=4)\n -> Merge Semi Join (cost=0.31..620.26 rows=10000 width=0)\n Merge Cond: (a.unique1 = x.unique1)\n -> Index Only Scan using tenk1_unique1 on tenk1 a (cost=0.29..270.29 rows=10000 width=4)\n -> CTE Scan on x (cost=0.00..200.00 rows=10000 width=4)\n(7 rows)\n\nthis variant doesn't:\n\nregression=# explain with x as materialized (select unique1 from tenk1 b)\nselect count(*) from tenk1 a\n where unique1 in (select * from x);\n QUERY PLAN \n----------------------------------------------------------------------------------------------------\n Aggregate (cost=1028.07..1028.08 rows=1 width=8)\n CTE x\n -> Index Only Scan using tenk1_unique1 on tenk1 b (cost=0.29..270.29 rows=10000 width=4)\n -> Hash Semi Join (cost=325.28..732.78 rows=10000 width=0)\n Hash Cond: (a.unique1 = x.unique1)\n -> Index Only Scan using tenk1_unique1 on tenk1 a (cost=0.29..270.29 rows=10000 width=4)\n -> Hash (cost=200.00..200.00 rows=10000 width=4)\n -> CTE Scan on x (cost=0.00..200.00 rows=10000 width=4)\n(8 rows)\n\nThat's not the fault of anything we did here; the IndexOnlyScan path\nin the subquery is in fact not marked with any pathkeys, even though\nclearly its result is sorted. I believe that's an intentional\ndecision from way way back, that pathkeys only correspond to orderings\nthat are of interest in the current query level. \"select unique1 from\ntenk1 b order by unique1\" has an interest in ordering by unique1,\nbut \"select unique1 from tenk1 b\" does not, so it's choosing that\npath strictly according to cost. Not generating pathkeys in such a\nquery saves a few cycles and ensures that we won't improperly prefer\na path on the basis of pathkeys if it hasn't got a cost advantage.\nSo I'm quite hesitant to muck with that old decision, especially in\nthe waning days of a development cycle, but the results do feel a\nlittle strange here.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Tue, 26 Mar 2024 13:20:06 -0400",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Propagate pathkeys from CTEs up to the outer query"
},
{
"msg_contents": "On Wed, Mar 27, 2024 at 1:20 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Richard Guo <guofenglinux@gmail.com> writes:\n> > I agree with your points. Previously I was thinking that CTEs were the\n> > only scenario where we needed to remember the best path and only\n> > required the best path's pathkeys. However, considering potential\n> > future use cases as you mentioned, I concur that having a per-subplan\n> > list of paths would be more future-proof. Please see attached v4 patch.\n>\n> Hm, well, you didn't actually fill in the paths for the other\n> subqueries. I agree that it's not worth doing so in\n> SS_make_initplan_from_plan, but a comment explaining that decision\n> seems in order. Also, there's nothing stopping us from saving the\n> path for subplans made in build_subplan, except adding a parameter\n> to pass them down. So I did that, and made a couple other cosmetic\n> changes, and pushed it.\n\n\nThanks for the adjustments and pushing!\n\n\n> That's not the fault of anything we did here; the IndexOnlyScan path\n> in the subquery is in fact not marked with any pathkeys, even though\n> clearly its result is sorted. I believe that's an intentional\n> decision from way way back, that pathkeys only correspond to orderings\n> that are of interest in the current query level. \"select unique1 from\n> tenk1 b order by unique1\" has an interest in ordering by unique1,\n> but \"select unique1 from tenk1 b\" does not, so it's choosing that\n> path strictly according to cost. Not generating pathkeys in such a\n> query saves a few cycles and ensures that we won't improperly prefer\n> a path on the basis of pathkeys if it hasn't got a cost advantage.\n> So I'm quite hesitant to muck with that old decision, especially in\n> the waning days of a development cycle, but the results do feel a\n> little strange here.\n\n\nYeah, I also noticed this while writing the test case. That's why I\nadded 'order by unique1' explicitly in the CTE subquery. This also\nhappens to subquery RTEs, such as\n\nexplain (costs off)\nselect * from (select unique1 from tenk1 offset 0) order by unique1;\n QUERY PLAN\n----------------------------------------------------\n Sort\n Sort Key: tenk1.unique1\n -> Index Only Scan using tenk1_unique1 on tenk1\n(3 rows)\n\nI agree that mucking with the old decision might not be a good idea. In\naddition, for a MATERIALIZED CTE, generating pathkeys according to the\nouter query's ordering requirements breaks the idea of optimization\nfence: the outer query should not affect the plan chosen for the CTE\nquery.\n\nThanks\nRichard\n\nOn Wed, Mar 27, 2024 at 1:20 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:Richard Guo <guofenglinux@gmail.com> writes:\n> I agree with your points. Previously I was thinking that CTEs were the\n> only scenario where we needed to remember the best path and only\n> required the best path's pathkeys. However, considering potential\n> future use cases as you mentioned, I concur that having a per-subplan\n> list of paths would be more future-proof. Please see attached v4 patch.\n\nHm, well, you didn't actually fill in the paths for the other\nsubqueries. I agree that it's not worth doing so in\nSS_make_initplan_from_plan, but a comment explaining that decision\nseems in order. Also, there's nothing stopping us from saving the\npath for subplans made in build_subplan, except adding a parameter\nto pass them down. So I did that, and made a couple other cosmetic\nchanges, and pushed it.Thanks for the adjustments and pushing! \nThat's not the fault of anything we did here; the IndexOnlyScan path\nin the subquery is in fact not marked with any pathkeys, even though\nclearly its result is sorted. I believe that's an intentional\ndecision from way way back, that pathkeys only correspond to orderings\nthat are of interest in the current query level. \"select unique1 from\ntenk1 b order by unique1\" has an interest in ordering by unique1,\nbut \"select unique1 from tenk1 b\" does not, so it's choosing that\npath strictly according to cost. Not generating pathkeys in such a\nquery saves a few cycles and ensures that we won't improperly prefer\na path on the basis of pathkeys if it hasn't got a cost advantage.\nSo I'm quite hesitant to muck with that old decision, especially in\nthe waning days of a development cycle, but the results do feel a\nlittle strange here.Yeah, I also noticed this while writing the test case. That's why Iadded 'order by unique1' explicitly in the CTE subquery. This alsohappens to subquery RTEs, such asexplain (costs off)select * from (select unique1 from tenk1 offset 0) order by unique1; QUERY PLAN---------------------------------------------------- Sort Sort Key: tenk1.unique1 -> Index Only Scan using tenk1_unique1 on tenk1(3 rows)I agree that mucking with the old decision might not be a good idea. Inaddition, for a MATERIALIZED CTE, generating pathkeys according to theouter query's ordering requirements breaks the idea of optimizationfence: the outer query should not affect the plan chosen for the CTEquery.ThanksRichard",
"msg_date": "Wed, 27 Mar 2024 14:52:58 +0800",
"msg_from": "Richard Guo <guofenglinux@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Propagate pathkeys from CTEs up to the outer query"
},
{
"msg_contents": "On Wed, 27 Mar 2024 at 06:20, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> That's not the fault of anything we did here; the IndexOnlyScan path\n> in the subquery is in fact not marked with any pathkeys, even though\n> clearly its result is sorted. I believe that's an intentional\n> decision from way way back, that pathkeys only correspond to orderings\n> that are of interest in the current query level. \"select unique1 from\n> tenk1 b order by unique1\" has an interest in ordering by unique1,\n> but \"select unique1 from tenk1 b\" does not, so it's choosing that\n> path strictly according to cost. Not generating pathkeys in such a\n> query saves a few cycles and ensures that we won't improperly prefer\n> a path on the basis of pathkeys if it hasn't got a cost advantage.\n> So I'm quite hesitant to muck with that old decision, especially in\n> the waning days of a development cycle, but the results do feel a\n> little strange here.\n\nI agree that add_path() might start making questionable choices if we\nwere to include unrelated pathkeys in a path. However, I don't think\nit would be a bad idea to give a subquery a bit more context about\nwhere it's running and which orders might be useful for the outer\nquery.\n\nWhat's been reported in [1] I think could be solved by giving the\nplanner some way to tell subqueries what pathkeys are useful to the\nouter query.\n\nDavid\n\n[1] https://www.postgresql.org/message-id/242fc7c6-a8aa-2daf-ac4c-0a231e2619c1%40gmail.com\n\n\n",
"msg_date": "Wed, 27 Mar 2024 22:34:10 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Propagate pathkeys from CTEs up to the outer query"
}
] |
[
{
"msg_contents": "Hi,\n\nHere's a quick status report after the fourth week:\nStatus summary:\nstatus | w1 | w2 | w3 | w4\n-----------------------------------+-----------+--------+--------+----------\nNeeds review: | 238 | 213 | 181 | 147\nWaiting on Author: | 44 | 46 | 52 | 65\nReady for Committer: | 27 | 27 | 26 | 24\nCommitted: | 36 | 46 | 57 | 70\nMoved to next CF | 1 | 3 | 4 | 4\nWithdrawn: | 2 | 4 | 12 | 14\nReturned with Feedback: | 3 | 12 | 18 | 26\nRejected: | 1 | 1 | 2 | 2\nTotal: | 352 | 352 | 352 | 352\n\nIf you have submitted a patch and it's in \"Waiting for author\" state,\nplease aim to get it to \"Needs review\" state soon if you can, as\nthat's where people are most likely to be looking for things to\nreview.\n\nI have pinged all the threads that are in \"Needs review\" state and\ndon't apply, compile warning-free, or pass check-world. I'll do some\nmore of that sort of thing.\n\nI have sent out mails for which there has been no activity for a long\ntime, please respond to the mails if you are planning to continue to\nwork on it or if you are planning to work on it in the next\ncommitfest, please move it to the next commitfest. If there is no\nresponse I'm planning to return these patches and it can be added\nagain when it will be worked upon actively.\n\nRegards,\nVignesh\n\n\n",
"msg_date": "Mon, 29 Jan 2024 09:07:50 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": true,
"msg_subject": "Commitfest 2024-01 fourth week update"
}
] |
[
{
"msg_contents": "Hi,\n\nI noticed one minor thing that the upgrade doc refers to the old 'conflicting'\ncolumn of pg_replication_slot. As the column has been changed to 'conflict_reason', \nI think the doc needs to be updated like the attachment.\n\nBest Regards,\nHou Zhijie",
"msg_date": "Mon, 29 Jan 2024 05:08:15 +0000",
"msg_from": "\"Zhijie Hou (Fujitsu)\" <houzj.fnst@fujitsu.com>",
"msg_from_op": true,
"msg_subject": "Update the doc that refers to the removed column of\n pg_replication_slots."
},
{
"msg_contents": "On Mon, Jan 29, 2024 at 10:38 AM Zhijie Hou (Fujitsu)\n<houzj.fnst@fujitsu.com> wrote:\n>\n> I noticed one minor thing that the upgrade doc refers to the old 'conflicting'\n> column of pg_replication_slot. As the column has been changed to 'conflict_reason',\n> I think the doc needs to be updated like the attachment.\n>\n\nRight, this should be fixed. I'll take care of this.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Mon, 29 Jan 2024 10:55:57 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Update the doc that refers to the removed column of\n pg_replication_slots."
}
] |
[
{
"msg_contents": "Greetings, everyone!\n\nWhile analyzing output of Svace static analyzer [1] I've found a bug.\n\nIn function intoasc(interval * i, char *str) from file \nsrc/interfaces/ecpg/compatlib/informix.c\nwe return a non-terminated string since we use memcpy on tmp which is \nitself NULL-teminated but\nlast zero byte is not copied.\n\nThe proposed solution is to use strcpy instead, since it is used in all \nother functions in informix.c.\n\nThe patch is attached.\n\n[1] - https://svace.pages.ispras.ru/svace-website/en/\n\nOleg Tselebrovskiy, Postgres Pro",
"msg_date": "Mon, 29 Jan 2024 11:47:31 +0300",
"msg_from": "o.tselebrovskiy@postgrespro.ru",
"msg_from_op": true,
"msg_subject": "Returning non-terminated string in ECPG Informix-compatible function"
},
{
"msg_contents": "On Mon, Jan 29, 2024 at 2:17 PM <o.tselebrovskiy@postgrespro.ru> wrote:\n>\n> Greetings, everyone!\n>\n> While analyzing output of Svace static analyzer [1] I've found a bug.\n>\n> In function intoasc(interval * i, char *str) from file\n> src/interfaces/ecpg/compatlib/informix.c\n> we return a non-terminated string since we use memcpy on tmp which is\n> itself NULL-teminated but\n> last zero byte is not copied.\n>\n> The proposed solution is to use strcpy instead, since it is used in all\n> other functions in informix.c.\n>\n> The patch is attached.\n>\n> [1] - https://svace.pages.ispras.ru/svace-website/en/\n>\n\nCan you please add a test case showcasing the bug? I see dttoasc()\nuses strcpy(). So there's already a precedence.\n\n-- \nBest Wishes,\nAshutosh Bapat\n\n\n",
"msg_date": "Tue, 30 Jan 2024 12:42:37 +0530",
"msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Returning non-terminated string in ECPG Informix-compatible\n function"
},
{
"msg_contents": "Here's the code for bug reproduction:\n#include <stdio.h>\n#include <stdlib.h>\n\nEXEC SQL INCLUDE pgtypes_interval.h;\nEXEC SQL INCLUDE ecpg_informix.h;\n\nEXEC SQL BEGIN DECLARE SECTION;\n\tchar dirty_str[100] = \"aaaaaaaaa_bbbbbbbb_ccccccccc_ddddddddd_\";\n\tinterval *interval_ptr;\nEXEC SQL END DECLARE SECTION;\n\nint main()\n{\n\tinterval_ptr = (interval *) malloc(sizeof(interval));\n\tinterval_ptr->time = 100000000;\n\tinterval_ptr->month = 240;\n\n\tprintf(\"dirty_str contents before intoasc: %s\\n\", dirty_str);\n\tintoasc(interval_ptr, dirty_str);\n\tprintf(\"dirty_str contents after intoasc: %s\\n\", dirty_str);\n\treturn 0;\n}\n\nAnd here's the output:\n\ndirty_str contents before intoasc: \naaaaaaaaa_bbbbbbbb_ccccccccc_ddddddddd_\ndirty_str contents after intoasc: @ 20 years 1 min 40 \nsecscccc_ddddddddd_\n\nI compiled it with following commands (provided for quicker \nreproduction):\n/path/to/pgsql/bin/ecpg informix_bug_example.pgc\ngcc -I/path/to/pgsql/include -c informix_bug_example.c\ngcc -o informix_bug_example informix_bug_example.o -L/path/to/pgsql/lib \n-lecpg -lecpg_compat\n\nI've also found at least one project that uses intoasc() in it - \nhttps://github.com/credativ/informix_fdw/\n\nOleg Tselebrovskiy, Postgres Pro\n\n\n",
"msg_date": "Tue, 30 Jan 2024 13:56:22 +0300",
"msg_from": "Oleg Tselebrovskiy <o.tselebrovskiy@postgrespro.ru>",
"msg_from_op": false,
"msg_subject": "Re: Returning non-terminated string in ECPG Informix-compatible\n function"
},
{
"msg_contents": "Greetings again.\nI was looking through more static analyzer output and found another \nproblem.\nIn ecpg/pgtypeslib/dt_common.c there are 4 calls of pgtypes_alloc.\nThis function uses calloc and returns NULL if OOM, but we don't check \nits\nreturn value and immediately pass it to strcpy, which could lead to \nsegfault.\n\nI suggest adding a check for a return value since all other calls of\npgtypes_alloc are checked for NULL.\n\nA proposed patch (with previous and current changes) is attached\n\nOleg Tselebrovskiy, Postgres Pro",
"msg_date": "Thu, 15 Feb 2024 12:15:40 +0700",
"msg_from": "Oleg Tselebrovskiy <o.tselebrovskiy@postgrespro.ru>",
"msg_from_op": false,
"msg_subject": "Re: Returning non-terminated string in ECPG Informix-compatible\n function"
},
{
"msg_contents": "On Thu, Feb 15, 2024 at 12:15:40PM +0700, Oleg Tselebrovskiy wrote:\n> Greetings again.\n> I was looking through more static analyzer output and found another problem.\n> In ecpg/pgtypeslib/dt_common.c there are 4 calls of pgtypes_alloc.\n> This function uses calloc and returns NULL if OOM, but we don't check its\n> return value and immediately pass it to strcpy, which could lead to\n> segfault.\n>\n> I suggest adding a check for a return value since all other calls of\n> pgtypes_alloc are checked for NULL.\n\nRight.\n\n> @@ -654,7 +654,7 @@ intoasc(interval * i, char *str)\n> if (!tmp)\n> return -errno;\n> \n> - memcpy(str, tmp, strlen(tmp));\n> + strcpy(str, tmp);\n\nFor this stuff, Ashutosh's point was to integrate a test case in the\npatch. With the pgc you have posted, most of the work is done, but\nthis should be added to src/interfaces/ecpg/test/sql/ to add some\nautomated coverage. See the area for references showing how this is\nachieved.\n\n> @@ -2837,6 +2843,8 @@ PGTYPEStimestamp_defmt_scan(char **str, char *fmt, timestamp * d,\n> case 'T':\n> pfmt++;\n> tmp = pgtypes_alloc(strlen(\"%H:%M:%S\") + strlen(pstr) + 1);\n> + if(!tmp)\n> + return 1;\n\nThese are obviously wrong as pgtypes_alloc() could return NULL.\n--\nMichael",
"msg_date": "Thu, 15 Feb 2024 14:25:07 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Returning non-terminated string in ECPG Informix-compatible\n function"
},
{
"msg_contents": "Thanks for review!\n\nI added a regression test that is based on code from previous email\n\nNew patch is attached\n\nOleg Tselebrovskiy, Postgres Pro",
"msg_date": "Thu, 15 Feb 2024 17:17:17 +0700",
"msg_from": "Oleg Tselebrovskiy <o.tselebrovskiy@postgrespro.ru>",
"msg_from_op": false,
"msg_subject": "Re: Returning non-terminated string in ECPG Informix-compatible\n function"
},
{
"msg_contents": "On Thu, Feb 15, 2024 at 05:17:17PM +0700, Oleg Tselebrovskiy wrote:\n> Thanks for review!\n\ndt_common.c is quite amazing, the APIs that we have in it rely on\nstrcpy() but we have no idea of the length of the buffer string given\nin input to store the result. This would require breaking the\nexisting APIs or inventing new ones to be able to plug some safer\nstrlcpy() calls. Not sure if it's really worth bothering. For now,\nI've applied the OOM checks on HEAD and the fix with the null\ntermination on all stable branches.\n--\nMichael",
"msg_date": "Mon, 19 Feb 2024 12:20:12 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Returning non-terminated string in ECPG Informix-compatible\n function"
}
] |
[
{
"msg_contents": "If you call dsa_allocate_extended(DSA_ALLOC_NO_OOM), it will still \nereport an error if you run out of space (originally reported at [0]).\n\nAttached patch adds code to test_dsa.c to demonstrate that:\n\npostgres=# select test_dsa_basic();\nERROR: could not resize shared memory segment \"/PostgreSQL.1312700148\" \nto 1075843072 bytes: No space left on device\n\n[0] https://github.com/pgvector/pgvector/issues/434#issuecomment-1912744489\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)",
"msg_date": "Mon, 29 Jan 2024 14:06:01 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": true,
"msg_subject": "DSA_ALLOC_NO_OOM doesn't work"
},
{
"msg_contents": "(moving to pgsql-hackers)\n\nOn 29/01/2024 14:06, Heikki Linnakangas wrote:\n> If you call dsa_allocate_extended(DSA_ALLOC_NO_OOM), it will still\n> ereport an error if you run out of space (originally reported at [0]).\n> \n> Attached patch adds code to test_dsa.c to demonstrate that:\n> \n> postgres=# select test_dsa_basic();\n> ERROR: could not resize shared memory segment \"/PostgreSQL.1312700148\"\n> to 1075843072 bytes: No space left on device\n> \n> [0] https://github.com/pgvector/pgvector/issues/434#issuecomment-1912744489\n\nI wrote the attached patch to address this, in a fairly straightforward \nor naive way. The problem was that even though dsa_allocate() had code \nto check the return value of dsm_create(), and return NULL instead of \nereport(ERROR) if the DSA_ALLOC_NO_OOM was set, dsm_create() does not in \nfact return NULL on OOM. To fix, I added a DSM_CREATE_NO_OOM option to \ndsm_create(), and I also had to punch that through to dsm_impl_op().\n\nThis is a little unpolished, but if we want to backpatch something \nnarrow now, this would probably be the right approach.\n\nHowever, I must say that the dsm_impl_op() interface is absolutely \ninsane. It's like someone looked at ioctl() and thought, \"hey that's a \ngreat idea!\". It mixes all different operations like creating or \ndestroying a DSM segment together into one function call, and the return \nvalue is just a boolean, even though the function could fail for many \ndifferent reasons, and the callers do in fact care about the reason. In \na more natural interface, the different operations would have very \ndifferent function signatures.\n\nI think we must refactor that. It might be best to leave this \nDSA_ALLOC_NO_OOM bug unfixed in backpatches, and fix it on top of the \nrefactorings on master only. Later, we can backpatch the refactorings \ntoo if we're comfortable with it; extensions shouldn't be using the \ndsm_impl_op() interface directly.\n\n(I skimmed through the thread where the DSM code was added, but didn't \nsee any mention of why dsm_impl_op() signature is like that: \nhttps://www.postgresql.org/message-id/CA%2BTgmoaDqDUgt%3D4Zs_QPOnBt%3DEstEaVNP%2B5t%2Bm%3DFPNWshiPR3A%40mail.gmail.com)\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)",
"msg_date": "Tue, 13 Feb 2024 16:23:20 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": true,
"msg_subject": "Re: DSA_ALLOC_NO_OOM doesn't work"
},
{
"msg_contents": "On Wed, Feb 14, 2024 at 3:23 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> On 29/01/2024 14:06, Heikki Linnakangas wrote:\n> > If you call dsa_allocate_extended(DSA_ALLOC_NO_OOM), it will still\n> > ereport an error if you run out of space (originally reported at [0]).\n> >\n> > Attached patch adds code to test_dsa.c to demonstrate that:\n> >\n> > postgres=# select test_dsa_basic();\n> > ERROR: could not resize shared memory segment \"/PostgreSQL.1312700148\"\n> > to 1075843072 bytes: No space left on device\n> >\n> > [0] https://github.com/pgvector/pgvector/issues/434#issuecomment-1912744489\n\nRight, DSA_ALLOC_NO_OOM handles the case where there aren't any more\nDSM slots (which used to be more common before we ramped up some\nconstants) and the case where max_total_segment_size (as self-imposed\nlimit) would be exceeded, but there is nothing to deal with failure to\nallocate at the DSM level, and yeah that just isn't a thing it can do.\nNot surprisingly that this observation comes from a Docker user: its\n64MB default size limit on the /dev/shm mountpoint breaks parallel\nquery as discussed on list a few times (see also\nhttps://github.com/docker-library/postgres/issues/416).\n\nThis is my mistake, introduced in commit 16be2fd10019 where I failed\nto pass that down into DSM code. The only user of DSA_ALLOC_NO_OOM in\ncore code so far is in dshash.c, where we just re-throw after some\ncleanup, commit 4569715b, so you could leak that control object due to\nthis phenomenon.\n\n> I wrote the attached patch to address this, in a fairly straightforward\n> or naive way. The problem was that even though dsa_allocate() had code\n> to check the return value of dsm_create(), and return NULL instead of\n> ereport(ERROR) if the DSA_ALLOC_NO_OOM was set, dsm_create() does not in\n> fact return NULL on OOM. To fix, I added a DSM_CREATE_NO_OOM option to\n> dsm_create(), and I also had to punch that through to dsm_impl_op().\n\nYeah, makes total sense.\n\n> This is a little unpolished, but if we want to backpatch something\n> narrow now, this would probably be the right approach.\n>\n> However, I must say that the dsm_impl_op() interface is absolutely\n> insane. It's like someone looked at ioctl() and thought, \"hey that's a\n> great idea!\". It mixes all different operations like creating or\n> destroying a DSM segment together into one function call, and the return\n> value is just a boolean, even though the function could fail for many\n> different reasons, and the callers do in fact care about the reason. In\n> a more natural interface, the different operations would have very\n> different function signatures.\n\nYeah. It also manages to channel some of shmat() et al's negative beauty.\n\nAnyway, that leads to this treatment of errnos in your patch:\n\n+ errno = 0;\n if (dsm_impl_op(DSM_OP_CREATE, seg->handle, size,\n&seg->impl_private,\n- &seg->mapped_address, &seg->mapped_size, ERROR))\n+ &seg->mapped_address, &seg->mapped_size,\nERROR, impl_flags))\n break;\n+ if ((flags & DSM_CREATE_NO_OOM) != 0 && (errno == ENOMEM\n|| errno == ENOSPC))\n\n... which seems reasonable given the constraints. Another idea might\nbe to write something different in one of those output parameters to\ndistinguish out-of-memory, but nothing really seems to fit...\n\n> I think we must refactor that. It might be best to leave this\n> DSA_ALLOC_NO_OOM bug unfixed in backpatches, and fix it on top of the\n> refactorings on master only. Later, we can backpatch the refactorings\n> too if we're comfortable with it; extensions shouldn't be using the\n> dsm_impl_op() interface directly.\n\nYeah, that sounds true. We don't do a good job of nailing down the\npublic API of PostgreSQL but dsm_impl_op() is a rare case that is very\nobviously not intended to be called by anyone else. On the other\nhand, if we really want to avoid changing the function prototype on\nprinciple, perhaps we could make a new operation DSM_OP_CREATE_NO_OOM\ninstead?\n\n\n",
"msg_date": "Wed, 14 Feb 2024 10:17:37 +1300",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: DSA_ALLOC_NO_OOM doesn't work"
},
{
"msg_contents": "On Tue, Feb 13, 2024 at 7:53 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> However, I must say that the dsm_impl_op() interface is absolutely\n> insane. It's like someone looked at ioctl() and thought, \"hey that's a\n> great idea!\".\n\nAs the person who wrote that code, this made me laugh.\n\nI agree it's not the prettiest interface, but I thought that was OK\nconsidering that it should only ever have a very limited number of\ncallers. I believe I did it this way in the interest of code\ncompactness. Since there are four DSM implementations, I wanted the\nimplementation-specific code to be short and all in one place, and\njamming it all into one function served that purpose. Also, there's a\nbunch of logic that is shared by multiple operations - detach and\ndestroy tend to be similar, and so do create and attach, and there are\neven things that are shared across all operations, like the snprintf\nat the top of dsm_impl_posix() or the slightly larger amount of\nboilerplate at the top of dsm_impl_sysv().\n\nI'm not particularly opposed to refactoring this to make it nicer, but\nmy judgement was that splitting it up into one function per operation\nper implementation, say, would have involved a lot of duplication of\nsmall bits of code that might then get out of sync with each other\nover time. By doing it this way, the logic is a bit tangled -- or\nmaybe more than a bit -- but there's very little duplication because\neach implementation gets jammed into the smallest possible box. I'm OK\nwith somebody deciding that I got the trade-offs wrong there, but I\nwill be interested to see the number of lines added vs. removed in any\nfuture refactoring patch.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n",
"msg_date": "Wed, 14 Feb 2024 12:53:14 +0530",
"msg_from": "Robert Haas <robertmhaas@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: DSA_ALLOC_NO_OOM doesn't work"
},
{
"msg_contents": "On 14/02/2024 09:23, Robert Haas wrote:\n> On Tue, Feb 13, 2024 at 7:53 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>> However, I must say that the dsm_impl_op() interface is absolutely\n>> insane. It's like someone looked at ioctl() and thought, \"hey that's a\n>> great idea!\".\n> \n> As the person who wrote that code, this made me laugh.\n> \n> I agree it's not the prettiest interface, but I thought that was OK\n> considering that it should only ever have a very limited number of\n> callers. I believe I did it this way in the interest of code\n> compactness. Since there are four DSM implementations, I wanted the\n> implementation-specific code to be short and all in one place, and\n> jamming it all into one function served that purpose. Also, there's a\n> bunch of logic that is shared by multiple operations - detach and\n> destroy tend to be similar, and so do create and attach, and there are\n> even things that are shared across all operations, like the snprintf\n> at the top of dsm_impl_posix() or the slightly larger amount of\n> boilerplate at the top of dsm_impl_sysv().\n> \n> I'm not particularly opposed to refactoring this to make it nicer, but\n> my judgement was that splitting it up into one function per operation\n> per implementation, say, would have involved a lot of duplication of\n> small bits of code that might then get out of sync with each other\n> over time. By doing it this way, the logic is a bit tangled -- or\n> maybe more than a bit -- but there's very little duplication because\n> each implementation gets jammed into the smallest possible box. I'm OK\n> with somebody deciding that I got the trade-offs wrong there, but I\n> will be interested to see the number of lines added vs. removed in any\n> future refactoring patch.\n\nThat's fair, I can see those reasons. Nevertheless, I do think it was a \nbad tradeoff. A little bit of repetition would be better here, or we can \nextract the common parts to smaller functions.\n\nI came up with the attached:\n\n 25 files changed, 1710 insertions(+), 1113 deletions(-)\n\nSo yeah, it's more code, and there's some repetition, but I think this \nis more readable. Some of that is extra boilerplate because I split the \nimplementations to separate files, and I also added tests.\n\nI'm not 100% wedded on all of the decisions here, but I think this is \nthe right direction overall. For example, I decided to separate \ndsm_handle used by the high-level interface in dsm.c and the \ndsm_impl_handle used by the low-level interace in dsm_impl_*.c (more on \nthat below). That feels slightly better to me, but could be left out if \nwe don't want that.\n\nNotable changes:\n\n- Split the single multiplexed dsm_impl_op() function into multiple \nfunctions for different operations. This allows more natural function \nsignatures for the different operations.\n\n- The create() function is now responsible for generating the handle, \ninstead of having the caller generate it. Those implementations that \nneed to generate a random handle and retry if it's already in use, now \ndo that retry within the implementation.\n\n- The destroy() function no longer detaches the segment; you must call \ndetach() first if the segment is still attached. This avoids having to \npass \"junk\" values when destroying a segment that's not attached, and in \ncase of error, makes it more clear what failed.\n\n- Separate dsm_handle, used by backend code to interact with the high \nlevel interface in dsm.c, from dsm_impl_handle, which is used to \ninteract with the low-level functions in dsm_impl.c. This gets rid of \nthe convention in dsm.c of reserving odd numbers for DSM segments stored \nin the main shmem area. There is now an explicit flag for that the \ncontrol slot. For generating dsm_handles, we now use the same scheme we \nused to use for main-area shm segments for all DSM segments, which \nincludes the slot number in the dsm_handle. The implementations use \ntheir own mechanisms for generating the low-level dsm_impl_handles (all \nbut the SysV implementation generate a random handle and retry on \ncollision).\n\n- Use IPC_PRIVATE in the SysV implementation to have the OS create a \nunique identifier for us. Use the shmid directly as the (low-level) \nhandle, so that we don't need to use shmget() to convert a key to shmid, \nand don't need the \"cache\" for that.\n\n- create() no longer returns the mapped_size. The old Windows \nimplementation had some code to read the actual mapped size after \ncreating the mapping, and returned that in *mapped_size. Others just \nreturned the requested size. In principle reading the actual size might \nbe useful; the caller might be able to make use of the whole mapped size \nwhen it's larger than requested. In practice, the callers didn't do \nthat. Also, POSIX shmem on FreeBSD has similar round-up-to-page-size \nbehavior but the implementation did not query the actual mapped size \nafter creating the segment, so you could not rely on it.\n\n- Added a test that exercises basic create, detach, attach functionality \nusing all the different implementations supported on the current platform.\n\n- Change datatype of the opaque types in dsm_impl.c from \"void *\" to \ntypedefs over uintptr_t. It's easy to make mistakes with \"void *\", as \nyou can pass any pointer without getting warnings from the compiler. \nDedicated typedefs give a bit more type checking. (This is in the first \ncommit, all the other changes are bundled together in the second commit.)\n\nOverall, I don't think this is backpatchable. The handle changes and use \nof IPC_PRIVATE in particular: they could lead to failure to clean up old \nsegments if you upgraded the binary without a clean shutdown. A slightly \ndifferent version of this possibly would be, but I'd like to focus on \nwhat's best for master for now.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)",
"msg_date": "Wed, 21 Feb 2024 21:19:49 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": true,
"msg_subject": "Re: DSA_ALLOC_NO_OOM doesn't work"
},
{
"msg_contents": "On Thu, Feb 22, 2024 at 8:19 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> - Separate dsm_handle, used by backend code to interact with the high\n> level interface in dsm.c, from dsm_impl_handle, which is used to\n> interact with the low-level functions in dsm_impl.c. This gets rid of\n> the convention in dsm.c of reserving odd numbers for DSM segments stored\n> in the main shmem area. There is now an explicit flag for that the\n> control slot. For generating dsm_handles, we now use the same scheme we\n> used to use for main-area shm segments for all DSM segments, which\n> includes the slot number in the dsm_handle. The implementations use\n> their own mechanisms for generating the low-level dsm_impl_handles (all\n> but the SysV implementation generate a random handle and retry on\n> collision).\n\nCould we use slot number and generation number, instead of slot number\nand random number? I have never liked the random number thing, which\nIIUC was needed because of SysV key space management problems 'leaking'\nup to the handle level (yuck). With generations, you could keep\ncollisions arbitrarily far apart (just decide how many bits to use).\nCollisions aren't exactly likely, but if there is no need for that\napproach, I'm not sure why we'd keep it. (I remember dealing with\nactual collisions in the wild due to lack of PRNG seeding in workers,\nwhich admittedly should be vanishingly rare now).\n\nIf the slot number is encoded into the handle, why do we still need a\nlinear search for the slot?\n\n> - create() no longer returns the mapped_size. The old Windows\n> implementation had some code to read the actual mapped size after\n> creating the mapping, and returned that in *mapped_size. Others just\n> returned the requested size. In principle reading the actual size might\n> be useful; the caller might be able to make use of the whole mapped size\n> when it's larger than requested. In practice, the callers didn't do\n> that. Also, POSIX shmem on FreeBSD has similar round-up-to-page-size\n> behavior but the implementation did not query the actual mapped size\n> after creating the segment, so you could not rely on it.\n\nI think that is an interesting issue with the main shmem area. There,\nwe can set huge_page_size to fantastically large sizes up to 16GB on\nsome architectures, but we have nothing to make sure we don't waste\nsome or most of the final page. But I agree that there's not much\npoint in worrying about this for DSM.\n\n> - Added a test that exercises basic create, detach, attach functionality\n> using all the different implementations supported on the current platform.\n\nI wonder how we could test the cleanup-after-crash behaviour.\n\n\n",
"msg_date": "Thu, 22 Feb 2024 10:30:41 +1300",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: DSA_ALLOC_NO_OOM doesn't work"
},
{
"msg_contents": "On Thu, Feb 22, 2024 at 10:30 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> collisions arbitrarily far apart (just decide how many bits to use).\n\n. o O ( Perhaps if you also allocated slots using a FIFO freelist,\ninstead of the current linear search for the first free slot, you\ncould maximise the time before a slot is reused, improving the\ncollision-avoiding power of a generation scheme? )\n\n\n",
"msg_date": "Thu, 22 Feb 2024 12:03:07 +1300",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: DSA_ALLOC_NO_OOM doesn't work"
},
{
"msg_contents": "On 22/02/2024 01:03, Thomas Munro wrote:\n> On Thu, Feb 22, 2024 at 10:30 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n>> collisions arbitrarily far apart (just decide how many bits to use).\n> \n> . o O ( Perhaps if you also allocated slots using a FIFO freelist,\n> instead of the current linear search for the first free slot, you\n> could maximise the time before a slot is reused, improving the\n> collision-avoiding power of a generation scheme? )\n\nWe could also enlarge dsm_handle from 32-bits to 64-bits, if we're \nworried about collisions.\n\nI actually experimented with something like that too: I encoded the \"is \nthis in main region\" in one of the high bits and let the implementation \nuse the low bits. One small issue with that is that we have a few places \nthat pass a DSM handle as the 'bgw_main' argument when launching a \nworker process, and on 32-bit platforms that would not be wide enough. \nThose could be changed to use the wider 'bgw_extra' field instead, though.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Thu, 22 Feb 2024 02:05:04 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": true,
"msg_subject": "Re: DSA_ALLOC_NO_OOM doesn't work"
},
{
"msg_contents": "On Thu, Feb 22, 2024 at 12:49 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> That's fair, I can see those reasons. Nevertheless, I do think it was a\n> bad tradeoff. A little bit of repetition would be better here, or we can\n> extract the common parts to smaller functions.\n>\n> I came up with the attached:\n>\n> 25 files changed, 1710 insertions(+), 1113 deletions(-)\n>\n> So yeah, it's more code, and there's some repetition, but I think this\n> is more readable. Some of that is extra boilerplate because I split the\n> implementations to separate files, and I also added tests.\n\nAdding tests is great. I'm unenthusiastic about the rest, but I don't\nreally care enough to argue.\n\nWhat's the goal here, anyway? I mean, why bother?\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n",
"msg_date": "Thu, 22 Feb 2024 09:55:42 +0530",
"msg_from": "Robert Haas <robertmhaas@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: DSA_ALLOC_NO_OOM doesn't work"
}
] |
[
{
"msg_contents": "Hello hackers,\n\nWhile investigating some query plans, I noticed some code that seems\nto be wrong: when create_merge_append_path() estimates the cost of\nsorting an input, it calls cost_sort() passing subpath->parent->tuples\nas the number of tuples. Shouldn't it use subpath->parent->rows or\neven subpath->rows instead? The `tuples` variable doesn't account for\nthe filters on the relation, so this leads to incorrect cost estimates\nwhen there are highly selective filters, and Sort + Append is chosen\ninstead of MergeAppend.\n\nI don't have a good repro yet because the plans I've been studying\ninvolve a third-party extension, but the code looks incorrect so I\nthought I should ask.\n\nHere is a link to this code on GitHub:\nhttps://github.com/postgres/postgres/blob/6a1ea02c491d16474a6214603dce40b5b122d4d1/src/backend/optimizer/util/pathnode.c#L1469-L1477\n\n---\nAlexander Kuzmenkov\nTimescale\n\n\n",
"msg_date": "Mon, 29 Jan 2024 13:40:41 +0100",
"msg_from": "Alexander Kuzmenkov <akuzmenkov@timescale.com>",
"msg_from_op": true,
"msg_subject": "Incorrect cost for MergeAppend"
},
{
"msg_contents": "On Mon, Jan 29, 2024 at 6:11 PM Alexander Kuzmenkov\n<akuzmenkov@timescale.com> wrote:\n>\n> Hello hackers,\n>\n> While investigating some query plans, I noticed some code that seems\n> to be wrong: when create_merge_append_path() estimates the cost of\n> sorting an input, it calls cost_sort() passing subpath->parent->tuples\n> as the number of tuples. Shouldn't it use subpath->parent->rows or\n> even subpath->rows instead? The `tuples` variable doesn't account for\n> the filters on the relation, so this leads to incorrect cost estimates\n> when there are highly selective filters, and Sort + Append is chosen\n> instead of MergeAppend.\n\nAll other callers of cost_sort() except plan_cluster_use_sort() are\nusing rows instead of tuples. Even plan_cluster_use_sort() has\nrel->rows = rel->tuples, it's actually passing rows. So agree with\nyour suggestion. However a test will be good since this code is quite\nold.\n\n-- \nBest Wishes,\nAshutosh Bapat\n\n\n",
"msg_date": "Tue, 30 Jan 2024 12:50:29 +0530",
"msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Incorrect cost for MergeAppend"
},
{
"msg_contents": "Here is a small patch that reproduces the problem on two tables with\ninheritance, and fixes it. I'll add it to the Commitfest.\n\nOn Tue, Jan 30, 2024 at 8:20 AM Ashutosh Bapat\n<ashutosh.bapat.oss@gmail.com> wrote:\n>\n> On Mon, Jan 29, 2024 at 6:11 PM Alexander Kuzmenkov\n> <akuzmenkov@timescale.com> wrote:\n> >\n> > Hello hackers,\n> >\n> > While investigating some query plans, I noticed some code that seems\n> > to be wrong: when create_merge_append_path() estimates the cost of\n> > sorting an input, it calls cost_sort() passing subpath->parent->tuples\n> > as the number of tuples. Shouldn't it use subpath->parent->rows or\n> > even subpath->rows instead? The `tuples` variable doesn't account for\n> > the filters on the relation, so this leads to incorrect cost estimates\n> > when there are highly selective filters, and Sort + Append is chosen\n> > instead of MergeAppend.\n>\n> All other callers of cost_sort() except plan_cluster_use_sort() are\n> using rows instead of tuples. Even plan_cluster_use_sort() has\n> rel->rows = rel->tuples, it's actually passing rows. So agree with\n> your suggestion. However a test will be good since this code is quite\n> old.\n>\n> --\n> Best Wishes,\n> Ashutosh Bapat",
"msg_date": "Tue, 30 Jan 2024 12:06:28 +0100",
"msg_from": "Alexander Kuzmenkov <akuzmenkov@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: Incorrect cost for MergeAppend"
},
{
"msg_contents": "Hi,\n\n> Here is a small patch that reproduces the problem on two tables with\n> inheritance, and fixes it. I'll add it to the Commitfest.\n\nThanks for the patch.\n\nI can confirm that it changes the plan from Sort + Append to MergeAppend.\n\nBefore:\n\n```\nexplain (costs off) select * from ma0 where a < 1000 order by a;\n QUERY PLAN\n---------------------------------------------------------\n Sort\n Sort Key: ma0.a\n -> Append\n -> Index Only Scan using ma0_pkey on ma0 ma0_1\n Index Cond: (a < 1000)\n -> Seq Scan on ma1 ma0_2\n Filter: (a < 1000)\n```\n\nAfter:\n\n```\n=# explain (costs off) select * from ma0 where a < 1000 order by a;\n QUERY PLAN\n---------------------------------------------------\n Merge Append\n Sort Key: ma0.a\n -> Index Only Scan using ma0_pkey on ma0 ma0_1\n Index Cond: (a < 1000)\n -> Sort\n Sort Key: ma0_2.a\n -> Seq Scan on ma1 ma0_2\n Filter: (a < 1000)\n```\n\nThe rest of the tests pass.\n\n-- \nBest regards,\nAleksander Alekseev\n\n\n",
"msg_date": "Tue, 30 Jan 2024 15:18:44 +0300",
"msg_from": "Aleksander Alekseev <aleksander@timescale.com>",
"msg_from_op": false,
"msg_subject": "Re: Incorrect cost for MergeAppend"
},
{
"msg_contents": "On Wed, 31 Jan 2024 at 00:06, Alexander Kuzmenkov\n<akuzmenkov@timescale.com> wrote:\n> Here is a small patch that reproduces the problem on two tables with\n> inheritance, and fixes it. I'll add it to the Commitfest.\n\nGood catch.\n\nIt seems to have been broken since MergeAppends were added in 11cad29c9.\n\nThe code fix looks good to me.\n\nThe tests look a bit heavy. I wondered if you could have used a UNION\nALL query with the tenk1 table so you didn't have to create tables,\nhowever, I see that case works ok since the parent->tuples is set in\nset_subquery_size_estimates() from \"rel->tuples =\nsub_final_rel->cheapest_total_path->rows;\".\n\nI played around with the following and see your patch changes the plan\nto a Merge Append away from an Append -> Sort plan.\n\ncreate table tenk_parent (like tenk1);\nalter table tenk1 inherit tenk_parent;\nalter table tenk2 inherit tenk_parent;\nexplain (costs off) select * from tenk_parent where thousand = 0 order\nby tenthous;\nalter table tenk1 no inherit tenk_parent;\nalter table tenk2 no inherit tenk_parent;\n\nI'm just not sure if we should be messing with tenk1 and tenk2 like that.\n\nYou should likely focus on trying to find a test that does not require\nmaking 2 tables with 10k rows.\n\nDavid\n\n\n",
"msg_date": "Wed, 31 Jan 2024 01:20:21 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Incorrect cost for MergeAppend"
},
{
"msg_contents": "On Tue, Jan 30, 2024 at 1:20 PM David Rowley <dgrowleyml@gmail.com> wrote:\n> You should likely focus on trying to find a test that does not require\n> making 2 tables with 10k rows.\n\nIs 1k smallint OK? It should fit in one page. Still reproduces the\nerror, and the entire test case runs in under 10 ms.",
"msg_date": "Tue, 30 Jan 2024 14:23:37 +0100",
"msg_from": "Alexander Kuzmenkov <akuzmenkov@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: Incorrect cost for MergeAppend"
},
{
"msg_contents": "On Wed, 31 Jan 2024 at 02:23, Alexander Kuzmenkov\n<akuzmenkov@timescale.com> wrote:\n>\n> On Tue, Jan 30, 2024 at 1:20 PM David Rowley <dgrowleyml@gmail.com> wrote:\n> > You should likely focus on trying to find a test that does not require\n> > making 2 tables with 10k rows.\n>\n> Is 1k smallint OK? It should fit in one page. Still reproduces the\n> error, and the entire test case runs in under 10 ms.\n\nI had a go at making it a bit smaller without going dangerously close\nto where the plan might change. The following seems to work.\n\ncreate table ma0(a int primary key);\ncreate table ma1() inherits (ma0);\ninsert into ma0 select generate_series(1, 400);\ninsert into ma1 select generate_series(1, 200);\nanalyze ma0;\nanalyze ma1;\n\nexplain (costs off) select * from ma0 where a < 100 order by a;\n\ndrop table ma0 cascade;\n\nAs for backpatching this. It does risk plans changing in stable\nversions of PostgreSQL, which we normally try to avoid. However, it\nseems quite similar to 1e731ed12a, albeit, far more long-standing.\nI'm currently thinking we should backpatch this back to 12.\n\nDoes anyone disagree?\n\nDavid\n\n\n",
"msg_date": "Wed, 31 Jan 2024 12:03:23 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Incorrect cost for MergeAppend"
},
{
"msg_contents": "On Wed, Jan 31, 2024 at 4:33 AM David Rowley <dgrowleyml@gmail.com> wrote:\n>\n> On Wed, 31 Jan 2024 at 02:23, Alexander Kuzmenkov\n> <akuzmenkov@timescale.com> wrote:\n> >\n> > On Tue, Jan 30, 2024 at 1:20 PM David Rowley <dgrowleyml@gmail.com> wrote:\n> > > You should likely focus on trying to find a test that does not require\n> > > making 2 tables with 10k rows.\n> >\n> > Is 1k smallint OK? It should fit in one page. Still reproduces the\n> > error, and the entire test case runs in under 10 ms.\n>\n> I had a go at making it a bit smaller without going dangerously close\n> to where the plan might change. The following seems to work.\n>\n> create table ma0(a int primary key);\n> create table ma1() inherits (ma0);\n> insert into ma0 select generate_series(1, 400);\n> insert into ma1 select generate_series(1, 200);\n> analyze ma0;\n> analyze ma1;\n>\n> explain (costs off) select * from ma0 where a < 100 order by a;\n>\n> drop table ma0 cascade;\n\nOn my laptop with all default settings\n\nwith patch\npostgres@231714=#explain select * from ma0 where a < 100 order by a;\n QUERY PLAN\n--------------------------------------------------------------------------------------\n Merge Append (cost=6.94..18.90 rows=198 width=4)\n Sort Key: ma0.a\n -> Index Only Scan using ma0_pkey on ma0 ma0_1 (cost=0.15..9.88\nrows=99 width=4)\n Index Cond: (a < 100)\n -> Sort (cost=6.78..7.03 rows=99 width=4)\n Sort Key: ma0_2.a\n -> Seq Scan on ma1 ma0_2 (cost=0.00..3.50 rows=99 width=4)\n Filter: (a < 100)\n(8 rows)\n\nwithout patch\n#explain select * from ma0 where a < 100 order by a;\n QUERY PLAN\n----------------------------------------------------------------------\n Sort (cost=19.04..19.54 rows=198 width=4)\n Sort Key: ma0.a\n -> Append (cost=0.00..11.49 rows=198 width=4)\n -> Seq Scan on ma0 ma0_1 (cost=0.00..7.00 rows=99 width=4)\n Filter: (a < 100)\n -> Seq Scan on ma1 ma0_2 (cost=0.00..3.50 rows=99 width=4)\n Filter: (a < 100)\n(7 rows)\n\npostgres@233864=#select (19.54 - 18.90)/19.54, (19.04 - 18.09)/19.04;\n ?column? | ?column?\n------------------------+------------------------\n 0.03275332650972364381 | 0.04989495798319327731\n(1 row)\n\nThose numbers are higher than 1% (#define STD_FUZZ_FACTOR 1.01) but\nslight variation in all the GUCs that affect cost, might bring the\ndifference closer to STD_FUZZ_FACTOR.\n\nGiven how close they are, maybe it's not such a good idea to\nbackpatch. If the plans change for better, users won't complain but\notherwise they will complain and will have no way to go back to their\ngood plans in production.\n\n-- \nBest Wishes,\nAshutosh Bapat\n\n\n",
"msg_date": "Wed, 31 Jan 2024 11:28:07 +0530",
"msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Incorrect cost for MergeAppend"
},
{
"msg_contents": "On Wed, 31 Jan 2024 at 18:58, Ashutosh Bapat\n<ashutosh.bapat.oss@gmail.com> wrote:\n> with patch\n> Merge Append (cost=6.94..18.90 rows=198 width=4)\n\n> without patch\n> Sort (cost=19.04..19.54 rows=198 width=4)\n\n> Those numbers are higher than 1% (#define STD_FUZZ_FACTOR 1.01) but\n> slight variation in all the GUCs that affect cost, might bring the\n> difference closer to STD_FUZZ_FACTOR.\n>\n> Given how close they are, maybe it's not such a good idea to\n> backpatch.\n\nThe reason those numbers are close is because I reduced the row count\non the test tables to a point where we only just get the Merge Append\nplan with a small margin. I don't see the test case costs as a\nrelevant factor for if we backpatch or not.\n\nWhat is relevant are things like:\n\nFor:\n* It's a clear bug and what's happening now is clearly wrong.\n* inheritance/partitioned table plan changes for the better in minor versions\n\nAgainst:\n* Nobody has complained for 13 years, so maybe it's unlikely anyone is\nsuffering too much.\n* Possibility of inheritance/partitioned table plans changing for the\nworse in minor versions\n\nFor now, I'm on the fence on this one.\n\nDavid\n\n\n",
"msg_date": "Wed, 31 Jan 2024 19:42:24 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Incorrect cost for MergeAppend"
},
{
"msg_contents": "On Wed, Jan 31, 2024 at 12:12 PM David Rowley <dgrowleyml@gmail.com> wrote:\n>\n> What is relevant are things like:\n>\n> For:\n> * It's a clear bug and what's happening now is clearly wrong.\n> * inheritance/partitioned table plan changes for the better in minor versions\n>\n> Against:\n> * Nobody has complained for 13 years, so maybe it's unlikely anyone is\n> suffering too much.\n> * Possibility of inheritance/partitioned table plans changing for the\n> worse in minor versions\n>\n\nThat's what I am thinking as well. And the plans that may change for\nthe worse are the ones where the costs with and without the patch are\nclose.\n\nJust to be clear, the change is for good and should be committed to\nthe master. It's the backpatching I am worried about.\n\n-- \nBest Wishes,\nAshutosh Bapat\n\n\n",
"msg_date": "Wed, 31 Jan 2024 12:16:47 +0530",
"msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Incorrect cost for MergeAppend"
},
{
"msg_contents": "I'd be happy to see this backpatched. What kind of regressions are we\nworried about? I'd say partition-wise sort + merge should be faster\nthan append + sort for reasonably sized tables. That's basically what\ntuplesort does inside. Moreso, this can enable index scans on\npartitions, which is an even better plan.\n\nOn Wed, Jan 31, 2024 at 7:46 AM Ashutosh Bapat\n<ashutosh.bapat.oss@gmail.com> wrote:\n>\n> On Wed, Jan 31, 2024 at 12:12 PM David Rowley <dgrowleyml@gmail.com> wrote:\n> >\n> > What is relevant are things like:\n> >\n> > For:\n> > * It's a clear bug and what's happening now is clearly wrong.\n> > * inheritance/partitioned table plan changes for the better in minor versions\n> >\n> > Against:\n> > * Nobody has complained for 13 years, so maybe it's unlikely anyone is\n> > suffering too much.\n> > * Possibility of inheritance/partitioned table plans changing for the\n> > worse in minor versions\n> >\n>\n> That's what I am thinking as well. And the plans that may change for\n> the worse are the ones where the costs with and without the patch are\n> close.\n>\n> Just to be clear, the change is for good and should be committed to\n> the master. It's the backpatching I am worried about.\n>\n> --\n> Best Wishes,\n> Ashutosh Bapat\n\n\n",
"msg_date": "Wed, 31 Jan 2024 13:33:21 +0100",
"msg_from": "Alexander Kuzmenkov <akuzmenkov@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: Incorrect cost for MergeAppend"
},
{
"msg_contents": "On Wed, Jan 31, 2024 at 1:33 PM Alexander Kuzmenkov\n<akuzmenkov@timescale.com> wrote:\n> I'd be happy to see this backpatched. What kind of regressions are we\n> worried about? I'd say partition-wise sort + merge should be faster\n> than append + sort for reasonably sized tables. That's basically what\n> tuplesort does inside. Moreso, this can enable index scans on\n> partitions, which is an even better plan.\n\nTo put it another way, this change enables our usual cost model for\nMergeAppend to work correctly in the presence of filters. I think we\ncan consider this model to be reasonably correct, and we don't\ncurrently have major problems with MergeAppend being chosen instead of\nSort + Append in cases where it's suboptimal, right? So applying it\nproperly in case with filters is not likely to introduce problems.\n\n\n",
"msg_date": "Wed, 31 Jan 2024 14:37:28 +0100",
"msg_from": "Alexander Kuzmenkov <akuzmenkov@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: Incorrect cost for MergeAppend"
},
{
"msg_contents": "On 2024-Jan-31, Alexander Kuzmenkov wrote:\n\n> To put it another way, this change enables our usual cost model for\n> MergeAppend to work correctly in the presence of filters. I think we\n> can consider this model to be reasonably correct, and we don't\n> currently have major problems with MergeAppend being chosen instead of\n> Sort + Append in cases where it's suboptimal, right? So applying it\n> properly in case with filters is not likely to introduce problems.\n\nSince we have a minor coming up very soon, I think it's not a good idea\nto backpatch right now. Maybe you can push to master now, and consider\nwhether to backpatch later.\n\nThe problem is -- if somebody has an application that gets good plans\nwith the current cost model, and you change the cost model and the plans\nbecome worse, what do they do? If you change this in a major release,\nthis is not an issue because they must test their queries before\nupgrading and if they fail to realize a problem exists then it's their\nfault. If you change it in a minor release, then those people will be\nvery upset that things were changed suddenly, and they may get wary of\nfuture minor upgrades, which we don't want.\n\nPlus, they would need to do careful testing before doing the minor\nupgrade.\n\nMaybe plans can only go from bad to good and never from good to bad.\nBut are we 100% certain that that is the case?\n\nPeople who are **desperate** to get this improvement can perhaps run a\npatched version in the meantime.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\n\n",
"msg_date": "Wed, 31 Jan 2024 14:52:03 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: Incorrect cost for MergeAppend"
},
{
"msg_contents": "Hi,\n\n>Since we have a minor coming up very soon, I think it's not a good idea\n>to backpatch right now. Maybe you can push to master now, and consider\n>whether to backpatch later.\n\n>The problem is -- if somebody has an application that gets good plans\n>with the current cost model, and you change the cost model and the plans\n>become worse, what do they do? If you change this in a major release,\n>this is not an issue because they must test their queries before\n>upgrading and if they fail to realize a problem exists then it's their\n>fault. If you change it in a minor release, then those people will be\n>very upset that things were changed suddenly, and they may get wary of\n>future minor upgrades, which we don't want.\n\nI agree with this, especially as we tell our customers that such changes do not happen from one minor release to another.\n\nRegards\nDaniel\n\n\n\n\n\n\n\nHi,\n\n\n\n\n>Since we have a minor coming up very soon, I think it's not a good idea\n>to backpatch right now. Maybe you can push to master now, and consider\n>whether to backpatch later.\n\n>The problem is -- if somebody has an application that gets good plans\n>with the current cost model, and you change the cost model and the plans\n>become worse, what do they do? If you change this in a major release,\n>this is not an issue because they must test their queries before\n>upgrading and if they fail to realize a problem exists then it's their\n>fault. If you change it in a minor release, then those people will be\n>very upset that things were changed suddenly, and they may get wary of\n>future minor upgrades, which we don't want.\n\n\n\n\nI agree with this, especially as we tell our customers that such changes do not happen from one minor release to another.\n\n\n\n\nRegards\n\nDaniel",
"msg_date": "Wed, 31 Jan 2024 14:24:44 +0000",
"msg_from": "\"Daniel Westermann (DWE)\" <daniel.westermann@dbi-services.com>",
"msg_from_op": false,
"msg_subject": "Re: Incorrect cost for MergeAppend"
},
{
"msg_contents": "Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> Since we have a minor coming up very soon, I think it's not a good idea\n> to backpatch right now. Maybe you can push to master now, and consider\n> whether to backpatch later.\n\nAs a rule, we don't back-patch changes like this ever. People don't\nappreciate plans changing in minor releases.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Wed, 31 Jan 2024 10:31:57 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Incorrect cost for MergeAppend"
},
{
"msg_contents": "On Thu, 1 Feb 2024 at 04:32, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> > Since we have a minor coming up very soon, I think it's not a good idea\n> > to backpatch right now. Maybe you can push to master now, and consider\n> > whether to backpatch later.\n>\n> As a rule, we don't back-patch changes like this ever. People don't\n> appreciate plans changing in minor releases.\n\nPushed to master.\n\nThanks for the report and the fix, Alexander.\n\n\n",
"msg_date": "Thu, 1 Feb 2024 09:49:36 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Incorrect cost for MergeAppend"
},
{
"msg_contents": "On Wed, Jan 31, 2024 at 9:49 PM David Rowley <dgrowleyml@gmail.com> wrote:\n> Pushed to master.\n>\n> Thanks for the report and the fix, Alexander.\n\nThank you!\n\n\n",
"msg_date": "Wed, 31 Jan 2024 22:01:25 +0100",
"msg_from": "Alexander Kuzmenkov <akuzmenkov@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: Incorrect cost for MergeAppend"
}
] |
[
{
"msg_contents": "Hello\n\nIn Dilip's patch to improve SLRU concurrency, there's a requirement to\nprevent predicate.c's SLRU control lock from being used to control\naccess to another shared memory structure, SerialControlData. This\nstruct is used to keep track of the areas of the SLRU that are valid.\nDilip just embedded that change into the patch he submitted, but I think\nthe patch is actually wrong in detail, because it's leaving the\nSerialAdd() function unchanged to use SerialSLRULock, which is wrong\nbecause that function depends heavily on the contents of\nSerialControlData, and it also modifies it. So if run concurrently with\nthe other functions that are using SerialControlLock, the result would\nmake no sense.\n\nI came up with the attached. If there are no objections, I'll be\npushing this shortly.\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — 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)",
"msg_date": "Mon, 29 Jan 2024 14:13:21 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "separating use of SerialSLRULock"
},
{
"msg_contents": "On 2024-Jan-29, Alvaro Herrera wrote:\n\n> In Dilip's patch to improve SLRU concurrency, there's a requirement to\n> prevent predicate.c's SLRU control lock from being used to control\n> access to another shared memory structure, SerialControlData. This\n> struct is used to keep track of the areas of the SLRU that are valid.\n> Dilip just embedded that change into the patch he submitted, but I think\n> the patch is actually wrong in detail, because it's leaving the\n> SerialAdd() function unchanged to use SerialSLRULock, which is wrong\n> because that function depends heavily on the contents of\n> SerialControlData, and it also modifies it.\n\nIt's terrifying that SerialAdd() doesn't seem to be covered by any\ntests, though.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — 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, 29 Jan 2024 16:04:33 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "Re: separating use of SerialSLRULock"
},
{
"msg_contents": "On 2024-Jan-29, Alvaro Herrera wrote:\n\n> It's terrifying that SerialAdd() doesn't seem to be covered by any\n> tests, though.\n\nI realized that there's some coverage when compiling with\nTEST_SUMMARIZE_SERIAL, so I tried that and it looks OK.\n\nOne other change I made was in the comment that explains the locking\norder. I had put the new lock at the top, but when I tested adding some\nasserts to verify that the other locks are not held, they turn out to\nfire soon enough ... and the conflicting lock is the last one of that\nlist. So I added the new lock below it, and the SLRU lock further down,\nbecause SerialAdd does it that way.\n\nI pushed it now.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\n\n",
"msg_date": "Tue, 30 Jan 2024 18:16:28 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "Re: separating use of SerialSLRULock"
}
] |
[
{
"msg_contents": "Hi hackers,\n\nI have tried to analyse Postgres code with Svace static analyzer [1] and\nfound something I think is a real bug.\n\nIn pgp-decrypt.c, in prefix_init function the following check:\nif (len > sizeof(tmpbuf))\n\nseem to be erroneous and should really look this way:\nif (len > PGP_MAX_BLOCK)\n\nOtherwise the below checks in this line could lead to buffer overflows:\nif (buf[len - 2] != buf[len] || buf[len - 1] != buf[len + 1])\n\nThis is because buf will point to tmpbuf, while tmpbuf have a size of\nPGP_MAX_BLOCK + 2.\n\nWhat do you think? The proposed patch towarts the current master branch is\nattached.\n\n[1] - https://svace.pages.ispras.ru/svace-website/en/\n\n--\n best regards,\n Mikhail A. Gribkov\n\ne-mail: youzhick@gmail.com\n*http://www.flickr.com/photos/youzhick/albums\n<http://www.flickr.com/photos/youzhick/albums>*\nhttp://www.strava.com/athletes/5085772\nphone: +7(916)604-71-12\nTelegram: @youzhick",
"msg_date": "Mon, 29 Jan 2024 16:37:44 +0300",
"msg_from": "Mikhail Gribkov <youzhick@gmail.com>",
"msg_from_op": true,
"msg_subject": "Wrong buffer limits check"
},
{
"msg_contents": "> On 29 Jan 2024, at 14:37, Mikhail Gribkov <youzhick@gmail.com> wrote:\n\n> I have tried to analyse Postgres code with Svace static analyzer [1] and found something I think is a real bug.\n> \n> In pgp-decrypt.c, in prefix_init function the following check:\n> if (len > sizeof(tmpbuf))\n> \n> seem to be erroneous and should really look this way:\n> if (len > PGP_MAX_BLOCK)\n\nStudying the code I think you're right, we should be ensuring that the cipher\nblock size isn't exceeding PGP_MAX_BLOCK. In practice it seems night\nimpossible to hit given the ciphers in cipher_list, but we should still fix it.\nUnsurprisingly this seems to have been there forever (since July 2005) so needs\nto be backpatched to all supported branches for the sake of consistency\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Mon, 29 Jan 2024 15:09:57 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: Wrong buffer limits check"
}
] |
[
{
"msg_contents": "Hi,\n\nIMO I believe that bitmapset can obtain an optimization in the calculation\nof the WORDNUM and BITNUM macros.\n\nAs you know, in bitmapset, negative members are not allowed.\n\nif (x < 0)\nelog(ERROR, \"negative bitmapset member not allowed\");\n\nThen, allow the compiler to optimize and do the calculations in unsigned.\n\nI did a demonstration in compiler explorer.\nhttps://godbolt.org/z/c68o43Eq1\n\nIt is demonstrated here as well.\n\nGenerated instructions: GCC 13.2\n\n#define WORDNUM_f1(x) ((x) / BITS_PER_BITMAPWORD)\n mov eax, DWORD PTR [rbp-20]\n lea edx, [rax+63]\n test eax, eax\n cmovs eax, edx\n sar eax, 6\n mov DWORD PTR [rbp-4], eax\n\n#define WORDNUM_f2(x) ((bitmapword) (x) / BITS_PER_BITMAPWORD)\n mov eax, DWORD PTR [rbp-20]\n cdqe\n shr rax, 6\n mov DWORD PTR [rbp-4], eax\n\n\n#define BITNUM_f1(x) ((x) % BITS_PER_BITMAPWORD)\n mov edx, DWORD PTR [rbp-20]\n mov eax, edx\n sar eax, 31\n shr eax, 26\n add edx, eax\n and edx, 63\n sub edx, eax\n mov DWORD PTR [rbp-4], edx\n\n#define BITNUM_f2(x) ((bitmapword) (x) % BITS_PER_BITMAPWORD)\n mov eax, DWORD PTR [rbp-20]\n and eax, 63\n mov DWORD PTR [rbp-4], eax\n\nAs you can see, when calculations are done in unsigned,\nthe generated instructions are optimized.\n\nPatch attached.\n\nBest regards,\nRanier Vilela",
"msg_date": "Mon, 29 Jan 2024 13:30:47 -0300",
"msg_from": "Ranier Vilela <ranier.vf@gmail.com>",
"msg_from_op": true,
"msg_subject": "Optmize bitmapword macros calc (src/backend/nodes/bitmapset.c)"
},
{
"msg_contents": "On Mon, Jan 29, 2024 at 01:30:47PM -0300, Ranier Vilela wrote:\n> IMO I believe that bitmapset can obtain an optimization in the calculation\n> of the WORDNUM and BITNUM macros.\n> \n> As you know, in bitmapset, negative members are not allowed.\n> \n> if (x < 0)\n> elog(ERROR, \"negative bitmapset member not allowed\");\n> \n> Then, allow the compiler to optimize and do the calculations in unsigned.\n\nI'm currently +0.1 for this change. I don't see any huge problem with\ntrimming a few instructions, but I'm dubious there's any measurable impact.\nHowever, a cycle saved is a cycle earned...\n\n-#define WORDNUM(x)\t((x) / BITS_PER_BITMAPWORD)\n-#define BITNUM(x)\t((x) % BITS_PER_BITMAPWORD)\n+#define WORDNUM(x)\t((bitmapword)(x) / BITS_PER_BITMAPWORD)\n+#define BITNUM(x)\t((bitmapword)(x) % BITS_PER_BITMAPWORD)\n\nI'm curious why we'd cast to bitmapword and not straight to uint32. I\ndon't think the intent is that callers will provide a bitmapword to these\nmacros. I also wonder if it's worth asserting that x is >= 0 before\ncasting here.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Mon, 29 Jan 2024 13:32:03 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Optmize bitmapword macros calc (src/backend/nodes/bitmapset.c)"
},
{
"msg_contents": "Em seg., 29 de jan. de 2024 às 16:32, Nathan Bossart <\nnathandbossart@gmail.com> escreveu:\n\n> On Mon, Jan 29, 2024 at 01:30:47PM -0300, Ranier Vilela wrote:\n> > IMO I believe that bitmapset can obtain an optimization in the\n> calculation\n> > of the WORDNUM and BITNUM macros.\n> >\n> > As you know, in bitmapset, negative members are not allowed.\n> >\n> > if (x < 0)\n> > elog(ERROR, \"negative bitmapset member not allowed\");\n> >\n> > Then, allow the compiler to optimize and do the calculations in unsigned.\n>\n> I'm currently +0.1 for this change. I don't see any huge problem with\n> trimming a few instructions, but I'm dubious there's any measurable impact.\n> However, a cycle saved is a cycle earned...\n>\nBitmapset is extensively used.\n\n\n> -#define WORDNUM(x) ((x) / BITS_PER_BITMAPWORD)\n> -#define BITNUM(x) ((x) % BITS_PER_BITMAPWORD)\n> +#define WORDNUM(x) ((bitmapword)(x) / BITS_PER_BITMAPWORD)\n> +#define BITNUM(x) ((bitmapword)(x) % BITS_PER_BITMAPWORD)\n>\n> I'm curious why we'd cast to bitmapword and not straight to uint32. I\n> don't think the intent is that callers will provide a bitmapword to these\n> macros.\n\nbitmapword It is the most correct and prudent option, if in the future,\nwe decide to change the number of nwords to uint64.\n\n\n> I also wonder if it's worth asserting that x is >= 0 before\n> casting here.\n>\nI don't think this would change anything.\n\nbest regards,\nRanier Vilela\n\nEm seg., 29 de jan. de 2024 às 16:32, Nathan Bossart <nathandbossart@gmail.com> escreveu:On Mon, Jan 29, 2024 at 01:30:47PM -0300, Ranier Vilela wrote:\n> IMO I believe that bitmapset can obtain an optimization in the calculation\n> of the WORDNUM and BITNUM macros.\n> \n> As you know, in bitmapset, negative members are not allowed.\n> \n> if (x < 0)\n> elog(ERROR, \"negative bitmapset member not allowed\");\n> \n> Then, allow the compiler to optimize and do the calculations in unsigned.\n\nI'm currently +0.1 for this change. I don't see any huge problem with\ntrimming a few instructions, but I'm dubious there's any measurable impact.\nHowever, a cycle saved is a cycle earned...Bitmapset is extensively used.\n\n-#define WORDNUM(x) ((x) / BITS_PER_BITMAPWORD)\n-#define BITNUM(x) ((x) % BITS_PER_BITMAPWORD)\n+#define WORDNUM(x) ((bitmapword)(x) / BITS_PER_BITMAPWORD)\n+#define BITNUM(x) ((bitmapword)(x) % BITS_PER_BITMAPWORD)\n\nI'm curious why we'd cast to bitmapword and not straight to uint32. I\ndon't think the intent is that callers will provide a bitmapword to these\nmacros.bitmapword It is the most correct and prudent option, if in the future, we decide to change the number of nwords to uint64. I also wonder if it's worth asserting that x is >= 0 before\ncasting here.I don't think this would change anything.best regards,Ranier Vilela",
"msg_date": "Mon, 29 Jan 2024 16:43:32 -0300",
"msg_from": "Ranier Vilela <ranier.vf@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Optmize bitmapword macros calc (src/backend/nodes/bitmapset.c)"
},
{
"msg_contents": "On Mon, Jan 29, 2024 at 04:43:32PM -0300, Ranier Vilela wrote:\n> Em seg., 29 de jan. de 2024 �s 16:32, Nathan Bossart <\n> nathandbossart@gmail.com> escreveu:\n>> -#define WORDNUM(x) ((x) / BITS_PER_BITMAPWORD)\n>> -#define BITNUM(x) ((x) % BITS_PER_BITMAPWORD)\n>> +#define WORDNUM(x) ((bitmapword)(x) / BITS_PER_BITMAPWORD)\n>> +#define BITNUM(x) ((bitmapword)(x) % BITS_PER_BITMAPWORD)\n>>\n>> I'm curious why we'd cast to bitmapword and not straight to uint32. I\n>> don't think the intent is that callers will provide a bitmapword to these\n>> macros.\n> \n> bitmapword It is the most correct and prudent option, if in the future,\n> we decide to change the number of nwords to uint64.\n\nIf we change nwords to a uint64, I think there will be many other changes\nrequired. Using uint32 probably trims the instructions further on machines\nwith 64-bit pointers, too (e.g., cdqe).\n\n>> I also wonder if it's worth asserting that x is >= 0 before\n>> casting here.\n>>\n> I don't think this would change anything.\n\nRight, but it would offer another layer of protection against negative\nintegers in Bitmapsets.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Mon, 29 Jan 2024 13:53:13 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Optmize bitmapword macros calc (src/backend/nodes/bitmapset.c)"
},
{
"msg_contents": "On Tue, 30 Jan 2024 at 08:32, Nathan Bossart <nathandbossart@gmail.com> wrote:\n> I'm currently +0.1 for this change. I don't see any huge problem with\n> trimming a few instructions, but I'm dubious there's any measurable impact.\n> However, a cycle saved is a cycle earned...\n\nFWIW, In [1] and subsequent replies, there are several examples of\nbenchmarks where various bitmapset functions are sitting high in the\nprofiles. So I wouldn't be too surprised if such a small change to the\nWORDNUM and BITNUM macros made a noticeable difference.\n\nA benchmark speaks a thousand words, however.\n\nDavid\n\n[1] https://postgr.es/m/CAApHDvq9eq0W_aFUGrb6ba28ieuQN4zM5Uwqxy7+LMZjJc+VGg@mail.gmail.com\n\n\n",
"msg_date": "Tue, 30 Jan 2024 11:23:57 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Optmize bitmapword macros calc (src/backend/nodes/bitmapset.c)"
},
{
"msg_contents": "On Tue, Jan 30, 2024 at 11:23:57AM +1300, David Rowley wrote:\n> On Tue, 30 Jan 2024 at 08:32, Nathan Bossart <nathandbossart@gmail.com> wrote:\n>> I'm currently +0.1 for this change. I don't see any huge problem with\n>> trimming a few instructions, but I'm dubious there's any measurable impact.\n>> However, a cycle saved is a cycle earned...\n> \n> FWIW, In [1] and subsequent replies, there are several examples of\n> benchmarks where various bitmapset functions are sitting high in the\n> profiles. So I wouldn't be too surprised if such a small change to the\n> WORDNUM and BITNUM macros made a noticeable difference.\n\nGood to know, thanks. If there is indeed demonstrable improvement, I'd\nreadily adjust my +0.1 to +1.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Mon, 29 Jan 2024 16:40:52 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Optmize bitmapword macros calc (src/backend/nodes/bitmapset.c)"
},
{
"msg_contents": "Em seg., 29 de jan. de 2024 às 19:40, Nathan Bossart <\nnathandbossart@gmail.com> escreveu:\n\n> On Tue, Jan 30, 2024 at 11:23:57AM +1300, David Rowley wrote:\n> > On Tue, 30 Jan 2024 at 08:32, Nathan Bossart <nathandbossart@gmail.com>\n> wrote:\n> >> I'm currently +0.1 for this change. I don't see any huge problem with\n> >> trimming a few instructions, but I'm dubious there's any measurable\n> impact.\n> >> However, a cycle saved is a cycle earned...\n> >\n> > FWIW, In [1] and subsequent replies, there are several examples of\n> > benchmarks where various bitmapset functions are sitting high in the\n> > profiles. So I wouldn't be too surprised if such a small change to the\n> > WORDNUM and BITNUM macros made a noticeable difference.\n>\n> Good to know, thanks. If there is indeed demonstrable improvement, I'd\n> readily adjust my +0.1 to +1.\n>\nFollowing the suggestions, I did a quick test with one of the scripts.\n\nUbuntu 64 bits\ngcc 12.3 64 bits\n\ncreate table t1 (a int) partition by list(a);\nselect 'create table t1_'||x||' partition of t1 for values\nin('||x||');' from generate_series(0,9)x;\n\ntest1.sql\nselect * from t1 where a > 1 and a < 3;\n\npgbench -U postgres -n -f test1.sql -T 15 postgres\n\nhead:\n\ntps = 27983.182940\ntps = 28916.903038\ntps = 29051.878855\n\npatched:\n\ntps = 27517.301246\ntps = 27848.684133\ntps = 28669.367300\n\n\ncreate table t2 (a int) partition by list(a);\nselect 'create table t2_'||x||' partition of t2 for values\nin('||x||');' from generate_series(0,9999)x;\n\ntest2.sql\nselect * from t2 where a > 1 and a < 3;\n\npgbench -U postgres -n -f test2.sql -T 15 postgres\n\nhead:\n\ntps = 27144.044463\ntps = 28932.948620\ntps = 29299.016248\n\npatched:\n\ntps = 27363.364039\ntps = 28588.141586\ntps = 28669.367300\n\nTo my complete surprise, the change is slower.\nI can't say how, with fewer instructions, gcc makes the binary worse.\n\nbest regards,\nRanier Vilela\n\nEm seg., 29 de jan. de 2024 às 19:40, Nathan Bossart <nathandbossart@gmail.com> escreveu:On Tue, Jan 30, 2024 at 11:23:57AM +1300, David Rowley wrote:\n> On Tue, 30 Jan 2024 at 08:32, Nathan Bossart <nathandbossart@gmail.com> wrote:\n>> I'm currently +0.1 for this change. I don't see any huge problem with\n>> trimming a few instructions, but I'm dubious there's any measurable impact.\n>> However, a cycle saved is a cycle earned...\n> \n> FWIW, In [1] and subsequent replies, there are several examples of\n> benchmarks where various bitmapset functions are sitting high in the\n> profiles. So I wouldn't be too surprised if such a small change to the\n> WORDNUM and BITNUM macros made a noticeable difference.\n\nGood to know, thanks. If there is indeed demonstrable improvement, I'd\nreadily adjust my +0.1 to +1.Following the suggestions, I did a quick test with one of the scripts.Ubuntu 64 bitsgcc 12.3 64 bitscreate table t1 (a int) partition by list(a);select 'create table t1_'||x||' partition of t1 for valuesin('||x||');' from generate_series(0,9)x;test1.sqlselect * from t1 where a > 1 and a < 3;pgbench -U postgres -n -f test1.sql -T 15 postgreshead:tps = 27983.182940tps = 28916.903038tps = 29051.878855patched:tps = 27517.301246tps = 27848.684133tps = 28669.367300create table t2 (a int) partition by list(a);select 'create table t2_'||x||' partition of t2 for valuesin('||x||');' from generate_series(0,9999)x;test2.sqlselect * from t2 where a > 1 and a < 3;pgbench -U postgres -n -f test2.sql -T 15 postgreshead:tps = 27144.044463tps = 28932.948620tps = 29299.016248patched:tps = 27363.364039tps = 28588.141586tps = 28669.367300To my complete surprise, the change is slower.I can't say how, with fewer instructions, gcc makes the binary worse.best regards,Ranier Vilela",
"msg_date": "Tue, 30 Jan 2024 10:37:40 -0300",
"msg_from": "Ranier Vilela <ranier.vf@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Optmize bitmapword macros calc (src/backend/nodes/bitmapset.c)"
}
] |
[
{
"msg_contents": "Add EXPLAIN (MEMORY) to report planner memory consumption\n\nThis adds a new \"Memory:\" line under the \"Planning:\" group (which\ncurrently only has \"Buffers:\") when the MEMORY option is specified.\n\nIn order to make the reporting reasonably accurate, we create a separate\nmemory context for planner activities, to be used only when this option\nis given. The total amount of memory allocated by that context is\nreported as \"allocated\"; we subtract memory in the context's freelists\nfrom that and report that result as \"used\". We use\nMemoryContextStatsInternal() to obtain the quantities.\n\nThe code structure to show buffer usage during planning was not in\namazing shape, so I (Álvaro) modified the patch a bit to clean that up\nin passing.\n\nAuthor: Ashutosh Bapat\nReviewed-by: David Rowley, Andrey Lepikhov, Jian He, Andy Fan\nDiscussion: https://www.postgresql.org/message-id/CAExHW5sZA=5LJ_ZPpRO-w09ck8z9p7eaYAqq3Ks9GDfhrxeWBw@mail.gmail.com\n\nBranch\n------\nmaster\n\nDetails\n-------\nhttps://git.postgresql.org/pg/commitdiff/5de890e3610d5a12cdaea36413d967cf5c544e20\n\nModified Files\n--------------\ncontrib/auto_explain/auto_explain.c | 2 +\ndoc/src/sgml/ref/explain.sgml | 14 ++++\nsrc/backend/commands/explain.c | 152 ++++++++++++++++++++++++++++------\nsrc/backend/commands/prepare.c | 22 ++++-\nsrc/backend/utils/mmgr/mcxt.c | 13 +++\nsrc/include/commands/explain.h | 4 +-\nsrc/include/utils/memutils.h | 2 +\nsrc/test/regress/expected/explain.out | 76 +++++++++++++++++\nsrc/test/regress/sql/explain.sql | 8 ++\n9 files changed, 265 insertions(+), 28 deletions(-)",
"msg_date": "Mon, 29 Jan 2024 16:55:27 +0000",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "pgsql: Add EXPLAIN (MEMORY) to report planner memory consumption"
},
{
"msg_contents": "Up to now, the explain \" \" (two space) format is not mixed with \"=\".\n\nAnd, other places which show \"Memory\" do not use \"=\". David will\nremember prior discussions.\nhttps://www.postgresql.org/message-id/20200402054120.GC14618@telsasoft.com\nhttps://www.postgresql.org/message-id/20200407042521.GH2228@telsasoft.com\n\n \"Memory: used=%lld bytes allocated=%lld bytes\",\nvs\n \"Buckets: %d (originally %d) Batches: %d (originally %d) Memory Usage: %ldkB\\n\",\n\nThere was some discussion about \"bytes\" - maybe it should instead show\nkB?\n\n(Also, I first thought that \"peek\" should be \"peak\", but eventually I\nrealized that's it's as intended.)\n\nOn Fri, Jan 12, 2024 at 10:53:08PM +0530, Abhijit Menon-Sen wrote:\n> (Those \"bytes\" look slightly odd to me in the midst of all the x=y\n> pieces, but that's probably not worth thinking about.)\n\n\nOn Mon, Jan 29, 2024 at 04:55:27PM +0000, Alvaro Herrera wrote:\n> Add EXPLAIN (MEMORY) to report planner memory consumption\n> \n> This adds a new \"Memory:\" line under the \"Planning:\" group (which\n> currently only has \"Buffers:\") when the MEMORY option is specified.\n> \n> In order to make the reporting reasonably accurate, we create a separate\n> memory context for planner activities, to be used only when this option\n> is given. The total amount of memory allocated by that context is\n> reported as \"allocated\"; we subtract memory in the context's freelists\n> from that and report that result as \"used\". We use\n> MemoryContextStatsInternal() to obtain the quantities.\n> \n> The code structure to show buffer usage during planning was not in\n> amazing shape, so I (�lvaro) modified the patch a bit to clean that up\n> in passing.\n> \n> Author: Ashutosh Bapat\n> Reviewed-by: David Rowley, Andrey Lepikhov, Jian He, Andy Fan\n> Discussion: https://www.postgresql.org/message-id/CAExHW5sZA=5LJ_ZPpRO-w09ck8z9p7eaYAqq3Ks9GDfhrxeWBw@mail.gmail.com\n\n\n",
"msg_date": "Mon, 5 Feb 2024 16:21:46 -0600",
"msg_from": "Justin Pryzby <pryzby@telsasoft.com>",
"msg_from_op": false,
"msg_subject": "Re: pgsql: Add EXPLAIN (MEMORY) to report planner memory consumption"
},
{
"msg_contents": "On Tue, Feb 6, 2024 at 3:51 AM Justin Pryzby <pryzby@telsasoft.com> wrote:\n>\n> Up to now, the explain \" \" (two space) format is not mixed with \"=\".\n>\n> And, other places which show \"Memory\" do not use \"=\". David will\n> remember prior discussions.\n> https://www.postgresql.org/message-id/20200402054120.GC14618@telsasoft.com\n> https://www.postgresql.org/message-id/20200407042521.GH2228@telsasoft.com\n>\n> \"Memory: used=%lld bytes allocated=%lld bytes\",\n> vs\n> \"Buckets: %d (originally %d) Batches: %d (originally %d) Memory Usage: %ldkB\\n\",\n>\n\nI have used = to be consistent with Buffers usage in the same Planning section.\n\nAre you suggesting that\n\"Memory: used=%lld bytes allocated=%lld bytes\",\nshould be used instead of\n\"Memory: used=%lld bytes allocated=%lld bytes\",\nPlease notice the single vs double space.\n\nI am fine with this.\n\n> There was some discussion about \"bytes\" - maybe it should instead show\n> kB?\n>\n\nSo EXPLAIN (memory) on a prepared statement may report memory less\nthan 1kB in which case bytes is a better unit. Planner may consume as\nless as few kBs of memory, reporting which in kBs would be lossy.\n\n> (Also, I first thought that \"peek\" should be \"peak\", but eventually I\n> realized that's it's as intended.)\n>\n\nDon't understand the context. But probably it doesn't matter.\n\n-- \nBest Wishes,\nAshutosh Bapat\n\n\n",
"msg_date": "Tue, 6 Feb 2024 14:56:31 +0530",
"msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: pgsql: Add EXPLAIN (MEMORY) to report planner memory consumption"
},
{
"msg_contents": "Many thanks, Justin, for the post-commit review.\n\nOn 2024-Feb-06, Ashutosh Bapat wrote:\n\n> On Tue, Feb 6, 2024 at 3:51 AM Justin Pryzby <pryzby@telsasoft.com> wrote:\n> >\n> > Up to now, the explain \" \" (two space) format is not mixed with \"=\".\n> >\n> > And, other places which show \"Memory\" do not use \"=\". David will\n> > remember prior discussions.\n> > https://www.postgresql.org/message-id/20200402054120.GC14618@telsasoft.com\n> > https://www.postgresql.org/message-id/20200407042521.GH2228@telsasoft.com\n> >\n> > \"Memory: used=%lld bytes allocated=%lld bytes\",\n> > vs\n> > \"Buckets: %d (originally %d) Batches: %d (originally %d) Memory Usage: %ldkB\\n\",\n> \n> I have used = to be consistent with Buffers usage in the same Planning section.\n> \n> Are you suggesting that\n> \"Memory: used=%lld bytes allocated=%lld bytes\",\n> should be used instead of\n> \"Memory: used=%lld bytes allocated=%lld bytes\",\n> Please notice the single vs double space.\n\nI think using a single space here would be confusing. It's not a\nproblem for show_wal_usage because that one doesn't print units.\nI don't know it was you (Ashutosh) or I that put the double space, but I\nconsidered the matter and determined that two were better.\n\nIn the new line we have two different separators (: and =) because there\nare two levels of info being presented; in the show_hash_info one we\nhave only one type of separator.\n\nI'm not saying this is final and definite. I'm just saying I did\nconsider this whole format issue and what you see is the conclusion I\nreached. It may or may not be what Ashutosh submitted -- I don't\nremember. As committer, I almost always tweak submitted patches, and I\nwon't apologize for that. Further patches to correct my mistakes and\nbad decisions always welcome.\n\n> > (Also, I first thought that \"peek\" should be \"peak\", but eventually I\n> > realized that's it's as intended.)\n> \n> Don't understand the context. But probably it doesn't matter.\n\nSource code always matters. Why would people spend so much time fixing\ntypos otherwise?\n\nsrc/backend/commands/explain.c:\nstatic bool peek_buffer_usage(ExplainState *es, const BufferUsage *usage);\n\nWe don't want to know what the \"peak\" buffer usage is, but we want to\n\"peek\" whether buffer usage would print anything. I did have to spent a\nminute thinking what the correct spelling was, here (but my English is\nalmost exclusively read/written, not spoken. Condolencies if you've had\nto suffer my spoken English at some conference or whatever). I didn't\nlook at the dictionary back then, but now I do:\nhttps://www.merriam-webster.com/dictionary/peek\nAs Justin says, it's the right word.\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n\"After a quick R of TFM, all I can say is HOLY CR** THAT IS COOL! PostgreSQL was\namazing when I first started using it at 7.2, and I'm continually astounded by\nlearning new features and techniques made available by the continuing work of\nthe development team.\"\nBerend Tober, http://archives.postgresql.org/pgsql-hackers/2007-08/msg01009.php\n\n\n",
"msg_date": "Wed, 7 Feb 2024 11:13:24 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "Re: pgsql: Add EXPLAIN (MEMORY) to report planner memory consumption"
},
{
"msg_contents": "On Wed, Feb 7, 2024 at 3:43 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>\n> Many thanks, Justin, for the post-commit review.\n>\n> On 2024-Feb-06, Ashutosh Bapat wrote:\n>\n> > On Tue, Feb 6, 2024 at 3:51 AM Justin Pryzby <pryzby@telsasoft.com> wrote:\n> > >\n> > > Up to now, the explain \" \" (two space) format is not mixed with \"=\".\n> > >\n> > > And, other places which show \"Memory\" do not use \"=\". David will\n> > > remember prior discussions.\n> > > https://www.postgresql.org/message-id/20200402054120.GC14618@telsasoft.com\n> > > https://www.postgresql.org/message-id/20200407042521.GH2228@telsasoft.com\n> > >\n> > > \"Memory: used=%lld bytes allocated=%lld bytes\",\n> > > vs\n> > > \"Buckets: %d (originally %d) Batches: %d (originally %d) Memory Usage: %ldkB\\n\",\n> >\n> > I have used = to be consistent with Buffers usage in the same Planning section.\n> >\n> > Are you suggesting that\n> > \"Memory: used=%lld bytes allocated=%lld bytes\",\n> > should be used instead of\n> > \"Memory: used=%lld bytes allocated=%lld bytes\",\n> > Please notice the single vs double space.\n>\n> I think using a single space here would be confusing. It's not a\n> problem for show_wal_usage because that one doesn't print units.\n> I don't know it was you (Ashutosh) or I that put the double space, but I\n> considered the matter and determined that two were better.\n>\n> In the new line we have two different separators (: and =) because there\n> are two levels of info being presented; in the show_hash_info one we\n> have only one type of separator.\n>\n> I'm not saying this is final and definite. I'm just saying I did\n> consider this whole format issue and what you see is the conclusion I\n> reached. It may or may not be what Ashutosh submitted -- I don't\n> remember. As committer, I almost always tweak submitted patches, and I\n> won't apologize for that. Further patches to correct my mistakes and\n> bad decisions always welcome.\n\nI don't have a preference myself. But now that you explain it, two\nspaces between unit and next entity does seem a better choice. I had\nused \",\", which faced a minor objection. Thanks for that modification.\nI failed to notice it in the beginning. Sorry.\n\n>\n> > > (Also, I first thought that \"peek\" should be \"peak\", but eventually I\n> > > realized that's it's as intended.)\n> >\n> > Don't understand the context. But probably it doesn't matter.\n>\n> Source code always matters. Why would people spend so much time fixing\n> typos otherwise?\n>\n> src/backend/commands/explain.c:\n> static bool peek_buffer_usage(ExplainState *es, const BufferUsage *usage);\n>\n\nAh! Thanks for sharing the context. Without that context, I didn't\nunderstand Justin's comment. I had reviewed this change post-commit\nand knew very much that its peek and not peak. I also note that it's\nbetter than show_planning :).\n\n-- \nBest Wishes,\nAshutosh Bapat\n\n\n",
"msg_date": "Wed, 7 Feb 2024 16:09:47 +0530",
"msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: pgsql: Add EXPLAIN (MEMORY) to report planner memory consumption"
}
] |
[
{
"msg_contents": "I just realized while looking at Jelte's patch for the new nonblocking\nquery cancel stuff that the Meson build doesn't run the libpq_pipeline\ntests :-(\n\nIs there any way to wire the tests to make it work?\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — 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": "Mon, 29 Jan 2024 18:37:37 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "meson + libpq_pipeline"
},
{
"msg_contents": "On Mon Jan 29, 2024 at 11:37 AM CST, Alvaro Herrera wrote:\n> I just realized while looking at Jelte's patch for the new nonblocking\n> query cancel stuff that the Meson build doesn't run the libpq_pipeline\n> tests :-(\n>\n> Is there any way to wire the tests to make it work?\n\nI can try to take a look for you. Not sure how hard it will be, but \nI can take a crack at it this week.\n\n-- \nTristan Partin\nNeon (https://neon.tech)\n\n\n",
"msg_date": "Mon, 29 Jan 2024 12:36:54 -0600",
"msg_from": "\"Tristan Partin\" <tristan@neon.tech>",
"msg_from_op": false,
"msg_subject": "Re: meson + libpq_pipeline"
},
{
"msg_contents": "On Mon, 29 Jan 2024 at 19:37, Tristan Partin <tristan@neon.tech> wrote:\n>\n> On Mon Jan 29, 2024 at 11:37 AM CST, Alvaro Herrera wrote:\n> > I just realized while looking at Jelte's patch for the new nonblocking\n> > query cancel stuff that the Meson build doesn't run the libpq_pipeline\n> > tests :-(\n> >\n> > Is there any way to wire the tests to make it work?\n>\n> I can try to take a look for you. Not sure how hard it will be, but\n> I can take a crack at it this week.\n\nIt already does afaik.\n\nsrc/test/modules/libpq_pipeline/meson.build includes rules to execute\nt/001_libpq_pipeline.pl\n\nAnd to run a specific test I run the libpq_pipeline binary manually\nagainst some postgres port that is already up:\n\nninja -C build && build/src/test/modules/libpq_pipeline/libpq_pipeline\ncancel 'port=9700'\n\n\n",
"msg_date": "Mon, 29 Jan 2024 21:52:38 +0100",
"msg_from": "Jelte Fennema-Nio <postgres@jeltef.nl>",
"msg_from_op": false,
"msg_subject": "Re: meson + libpq_pipeline"
},
{
"msg_contents": "On 29.01.24 18:37, Alvaro Herrera wrote:\n> I just realized while looking at Jelte's patch for the new nonblocking\n> query cancel stuff that the Meson build doesn't run the libpq_pipeline\n> tests :-(\n> \n> Is there any way to wire the tests to make it work?\n\nI think it is running already.\n\nFor example, here is a cfbot run (that fails for other reasons, but it \npreserves the test artifacts): https://cirrus-ci.com/task/6143446205857792\n\nHere is the libpq_pipeline log: \nhttps://api.cirrus-ci.com/v1/artifact/task/6143446205857792/testrun/build/testrun/libpq_pipeline/001_libpq_pipeline/log/regress_log_001_libpq_pipeline\n\n\n",
"msg_date": "Tue, 30 Jan 2024 09:21:45 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": false,
"msg_subject": "Re: meson + libpq_pipeline"
},
{
"msg_contents": "On 2024-Jan-29, Jelte Fennema-Nio wrote:\n\n> On Mon, 29 Jan 2024 at 19:37, Tristan Partin <tristan@neon.tech> wrote:\n> >\n> > On Mon Jan 29, 2024 at 11:37 AM CST, Alvaro Herrera wrote:\n> > > I just realized while looking at Jelte's patch for the new nonblocking\n> > > query cancel stuff that the Meson build doesn't run the libpq_pipeline\n> > > tests :-(\n\n> > I can try to take a look for you. Not sure how hard it will be, but\n> > I can take a crack at it this week.\n> \n> It already does afaik.\n> \n> src/test/modules/libpq_pipeline/meson.build includes rules to execute\n> t/001_libpq_pipeline.pl\n\nOh, you're right, I missed that. I was looking for something in the\nmeson rules that would run \"libpq_pipeline tests\", but actually that's\nwhat t/001_libpq_pipeline.pl does internally. (Probably a good thing\ntoo, because it's quite likely that what libpq_pipeline emits as output\nis not valid TAP. I didn't ever tested it that way.)\n\nThanks Tristan for offering to help,\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/\n\"Ninguna manada de bestias tiene una voz tan horrible como la humana\" (Orual)\n\n\n",
"msg_date": "Tue, 30 Jan 2024 12:42:17 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "Re: meson + libpq_pipeline"
}
] |
[
{
"msg_contents": "Hi,\n\nLast year, David and I worked on a round of refactoring for\nheapgettup() and heapgettup_pagemode() [1]. Now that the streaming\nread API has been proposed [2], there is a bit more refactoring that\ncan be done on master to prepare sequential scan to support streaming\nreads.\n\nPatches 0001 and 0002 in the attached patchset do this new round of\nrefactoring. 0003 is the remainder of the streaming read API that is\nnot yet in master. 0004 is the sequential scan streaming read user.\n\nThe primary change needed to be able to drop in streaming read support\nwas that heapgettup() and heapgettup_pagemode() have to wait for there\nto be no more valid buffers instead of waiting until there were no\nmore valid BlockNumbers to know that the relation has been entirely\nprocessed. Naturally, streaming reads prefetch ahead of the block\nbeing currently processed by the scan, so all blocks should have been\nrequested long before all blocks have been processed.\n\nTo change this, I split up heapgetpage() into two functions -- one\nresponsible for getting blocks into buffers and the other for\nprocessing a page (pruning, checking tuple visibility, etc). As a\nconsequence, I had to change the other caller of heapgetpage() (sample\nscans). Since I was doing this anyway, I made a few changes there. It\nis arguable that those changes could be split up differently between\n0001 and 0004. However, I wanted 0004 to be *only* the sequential scan\nstreaming read user code.\n\nThere is an outstanding question about where to allocate the\nPgStreamingRead object for sequential scans (see TODO in 0004).\nHowever, I thought I would keep this thread focused on 0001 and 0002.\n\nThough logically the performance with 0001 and 0002 should be the same\nas master (no new non-inline function calls, no additional looping),\nI've done a bit of profiling anyway. I created a large multi-GB table,\nread it all into shared buffers (disabling the large sequential scan\nbulkread optimization), and did a sequential SELECT count(*) from the\ntable. From the profiles below, you'll notice that master and the\npatch are basically the same. Actual percentages vary from run-to-run.\nExecution time is the same.\n\npatch\n 15.49% postgres postgres [.] ExecInterpExpr\n 11.03% postgres postgres [.] heapgettup_pagemode\n 10.85% postgres postgres [.] ExecStoreBufferHeapTuple\n 9.14% postgres postgres [.] heap_getnextslot\n 8.39% postgres postgres [.] heapbuildvis\n 6.47% postgres postgres [.] SeqNext\n\nmaster\n 14.16% postgres postgres [.] ExecInterpExpr\n 11.54% postgres postgres [.] heapgettup_pagemode\n 10.63% postgres postgres [.] ExecStoreBufferHeapTuple\n 10.22% postgres postgres [.] heap_getnextslot\n 8.53% postgres postgres [.] heapgetpage\n 5.35% postgres postgres [.] SeqNext\n\n- Melanie\n\n[1] https://www.postgresql.org/message-id/flat/CAAKRu_YSOnhKsDyFcqJsKtBSrd32DP-jjXmv7hL0BPD-z0TGXQ%40mail.gmail.com\n[2] https://www.postgresql.org/message-id/flat/CA%2BhUKGJkOiOCa%2Bmag4BF%2BzHo7qo%3Do9CFheB8%3Dg6uT5TUm2gkvA%40mail.gmail.com",
"msg_date": "Mon, 29 Jan 2024 16:17:24 -0500",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Tue, 30 Jan 2024 at 10:17, Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n> Though logically the performance with 0001 and 0002 should be the same\n> as master (no new non-inline function calls, no additional looping),\n> I've done a bit of profiling anyway. I created a large multi-GB table,\n> read it all into shared buffers (disabling the large sequential scan\n> bulkread optimization), and did a sequential SELECT count(*) from the\n> table. From the profiles below, you'll notice that master and the\n> patch are basically the same. Actual percentages vary from run-to-run.\n> Execution time is the same.\n\nCan you also run a test on a Seqscan with a filter that filters out\nall tuples? There's less overhead in other parts of the executor with\nsuch a query.\n\nDavid\n\n\n",
"msg_date": "Tue, 30 Jan 2024 10:24:36 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Mon, Jan 29, 2024 at 4:24 PM David Rowley <dgrowleyml@gmail.com> wrote:\n>\n> On Tue, 30 Jan 2024 at 10:17, Melanie Plageman\n> <melanieplageman@gmail.com> wrote:\n> > Though logically the performance with 0001 and 0002 should be the same\n> > as master (no new non-inline function calls, no additional looping),\n> > I've done a bit of profiling anyway. I created a large multi-GB table,\n> > read it all into shared buffers (disabling the large sequential scan\n> > bulkread optimization), and did a sequential SELECT count(*) from the\n> > table. From the profiles below, you'll notice that master and the\n> > patch are basically the same. Actual percentages vary from run-to-run.\n> > Execution time is the same.\n>\n> Can you also run a test on a Seqscan with a filter that filters out\n> all tuples? There's less overhead in other parts of the executor with\n> such a query.\n\nYes, of course. Thank you so much for taking a look!\n\nWhile I was at it, I changed the table schema to be entirely composed\nof INT type columns and regenerated the data. Note that, both in this\nexample and my previous example, I ensured that the table was vacuumed\nbeforehand (and autovacuum disabled for the table) so there wasn't any\non-access pruning happening (heapgetpage() does that in pagemode).\n\nThis is the schema\n CREATE TABLE foo(id INT, a INT, b INT, c INT, d INT, e INT, f INT, g\nINT) with (autovacuum_enabled=false);\n\nI added 46000000 rows to the table, making it 2.6 GB. Shared buffers\nis double that. Before profiling, I did a SELECT * from the table with\nthe large sequential scan bulkread optimization disabled. Then I\nvacuumed the table. Finally, I turned up parallel_setup_cost high\nenough to disable query parallelism.\n\nThe query I profiled was:\nSELECT * FROM foo WHERE id = 0;\nWith the data I generated, 0 rows match that condition.\n\nProfiles below. Execution time essentially the same.\n\npatch:\n 17.08% postgres postgres [.] ExecInterpExpr\n 11.17% postgres postgres [.] tts_buffer_heap_getsomeattrs\n 10.64% postgres postgres [.] ExecStoreBufferHeapTuple\n 9.82% postgres postgres [.] heap_getnextslot\n 9.13% postgres postgres [.] heapgettup_pagemode\n 8.98% postgres postgres [.] heapbuildvis\n 5.40% postgres postgres [.] HeapCheckForSerializableConflictOut\n 5.16% postgres postgres [.] SeqNext\n\nmaster:\n 17.89% postgres postgres [.] ExecInterpExpr\n 12.28% postgres postgres [.] tts_buffer_heap_getsomeattrs\n 10.54% postgres postgres [.] ExecStoreBufferHeapTuple\n 10.11% postgres postgres [.] heapgettup_pagemode\n 8.52% postgres postgres [.] heapgetpage\n 8.28% postgres postgres [.] heap_getnextslot\n 5.00% postgres postgres [.] HeapCheckForSerializableConflictOut\n 4.71% postgres postgres [.] SeqNext\n\n- Melanie\n\n\n",
"msg_date": "Mon, 29 Jan 2024 17:35:06 -0500",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Mon, Jan 29, 2024 at 4:17 PM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n>\n> There is an outstanding question about where to allocate the\n> PgStreamingRead object for sequential scans\n\nI've written three alternative implementations of the actual streaming\nread user for sequential scan which handle the question of where to\nallocate the streaming read object and how to handle changing scan\ndirection in different ways.\n\nOption A) https://github.com/melanieplageman/postgres/tree/seqscan_pgsr_initscan_allocation\n- Allocates the streaming read object in initscan(). Since we do not\nknow the scan direction at this time, if the scan ends up not being a\nforwards scan, the streaming read object must later be freed -- so\nthis will sometimes allocate a streaming read object it never uses.\n- Only supports ForwardScanDirection and once the scan direction\nchanges, streaming is never supported again -- even if we return to\nForwardScanDirection\n- Must maintain a \"fallback\" codepath that does not use the streaming read API\n\nOption B) https://github.com/melanieplageman/postgres/tree/seqscan_pgsr_heapgettup_alloc_forward_only\n- Allocates the streaming read object in heapgettup[_pagemode]() when\nit has not been previously allocated. To do this it has to record and\nswitch into a different memory context than the per-tuple context. It\nonly allocates the streaming read object if it is a forwards scan. It\nfrees the streaming read object if the scan direction is later\nchanged.\n- Only supports ForwardScanDirection and once the scan direction\nchanges, streaming is never supported again -- even if we return to\nForwardScanDirection\n- Must maintain a \"fallback\" codepath that does not use the streaming read API\n\nOption C) https://github.com/melanieplageman/postgres/tree/seqscan_pgsr_all_dir_stream\n- Allocates the streaming read object in heapgettup[_pagemode]() when\nit has not been previously allocated. To do this it has to record and\nswitch into a different memory context than the per-tuple context.\n- All scan directions support streaming. To do this, the scan\ndirection has to be tracked and we must check if the direction has\nchanged on every heapgettup[_pagemode]() invocation to avoid returning\nwrong results.\n- No \"fallback\" codepath as all heap sequential scans will use the\nstreaming read API\n\nAs you can see, each option has pros and cons. I'm interested in what\nothers think about which we should choose.\n\n- Melanie\n\n\n",
"msg_date": "Mon, 19 Feb 2024 18:05:23 -0500",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Tue, Feb 20, 2024 at 4:35 AM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n> I've written three alternative implementations of the actual streaming\n> read user for sequential scan which handle the question of where to\n> allocate the streaming read object and how to handle changing scan\n> direction in different ways.\n\nIt's weird to me that the prospect of changing the scan direction\ncauses such complexity. I mean, why doesn't a streaming read object\nhave a forget_all_my_previous_requests() method or somesuch?\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n",
"msg_date": "Tue, 20 Feb 2024 16:43:13 +0530",
"msg_from": "Robert Haas <robertmhaas@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Tue, Feb 20, 2024 at 6:13 AM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> On Tue, Feb 20, 2024 at 4:35 AM Melanie Plageman\n> <melanieplageman@gmail.com> wrote:\n> > I've written three alternative implementations of the actual streaming\n> > read user for sequential scan which handle the question of where to\n> > allocate the streaming read object and how to handle changing scan\n> > direction in different ways.\n>\n> It's weird to me that the prospect of changing the scan direction\n> causes such complexity. I mean, why doesn't a streaming read object\n> have a forget_all_my_previous_requests() method or somesuch?\n\nBasically, that is what pg_streaming_read_free() does. It goes through\nand releases the buffers it had pinned and frees any per-buffer data\nallocated.\n\nThe complexity with the sequential scan streaming read user and scan\ndirection is just that it has to detect when the scan direction\nchanges and do the releasing/freeing and reallocation. The scan\ndirection is passed to heapgettup[_pagemode](), so this is something\nthat can change on a tuple-to-tuple basis.\n\nIt is less that doing this is complicated and more that it is annoying\nand distracting to have to check for and handle a very unimportant and\nuncommon case in the main path of the common case.\n\n- Melanie\n\n\n",
"msg_date": "Tue, 20 Feb 2024 11:15:39 -0500",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Mon, Feb 19, 2024 at 6:05 PM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n>\n> On Mon, Jan 29, 2024 at 4:17 PM Melanie Plageman\n> <melanieplageman@gmail.com> wrote:\n> >\n> > There is an outstanding question about where to allocate the\n> > PgStreamingRead object for sequential scans\n>\n> I've written three alternative implementations of the actual streaming\n> read user for sequential scan which handle the question of where to\n> allocate the streaming read object and how to handle changing scan\n> direction in different ways.\n>\n> Option A) https://github.com/melanieplageman/postgres/tree/seqscan_pgsr_initscan_allocation\n> - Allocates the streaming read object in initscan(). Since we do not\n> know the scan direction at this time, if the scan ends up not being a\n> forwards scan, the streaming read object must later be freed -- so\n> this will sometimes allocate a streaming read object it never uses.\n> - Only supports ForwardScanDirection and once the scan direction\n> changes, streaming is never supported again -- even if we return to\n> ForwardScanDirection\n> - Must maintain a \"fallback\" codepath that does not use the streaming read API\n\nAttached is a version of this patch which implements a \"reset\"\nfunction for the streaming read API which should be cheaper than the\nfull pg_streaming_read_free() on rescan. This can easily be ported to\nwork on any of my proposed implementations (A/B/C). I implemented it\non A as an example.\n\n- Melanie",
"msg_date": "Mon, 26 Feb 2024 15:56:57 -0500",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Mon, Feb 26, 2024 at 03:56:57PM -0500, Melanie Plageman wrote:\n> On Mon, Feb 19, 2024 at 6:05 PM Melanie Plageman\n> <melanieplageman@gmail.com> wrote:\n> >\n> > On Mon, Jan 29, 2024 at 4:17 PM Melanie Plageman\n> > <melanieplageman@gmail.com> wrote:\n> > >\n> > > There is an outstanding question about where to allocate the\n> > > PgStreamingRead object for sequential scans\n> >\n> > I've written three alternative implementations of the actual streaming\n> > read user for sequential scan which handle the question of where to\n> > allocate the streaming read object and how to handle changing scan\n> > direction in different ways.\n> >\n> > Option A) https://github.com/melanieplageman/postgres/tree/seqscan_pgsr_initscan_allocation\n> > - Allocates the streaming read object in initscan(). Since we do not\n> > know the scan direction at this time, if the scan ends up not being a\n> > forwards scan, the streaming read object must later be freed -- so\n> > this will sometimes allocate a streaming read object it never uses.\n> > - Only supports ForwardScanDirection and once the scan direction\n> > changes, streaming is never supported again -- even if we return to\n> > ForwardScanDirection\n> > - Must maintain a \"fallback\" codepath that does not use the streaming read API\n> \n> Attached is a version of this patch which implements a \"reset\"\n> function for the streaming read API which should be cheaper than the\n> full pg_streaming_read_free() on rescan. This can easily be ported to\n> work on any of my proposed implementations (A/B/C). I implemented it\n> on A as an example.\n\nAttached is the latest version of this patchset -- rebased in light of\nThomas' updatees to the streaming read API [1]. I have chosen the\napproach I think we should go with. It is a hybrid of my previously\nproposed approaches.\n\nThe streaming read is allocated in heap_beginscan() and then reset on\nrescan and when the scan direction changes. I only check if the scan\ndirection changes when a new page is needed. This implementation means\nno fallback method is needed, so we can remove the non-streaming read\ncode for heap sequential scans.\n\nBecause heapgettup() and heapgettup_pagemode() are also used for TID\nrange scans, this patch also happens to implement streaming reads for\nTID range scans.\n\n- Melanie\n\n[1] https://www.postgresql.org/message-id/CA%2BhUKGJtLyxcAEvLhVUhgD4fMQkOu3PDaj8Qb9SR_UsmzgsBpQ%40mail.gmail.com",
"msg_date": "Wed, 28 Feb 2024 12:30:40 -0500",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Wed, Feb 28, 2024 at 12:30 PM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n>\n> On Mon, Feb 26, 2024 at 03:56:57PM -0500, Melanie Plageman wrote:\n> > On Mon, Feb 19, 2024 at 6:05 PM Melanie Plageman\n> > <melanieplageman@gmail.com> wrote:\n> > >\n> > > On Mon, Jan 29, 2024 at 4:17 PM Melanie Plageman\n> > > <melanieplageman@gmail.com> wrote:\n> > > >\n> > > > There is an outstanding question about where to allocate the\n> > > > PgStreamingRead object for sequential scans\n> > >\n> > > I've written three alternative implementations of the actual streaming\n> > > read user for sequential scan which handle the question of where to\n> > > allocate the streaming read object and how to handle changing scan\n> > > direction in different ways.\n> > >\n> > > Option A) https://github.com/melanieplageman/postgres/tree/seqscan_pgsr_initscan_allocation\n> > > - Allocates the streaming read object in initscan(). Since we do not\n> > > know the scan direction at this time, if the scan ends up not being a\n> > > forwards scan, the streaming read object must later be freed -- so\n> > > this will sometimes allocate a streaming read object it never uses.\n> > > - Only supports ForwardScanDirection and once the scan direction\n> > > changes, streaming is never supported again -- even if we return to\n> > > ForwardScanDirection\n> > > - Must maintain a \"fallback\" codepath that does not use the streaming read API\n> >\n> > Attached is a version of this patch which implements a \"reset\"\n> > function for the streaming read API which should be cheaper than the\n> > full pg_streaming_read_free() on rescan. This can easily be ported to\n> > work on any of my proposed implementations (A/B/C). I implemented it\n> > on A as an example.\n>\n> Attached is the latest version of this patchset -- rebased in light of\n> Thomas' updatees to the streaming read API [1]. I have chosen the\n> approach I think we should go with. It is a hybrid of my previously\n> proposed approaches.\n\nWhile investigating some performance concerns, Andres pointed out that\nthe members I add to HeapScanDescData in this patch push rs_cindex and\nrs_ntuples to another cacheline and introduce a 4-byte hole. Attached\nv4's HeapScanDescData is as well-packed as on master and its members\nare reordered so that rs_cindex and rs_ntuples are back on the second\ncacheline of the struct's data.\n\n- Melanie",
"msg_date": "Sat, 2 Mar 2024 18:07:48 -0500",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Sat, Mar 02, 2024 at 06:07:48PM -0500, Melanie Plageman wrote:\n> On Wed, Feb 28, 2024 at 12:30 PM Melanie Plageman\n> <melanieplageman@gmail.com> wrote:\n> >\n> > On Mon, Feb 26, 2024 at 03:56:57PM -0500, Melanie Plageman wrote:\n> > > On Mon, Feb 19, 2024 at 6:05 PM Melanie Plageman\n> > > <melanieplageman@gmail.com> wrote:\n> > > >\n> > > > On Mon, Jan 29, 2024 at 4:17 PM Melanie Plageman\n> > > > <melanieplageman@gmail.com> wrote:\n> > > > >\n> > > > > There is an outstanding question about where to allocate the\n> > > > > PgStreamingRead object for sequential scans\n> > > >\n> > > > I've written three alternative implementations of the actual streaming\n> > > > read user for sequential scan which handle the question of where to\n> > > > allocate the streaming read object and how to handle changing scan\n> > > > direction in different ways.\n> > > >\n> > > > Option A) https://github.com/melanieplageman/postgres/tree/seqscan_pgsr_initscan_allocation\n> > > > - Allocates the streaming read object in initscan(). Since we do not\n> > > > know the scan direction at this time, if the scan ends up not being a\n> > > > forwards scan, the streaming read object must later be freed -- so\n> > > > this will sometimes allocate a streaming read object it never uses.\n> > > > - Only supports ForwardScanDirection and once the scan direction\n> > > > changes, streaming is never supported again -- even if we return to\n> > > > ForwardScanDirection\n> > > > - Must maintain a \"fallback\" codepath that does not use the streaming read API\n> > >\n> > > Attached is a version of this patch which implements a \"reset\"\n> > > function for the streaming read API which should be cheaper than the\n> > > full pg_streaming_read_free() on rescan. This can easily be ported to\n> > > work on any of my proposed implementations (A/B/C). I implemented it\n> > > on A as an example.\n> >\n> > Attached is the latest version of this patchset -- rebased in light of\n> > Thomas' updatees to the streaming read API [1]. I have chosen the\n> > approach I think we should go with. It is a hybrid of my previously\n> > proposed approaches.\n> \n> While investigating some performance concerns, Andres pointed out that\n> the members I add to HeapScanDescData in this patch push rs_cindex and\n> rs_ntuples to another cacheline and introduce a 4-byte hole. Attached\n> v4's HeapScanDescData is as well-packed as on master and its members\n> are reordered so that rs_cindex and rs_ntuples are back on the second\n> cacheline of the struct's data.\n\nI did some additional profiling and realized that dropping the\nunlikely() from the places we check rs_inited frequently was negatively\nimpacting performance. v5 adds those back and also makes a few other\nvery minor cleanups.\n\nNote that this patch set has a not yet released version of Thomas\nMunro's Streaming Read API with a new ramp-up logic which seems to fix a\nperformance issue I saw with my test case when all of the sequential\nscan's blocks are in shared buffers. Once he sends the official new\nversion, I will rebase this and point to his explanation in that thread.\n\n- Melanie",
"msg_date": "Fri, 8 Mar 2024 16:56:47 -0500",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Fri, Mar 8, 2024 at 4:56 PM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n>\n> On Sat, Mar 02, 2024 at 06:07:48PM -0500, Melanie Plageman wrote:\n> > On Wed, Feb 28, 2024 at 12:30 PM Melanie Plageman\n> > <melanieplageman@gmail.com> wrote:\n> > >\n> > > On Mon, Feb 26, 2024 at 03:56:57PM -0500, Melanie Plageman wrote:\n> > > > On Mon, Feb 19, 2024 at 6:05 PM Melanie Plageman\n> > > > <melanieplageman@gmail.com> wrote:\n> > > > >\n> > > > > On Mon, Jan 29, 2024 at 4:17 PM Melanie Plageman\n> > > > > <melanieplageman@gmail.com> wrote:\n> > > > > >\n> > > > > > There is an outstanding question about where to allocate the\n> > > > > > PgStreamingRead object for sequential scans\n> > > > >\n> > > > > I've written three alternative implementations of the actual streaming\n> > > > > read user for sequential scan which handle the question of where to\n> > > > > allocate the streaming read object and how to handle changing scan\n> > > > > direction in different ways.\n> > > > >\n> > > > > Option A) https://github.com/melanieplageman/postgres/tree/seqscan_pgsr_initscan_allocation\n> > > > > - Allocates the streaming read object in initscan(). Since we do not\n> > > > > know the scan direction at this time, if the scan ends up not being a\n> > > > > forwards scan, the streaming read object must later be freed -- so\n> > > > > this will sometimes allocate a streaming read object it never uses.\n> > > > > - Only supports ForwardScanDirection and once the scan direction\n> > > > > changes, streaming is never supported again -- even if we return to\n> > > > > ForwardScanDirection\n> > > > > - Must maintain a \"fallback\" codepath that does not use the streaming read API\n> > > >\n> > > > Attached is a version of this patch which implements a \"reset\"\n> > > > function for the streaming read API which should be cheaper than the\n> > > > full pg_streaming_read_free() on rescan. This can easily be ported to\n> > > > work on any of my proposed implementations (A/B/C). I implemented it\n> > > > on A as an example.\n> > >\n> > > Attached is the latest version of this patchset -- rebased in light of\n> > > Thomas' updatees to the streaming read API [1]. I have chosen the\n> > > approach I think we should go with. It is a hybrid of my previously\n> > > proposed approaches.\n> >\n> > While investigating some performance concerns, Andres pointed out that\n> > the members I add to HeapScanDescData in this patch push rs_cindex and\n> > rs_ntuples to another cacheline and introduce a 4-byte hole. Attached\n> > v4's HeapScanDescData is as well-packed as on master and its members\n> > are reordered so that rs_cindex and rs_ntuples are back on the second\n> > cacheline of the struct's data.\n>\n> I did some additional profiling and realized that dropping the\n> unlikely() from the places we check rs_inited frequently was negatively\n> impacting performance. v5 adds those back and also makes a few other\n> very minor cleanups.\n>\n> Note that this patch set has a not yet released version of Thomas\n> Munro's Streaming Read API with a new ramp-up logic which seems to fix a\n> performance issue I saw with my test case when all of the sequential\n> scan's blocks are in shared buffers. Once he sends the official new\n> version, I will rebase this and point to his explanation in that thread.\n\nAttached v6 has the version of the streaming read API mentioned here\n[1]. This resolved the fully-in-shared-buffers regressions\ninvestigated in that thread by Andres, Bilal, and Thomas.\n\nThe one outstanding item for the sequential scan streaming read user\nis deciding how the BAS_BULKREAD buffer access strategy should\ninteract with the streaming read infrastructure. We discussed a bit\noff-list, and it seems clear that the ring must be at least as large\nas io_combine_limit. This should be no problem for BAS_BULKREAD\nbecause its ring is 16 MB. The question is whether or not we need to\ndo anything right now to ensure there aren't adverse interactions\nbetween io_combine_limit, max_ios, and the buffer access strategy ring\nbuffer size.\n\n- Melanie\n\n[1] https://www.postgresql.org/message-id/CA%2BhUKGJTwrS7F%3DuJPx3SeigMiQiW%2BLJaOkjGyZdCntwyMR%3DuAw%40mail.gmail.com",
"msg_date": "Wed, 27 Mar 2024 20:47:03 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Wed, Mar 27, 2024 at 08:47:03PM -0400, Melanie Plageman wrote:\n> On Fri, Mar 8, 2024 at 4:56 PM Melanie Plageman\n> <melanieplageman@gmail.com> wrote:\n> >\n> > On Sat, Mar 02, 2024 at 06:07:48PM -0500, Melanie Plageman wrote:\n> > > On Wed, Feb 28, 2024 at 12:30 PM Melanie Plageman\n> > > <melanieplageman@gmail.com> wrote:\n> > > >\n> > > > On Mon, Feb 26, 2024 at 03:56:57PM -0500, Melanie Plageman wrote:\n> > > > > On Mon, Feb 19, 2024 at 6:05 PM Melanie Plageman\n> > > > > <melanieplageman@gmail.com> wrote:\n> > > > > >\n> > > > > > On Mon, Jan 29, 2024 at 4:17 PM Melanie Plageman\n> > > > > > <melanieplageman@gmail.com> wrote:\n> > > > > > >\n> > > > > > > There is an outstanding question about where to allocate the\n> > > > > > > PgStreamingRead object for sequential scans\n> > > > > >\n> > > > > > I've written three alternative implementations of the actual streaming\n> > > > > > read user for sequential scan which handle the question of where to\n> > > > > > allocate the streaming read object and how to handle changing scan\n> > > > > > direction in different ways.\n> > > > > >\n> > > > > > Option A) https://github.com/melanieplageman/postgres/tree/seqscan_pgsr_initscan_allocation\n> > > > > > - Allocates the streaming read object in initscan(). Since we do not\n> > > > > > know the scan direction at this time, if the scan ends up not being a\n> > > > > > forwards scan, the streaming read object must later be freed -- so\n> > > > > > this will sometimes allocate a streaming read object it never uses.\n> > > > > > - Only supports ForwardScanDirection and once the scan direction\n> > > > > > changes, streaming is never supported again -- even if we return to\n> > > > > > ForwardScanDirection\n> > > > > > - Must maintain a \"fallback\" codepath that does not use the streaming read API\n> > > > >\n> > > > > Attached is a version of this patch which implements a \"reset\"\n> > > > > function for the streaming read API which should be cheaper than the\n> > > > > full pg_streaming_read_free() on rescan. This can easily be ported to\n> > > > > work on any of my proposed implementations (A/B/C). I implemented it\n> > > > > on A as an example.\n> > > >\n> > > > Attached is the latest version of this patchset -- rebased in light of\n> > > > Thomas' updatees to the streaming read API [1]. I have chosen the\n> > > > approach I think we should go with. It is a hybrid of my previously\n> > > > proposed approaches.\n> > >\n> > > While investigating some performance concerns, Andres pointed out that\n> > > the members I add to HeapScanDescData in this patch push rs_cindex and\n> > > rs_ntuples to another cacheline and introduce a 4-byte hole. Attached\n> > > v4's HeapScanDescData is as well-packed as on master and its members\n> > > are reordered so that rs_cindex and rs_ntuples are back on the second\n> > > cacheline of the struct's data.\n> >\n> > I did some additional profiling and realized that dropping the\n> > unlikely() from the places we check rs_inited frequently was negatively\n> > impacting performance. v5 adds those back and also makes a few other\n> > very minor cleanups.\n> >\n> > Note that this patch set has a not yet released version of Thomas\n> > Munro's Streaming Read API with a new ramp-up logic which seems to fix a\n> > performance issue I saw with my test case when all of the sequential\n> > scan's blocks are in shared buffers. Once he sends the official new\n> > version, I will rebase this and point to his explanation in that thread.\n> \n> Attached v6 has the version of the streaming read API mentioned here\n> [1]. This resolved the fully-in-shared-buffers regressions\n> investigated in that thread by Andres, Bilal, and Thomas.\n\nAttached v7 has version 14 of the streaming read API as well as a few\nsmall tweaks to comments and code.\n\nI noticed that 0001 in the set posed a small regression from master for\na sequential scan of a relation already in shared buffers. While\ninvestigating this, I saw that heapfetchbuf() was still not being\ninlined (compiled at -O2) and when I promoted heapfetchbuf() from static\ninline to static pg_attribute_always_inline, most of the very small\nregression I saw went away. I don't know if I squashed the issue\nentirely, though.\n\n- Melanie",
"msg_date": "Mon, 1 Apr 2024 15:58:48 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On 01/04/2024 22:58, Melanie Plageman wrote:\n> Attached v7 has version 14 of the streaming read API as well as a few\n> small tweaks to comments and code.\n\nI saw benchmarks in this thread to show that there's no regression when \nthe data is in cache, but I didn't see any benchmarks demonstrating the \nbenefit of this. So I ran this quick test:\n\n-- create table ~1 GB table with only 1 row per page.\nCREATE TABLE giga (i int, filler text) with (fillfactor=10);\ninsert into giga select g, repeat('x', 900) from generate_series(1, \n140000) g;\nvacuum freeze giga;\n\n\\timing on\nselect count(*) from giga;\n\nThe SELECT takes about 390 ms on 'master', and 230 ms with the patch.\n\nThis is pretty much the best case for this patch, real world gains will \nbe much smaller. Nevertheless, nice speedup!\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Tue, 2 Apr 2024 20:10:37 +0300",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Tue, Apr 2, 2024 at 1:10 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> On 01/04/2024 22:58, Melanie Plageman wrote:\n> > Attached v7 has version 14 of the streaming read API as well as a few\n> > small tweaks to comments and code.\n>\n> I saw benchmarks in this thread to show that there's no regression when\n> the data is in cache, but I didn't see any benchmarks demonstrating the\n> benefit of this. So I ran this quick test:\n\nGood point! It would be good to show why we would actually want this\npatch. Attached v8 is rebased over current master (which now has the\nstreaming read API).\n\nOn the topic of BAS_BULKREAD buffer access strategy, I think the least\nwe could do is add an assert like this to read_stream_begin_relation()\nafter calculating max_pinned_buffers.\n\n Assert(GetAccessStrategyBufferCount(strategy) > max_pinned_buffers);\n\nPerhaps we should do more? I think with a ring size of 16 MB, large\nSELECTs are safe for now. But I know future developers will make\nchanges and it would be good not to assume they will understand that\npinning more buffers than the size of the ring effectively invalidates\nthe ring.\n\n- Melanie",
"msg_date": "Wed, 3 Apr 2024 13:02:57 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Thu, Apr 4, 2024 at 6:03 AM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n> On Tue, Apr 2, 2024 at 1:10 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> > On 01/04/2024 22:58, Melanie Plageman wrote:\n> > > Attached v7 has version 14 of the streaming read API as well as a few\n> > > small tweaks to comments and code.\n> >\n> > I saw benchmarks in this thread to show that there's no regression when\n> > the data is in cache, but I didn't see any benchmarks demonstrating the\n> > benefit of this. So I ran this quick test:\n>\n> Good point! It would be good to show why we would actually want this\n> patch. Attached v8 is rebased over current master (which now has the\n> streaming read API).\n\nAnecdotally by all reports I've seen so far, all-in-cache seems to be\nconsistently a touch faster than master if anything, for streaming seq\nscan and streaming ANALYZE. That's great!, but it doesn't seem to be\ndue to intentional changes. No efficiency is coming from batching\nanything. Perhaps it has to do with CPU pipelining effects: though\nit's doing the same work as ReadBuffer()-when-it-gets-a-hit, the work\nitself is cut up into stages in a kind of pipeline:\nread_stream_next_buffer() chooses page n + 2, pins page n + 1 and\nreturns page n each time you call it, so maybe we get more CPU\nparallelism due to spreading the data dependencies out? (Makes me\nwonder what happens if you insert a memory prefetch for the page\nheader into that production line, and if there are more opportunities\nto spread dependencies out eg hashing the buffer tag ahead of time.)\n\n> On the topic of BAS_BULKREAD buffer access strategy, I think the least\n> we could do is add an assert like this to read_stream_begin_relation()\n> after calculating max_pinned_buffers.\n>\n> Assert(GetAccessStrategyBufferCount(strategy) > max_pinned_buffers);\n>\n> Perhaps we should do more? I think with a ring size of 16 MB, large\n> SELECTs are safe for now. But I know future developers will make\n> changes and it would be good not to assume they will understand that\n> pinning more buffers than the size of the ring effectively invalidates\n> the ring.\n\nYeah I think we should clamp max_pinned_buffers if we see a strategy.\nWhat do you think about:\n\n if (strategy)\n {\n int strategy_buffers = GetAccessStrategyBufferCount(strategy);\n max_pinned_buffers = Min(strategy_buffers / 2, max_pinned_buffers);\n }\n\nI just don't know where to get that '2'. The idea would be to\nhopefully never actually be constrained by it in practice, except in\ntiny/toy setups, so we can't go too wrong with our number '2' there.\n\nThen we should increase the default ring sizes for BAS_BULKREAD and\nBAS_VACUUM to make the previous statement true. The size of main\nmemory and L2 cache have increased dramatically since those strategies\nwere invented. I think we should at least double them, and more\nlikely quadruple them. I realise you already made them configurable\nper command in commit 1cbbee033, but I mean the hard coded default 256\nin freelist.c. It's not only to get more space for our prefetching\nplans, it's also to give the system more chance of flushing WAL\nasynchronously/in some other backend before you crash into dirty data;\nas you discovered, prefetching accidentally makes that effect worse\nin.a BAS_VACUUM strategy, by taking away space that is effectively\ndeferring WAL flushes, so I'd at least like to double the size for if\nwe use \"/ 2\" above.\n\n\n",
"msg_date": "Thu, 4 Apr 2024 09:27:35 +1300",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Wed, Apr 3, 2024 at 4:28 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n>\n> On Thu, Apr 4, 2024 at 6:03 AM Melanie Plageman\n> <melanieplageman@gmail.com> wrote:\n> > On the topic of BAS_BULKREAD buffer access strategy, I think the least\n> > we could do is add an assert like this to read_stream_begin_relation()\n> > after calculating max_pinned_buffers.\n> >\n> > Assert(GetAccessStrategyBufferCount(strategy) > max_pinned_buffers);\n> >\n> > Perhaps we should do more? I think with a ring size of 16 MB, large\n> > SELECTs are safe for now. But I know future developers will make\n> > changes and it would be good not to assume they will understand that\n> > pinning more buffers than the size of the ring effectively invalidates\n> > the ring.\n>\n> Yeah I think we should clamp max_pinned_buffers if we see a strategy.\n> What do you think about:\n>\n> if (strategy)\n> {\n> int strategy_buffers = GetAccessStrategyBufferCount(strategy);\n> max_pinned_buffers = Min(strategy_buffers / 2, max_pinned_buffers);\n> }\n>\n> I just don't know where to get that '2'. The idea would be to\n> hopefully never actually be constrained by it in practice, except in\n> tiny/toy setups, so we can't go too wrong with our number '2' there.\n\nYea, I don't actually understand why not just use strategy_buffers - 1\nor something. 1/2 seems like a big limiting factor for those\nstrategies with small rings.\n\nI don't really think it will come up for SELECT queries since they\nrely on readahead and not prefetching.\nIt does seem like it could easily come up for analyze.\n\nBut I am on board with the idea of clamping for sequential scan/TID\nrange scan. For vacuum, we might have to think harder. If the user\nspecifies buffer_usage_limit and io_combine_limit and they are never\nreaching IOs of io_combine_limit because of their buffer_usage_limit\nvalue, then we should probably inform them.\n\n- Melanie\n\n\n",
"msg_date": "Wed, 3 Apr 2024 17:38:42 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "Hi,\n\nOn 2024-04-04 09:27:35 +1300, Thomas Munro wrote:\n> Anecdotally by all reports I've seen so far, all-in-cache seems to be\n> consistently a touch faster than master if anything, for streaming seq\n> scan and streaming ANALYZE. That's great!, but it doesn't seem to be\n> due to intentional changes. No efficiency is coming from batching\n> anything. Perhaps it has to do with CPU pipelining effects: though\n> it's doing the same work as ReadBuffer()-when-it-gets-a-hit, the work\n> itself is cut up into stages in a kind of pipeline:\n> read_stream_next_buffer() chooses page n + 2, pins page n + 1 and\n> returns page n each time you call it, so maybe we get more CPU\n> parallelism due to spreading the data dependencies out?\n\nAnother theory is that it's due to the plain ReadBuffer() path needing to do\nRelationGetSmgr(reln) on every call, whereas the streaming read path doesn't\nneed to.\n\n\n\n> > On the topic of BAS_BULKREAD buffer access strategy, I think the least\n> > we could do is add an assert like this to read_stream_begin_relation()\n> > after calculating max_pinned_buffers.\n> >\n> > Assert(GetAccessStrategyBufferCount(strategy) > max_pinned_buffers);\n> >\n> > Perhaps we should do more? I think with a ring size of 16 MB, large\n> > SELECTs are safe for now. But I know future developers will make\n> > changes and it would be good not to assume they will understand that\n> > pinning more buffers than the size of the ring effectively invalidates\n> > the ring.\n>\n> Yeah I think we should clamp max_pinned_buffers if we see a strategy.\n> What do you think about:\n>\n> if (strategy)\n> {\n> int strategy_buffers = GetAccessStrategyBufferCount(strategy);\n> max_pinned_buffers = Min(strategy_buffers / 2, max_pinned_buffers);\n> }\n\n> I just don't know where to get that '2'. The idea would be to\n> hopefully never actually be constrained by it in practice, except in\n> tiny/toy setups, so we can't go too wrong with our number '2' there.\n\nThe / 2 is to avoid causing unnecessarily frequent WAL flushes, right? If so,\nshould we apply that only if the ring the strategy doesn't use the\nStrategyRejectBuffer() logic?\n\nI think it's fine to add a handwavy justification for the 2, saying that we\nwant to balance readahead distance and reducing WAL write frequency, and that\nat some point more sophisticated logic will be needed.\n\n\n> Then we should increase the default ring sizes for BAS_BULKREAD and\n> BAS_VACUUM to make the previous statement true.\n\nI'm not sure it's right tying them together. The concerns for both are fairly\ndifferent.\n\n\n> The size of main memory and L2 cache have increased dramatically since those\n> strategies were invented. I think we should at least double them, and more\n> likely quadruple them. I realise you already made them configurable per\n> command in commit 1cbbee033, but I mean the hard coded default 256 in\n> freelist.c. It's not only to get more space for our prefetching plans, it's\n> also to give the system more chance of flushing WAL asynchronously/in some\n> other backend before you crash into dirty data; as you discovered,\n> prefetching accidentally makes that effect worse in.a BAS_VACUUM strategy,\n> by taking away space that is effectively deferring WAL flushes, so I'd at\n> least like to double the size for if we use \"/ 2\" above.\n\nI think for VACUUM we should probably go a bit further. There's no comparable\nL1/L2 issue, because the per-buffer processing + WAL insertion is a lot more\nexpensive, compared to a seqscan. I'd go or at lest 4x-8x.\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Wed, 3 Apr 2024 15:12:57 -0700",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Thu, 4 Apr 2024 at 06:03, Melanie Plageman <melanieplageman@gmail.com> wrote:\n> Attached v8 is rebased over current master (which now has the\n> streaming read API).\n\nI've looked at the v8-0001 patch.\n\nI wasn't too keen on heapbuildvis() as a function name for an external\nfunction. Since it also does pruning work, it seemed weird to make it\nsound like it only did visibility work. Per our offline discussion\nabout names, I've changed it to what you suggested which is\nheap_page_prep().\n\nAside from that, there was an outdated comment: \"In pageatatime mode,\nheapgetpage() already did visibility checks,\" which was no longer true\nas that's done in heapbuildvis() (now heap_page_prep()).\n\nI also did a round of comment adjustments as there were a few things I\ndidn't like, e.g:\n\n+ * heapfetchbuf - subroutine for heapgettup()\n\nThis is also used in heapgettup_pagemode(), so I thought it was a bad\nidea for a function to list places it thinks it's being called. I\nalso thought it redundant to write \"This routine\" in the function head\ncomment. I think \"this routine\" is implied by the context. I ended up\nwith:\n\n/*\n * heapfetchbuf - read and pin the given MAIN_FORKNUM block number.\n *\n * Read the specified block of the scan relation into a buffer and pin that\n * buffer before saving it in the scan descriptor.\n */\n\nI'm happy with your changes to heapam_scan_sample_next_block(). I did\nadjust the comment above CHECK_FOR_INTERRUPTS() so it was effectively\nthe same as the seqscan version, just with \"seqscan\" swapped for\n\"sample scan\".\n\nThe only other thing I adjusted there was to use \"blockno\" in some\nplaces where you were using hscan->rs_cblock. These all come after\nthe \"hscan->rs_cblock = blockno;\" line. My thoughts here are that this\nis more likely to avoid reading the value from the struct again if the\ncompiler isn't happy that the two values are still equivalent for some\nreason. Even if the compiler is happy today, it would only take a\ncode change to pass hscan to some external function for the compiler\nto perhaps be uncertain if that function has made an adjustment to\nrs_cblock and go with the safe option of pulling the value out the\nstruct again which is a little more expensive as it requires some\nmaths to figure out the offset.\n\nI've attached v9-0001 and a delta of just my changes from v8.\n\nDavid",
"msg_date": "Thu, 4 Apr 2024 14:08:34 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Wed, Apr 3, 2024 at 9:08 PM David Rowley <dgrowleyml@gmail.com> wrote:\n>\n> On Thu, 4 Apr 2024 at 06:03, Melanie Plageman <melanieplageman@gmail.com> wrote:\n> > Attached v8 is rebased over current master (which now has the\n> > streaming read API).\n>\n> I've looked at the v8-0001 patch.\n\nThanks for taking a look!\n\n> I wasn't too keen on heapbuildvis() as a function name for an external\n> function. Since it also does pruning work, it seemed weird to make it\n> sound like it only did visibility work. Per our offline discussion\n> about names, I've changed it to what you suggested which is\n> heap_page_prep().\n\nLooking at it in the code, I am wondering if we should call\nheap_page_prep() heap_scan_page_prep(). Just wondering if it is clear\nthat it is prepping a page to be scanned. You choose whatever you\nthink is best.\n\n> Aside from that, there was an outdated comment: \"In pageatatime mode,\n> heapgetpage() already did visibility checks,\" which was no longer true\n> as that's done in heapbuildvis() (now heap_page_prep()).\n>\n> I also did a round of comment adjustments as there were a few things I\n> didn't like, e.g:\n>\n> + * heapfetchbuf - subroutine for heapgettup()\n>\n> This is also used in heapgettup_pagemode(), so I thought it was a bad\n> idea for a function to list places it thinks it's being called. I\n> also thought it redundant to write \"This routine\" in the function head\n> comment. I think \"this routine\" is implied by the context. I ended up\n> with:\n>\n> /*\n> * heapfetchbuf - read and pin the given MAIN_FORKNUM block number.\n> *\n> * Read the specified block of the scan relation into a buffer and pin that\n> * buffer before saving it in the scan descriptor.\n> */\n>\n> I'm happy with your changes to heapam_scan_sample_next_block(). I did\n> adjust the comment above CHECK_FOR_INTERRUPTS() so it was effectively\n> the same as the seqscan version, just with \"seqscan\" swapped for\n> \"sample scan\".\n\nThat all is fine with me.\n\n> The only other thing I adjusted there was to use \"blockno\" in some\n> places where you were using hscan->rs_cblock. These all come after\n> the \"hscan->rs_cblock = blockno;\" line. My thoughts here are that this\n> is more likely to avoid reading the value from the struct again if the\n> compiler isn't happy that the two values are still equivalent for some\n> reason. Even if the compiler is happy today, it would only take a\n> code change to pass hscan to some external function for the compiler\n> to perhaps be uncertain if that function has made an adjustment to\n> rs_cblock and go with the safe option of pulling the value out the\n> struct again which is a little more expensive as it requires some\n> maths to figure out the offset.\n>\n> I've attached v9-0001 and a delta of just my changes from v8.\n\nAll sounds good and LGTM\n\n- Melanie\n\n\n",
"msg_date": "Wed, 3 Apr 2024 21:37:48 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Thu, 4 Apr 2024 at 14:38, Melanie Plageman <melanieplageman@gmail.com> wrote:\n> Looking at it in the code, I am wondering if we should call\n> heap_page_prep() heap_scan_page_prep(). Just wondering if it is clear\n> that it is prepping a page to be scanned. You choose whatever you\n> think is best.\n\nI ended up calling it heap_prepare_pagescan() as I started to think\nprep/prepare should come first. I don't think it's perfect as the\nintended meaning is heap_prepare_page_for_scanning_in_pagemode(), but\nthat's obviously too long.\n\nI've pushed the v9-0001 with that rename done.\n\nDavid\n\n\n",
"msg_date": "Thu, 4 Apr 2024 16:45:16 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Thu, 4 Apr 2024 at 16:45, David Rowley <dgrowleyml@gmail.com> wrote:\n> I've pushed the v9-0001 with that rename done.\n\nI've now just pushed the 0002 patch with some revisions:\n\n1. The function declarations you added for heapgettup_advance_block()\nand heapgettup_initial_block() didn't match the properties of their\ndefinitions. You'd declared both of these static inline but neither\nof these were.\n2. I felt inclined to rename heapfetchbuf() to heapfetchnextbuf() as\nthat's effectively what it does with v8-0002, however, that's just too\nmany words all shoved together, so I renamed it to\nheap_fetch_next_buffer().\n3. I changed heapgettup_initial_block() to pg_noinline as it both\nmakes more sense to have this out of line and it also fixed a small\nperformance regression.\n\nLooks like I also failed to grep for all the remaining instances of\n\"heapgetpage\" in 44086b097. Those are now fixed by 3a4a3537a.\n\nI also rebased the 0003 patch which I've attached as a raw patch.\n\nFWIW, using Heikki's test in [1] with a pg_prewarm each time after\nrestarting the instance. No parallel aggregate.\n\ndrowley@amd3990x:~$ cat bench.sql\n select count(*) from giga;\n\ndrowley@amd3990x:~$ pgbench -n -f bench.sql -T 120 postgres | grep latency\n\n44086b097~1\nlatency average = 34.323 ms\nlatency average = 34.332 ms\n\n44086b097\nlatency average = 34.811 ms\nlatency average = 34.862 ms\n\n3a4a3537a\nlatency average = 34.497 ms\nlatency average = 34.538 ms\n\n3a4a3537a + read_stream_for_seqscans.patch\nlatency average = 40.923 ms\nlatency average = 41.415 ms\n\ni.e. no meaningful change from the refactor, but a regression from a\ncached workload that changes the page often without doing much work in\nbetween with the read stread patch.\n\nI'm happy to run further benchmarks, but for the remainder of the\ncommitter responsibility for the next patches, I'm going to leave that\nto Thomas.\n\nDavid\n\n[1] https://www.postgresql.org/message-id/3b0f3701-addd-4629-9257-cf28e1a6e6a1@iki.fi",
"msg_date": "Thu, 4 Apr 2024 20:02:43 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Thu, Apr 4, 2024 at 11:13 AM Andres Freund <andres@anarazel.de> wrote:\n> The / 2 is to avoid causing unnecessarily frequent WAL flushes, right? If so,\n> should we apply that only if the ring the strategy doesn't use the\n> StrategyRejectBuffer() logic?\n\nHmm, I don't really know, but that sounds plausible. What do you\nthink about the attached?\n\n> I think for VACUUM we should probably go a bit further. There's no comparable\n> L1/L2 issue, because the per-buffer processing + WAL insertion is a lot more\n> expensive, compared to a seqscan. I'd go or at lest 4x-8x.\n\nAlright what about this?",
"msg_date": "Thu, 4 Apr 2024 22:31:57 +1300",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Thu, Apr 4, 2024 at 10:31 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> Alright what about this?\n\nForgot to git add a change, new version.",
"msg_date": "Thu, 4 Apr 2024 22:37:39 +1300",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Thu, Apr 4, 2024 at 8:02 PM David Rowley <dgrowleyml@gmail.com> wrote:\n> 3a4a3537a\n> latency average = 34.497 ms\n> latency average = 34.538 ms\n>\n> 3a4a3537a + read_stream_for_seqscans.patch\n> latency average = 40.923 ms\n> latency average = 41.415 ms\n>\n> i.e. no meaningful change from the refactor, but a regression from a\n> cached workload that changes the page often without doing much work in\n> between with the read stread patch.\n\nI ran Heikki's test except I ran the \"insert\" 4 times to get a table\nof 4376MB according to \\d+. On my random cloud ARM server (SB=8GB,\nhuge pages, parallelism disabled), I see a speedup 1290ms -> 1046ms\nwhen the data is in LInux cache and PG is not prewarmed, roughly as he\nreported. Good.\n\nIf I pg_prewarm first, I see that slowdown 260ms -> 294ms. Trying\nthings out to see what works, I got that down to 243ms (ie beat\nmaster) by inserting a memory prefetch:\n\n--- a/src/backend/storage/aio/read_stream.c\n+++ b/src/backend/storage/aio/read_stream.c\n@@ -757,6 +757,8 @@ read_stream_next_buffer(ReadStream *stream, void\n**per_buffer_data)\n /* Prepare for the next call. */\n read_stream_look_ahead(stream, false);\n\n+ __builtin_prefetch(BufferGetPage(stream->buffers[stream->oldest_buffer_index]));\n\nMaybe that's a solution to a different problem that just happens to\nmore than make up the difference in this case, and it may be\nquestionable whether that cache line will survive long enough to help\nyou, but this one-tuple-per-page test likes it... Hmm, to get a more\nrealistic table than the one-tuple-per-page on, I tried doubling a\ntenk1 table until it reached 2759MB and then I got a post-prewarm\nregression 702ms -> 721ms, and again I can beat master by memory\nprefetching: 689ms.\n\nAnnoyingly, with the same table I see no difference between the actual\npg_prewarm('giga') time: around 155ms for both. pg_prewarm is able to\nuse the 'fast path' I made pretty much just to be able to minimise\nregression in that (probably stupid) all-cached tes that doesn't even\nlook at the page contents. Unfortunately seq scan can't use it\nbecause it has per-buffer data, which is one of the things it can't do\n(because of a space management issue). Maybe I should try to find a\nway to fix that.\n\n> I'm happy to run further benchmarks, but for the remainder of the\n> committer responsibility for the next patches, I'm going to leave that\n> to Thomas.\n\nThanks!\n\n\n",
"msg_date": "Fri, 5 Apr 2024 00:45:12 +1300",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Thu, Apr 4, 2024 at 3:02 AM David Rowley <dgrowleyml@gmail.com> wrote:\n>\n> On Thu, 4 Apr 2024 at 16:45, David Rowley <dgrowleyml@gmail.com> wrote:\n> > I've pushed the v9-0001 with that rename done.\n>\n> I've now just pushed the 0002 patch with some revisions:\n\nThanks!\n\n> 1. The function declarations you added for heapgettup_advance_block()\n> and heapgettup_initial_block() didn't match the properties of their\n> definitions. You'd declared both of these static inline but neither\n> of these were.\n\nAh, they needed to be defined static but I intentionally left off the\ninline in the definition and only put it in the forward declaration\nbecause I thought that was correct. Anyway, I'm fine with how you did\nit in the end.\n\n> 2. I felt inclined to rename heapfetchbuf() to heapfetchnextbuf() as\n> that's effectively what it does with v8-0002, however, that's just too\n> many words all shoved together, so I renamed it to\n> heap_fetch_next_buffer().\n\nSounds good.\n\n> 3. I changed heapgettup_initial_block() to pg_noinline as it both\n> makes more sense to have this out of line and it also fixed a small\n> performance regression.\n\nAh, I guess it is in the unlikely path. I often forget that noinline\nexists. It's interesting that that made a noticeable difference since\nit is a pretty short function. Thanks for taking such a close look!\n\n> Looks like I also failed to grep for all the remaining instances of\n> \"heapgetpage\" in 44086b097. Those are now fixed by 3a4a3537a.\n>\n> I also rebased the 0003 patch which I've attached as a raw patch.\n\nThanks!\n\n> FWIW, using Heikki's test in [1] with a pg_prewarm each time after\n> restarting the instance. No parallel aggregate.\n>\n> drowley@amd3990x:~$ cat bench.sql\n> select count(*) from giga;\n>\n> drowley@amd3990x:~$ pgbench -n -f bench.sql -T 120 postgres | grep latency\n>\n> 44086b097~1\n> latency average = 34.323 ms\n> latency average = 34.332 ms\n>\n> 44086b097\n> latency average = 34.811 ms\n> latency average = 34.862 ms\n>\n> 3a4a3537a\n> latency average = 34.497 ms\n> latency average = 34.538 ms\n>\n> 3a4a3537a + read_stream_for_seqscans.patch\n> latency average = 40.923 ms\n> latency average = 41.415 ms\n>\n> i.e. no meaningful change from the refactor, but a regression from a\n> cached workload that changes the page often without doing much work in\n> between with the read stread patch.\n\nCool. Thanks for testing this out. Sounds like Thomas did some\nanalysis of how to resolve this for the streaming read user, and I\nwill do some too.\n\n- Melanie\n\n\n",
"msg_date": "Thu, 4 Apr 2024 09:47:50 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Thu, Apr 4, 2024 at 7:45 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n>\n> On Thu, Apr 4, 2024 at 8:02 PM David Rowley <dgrowleyml@gmail.com> wrote:\n> > 3a4a3537a\n> > latency average = 34.497 ms\n> > latency average = 34.538 ms\n> >\n> > 3a4a3537a + read_stream_for_seqscans.patch\n> > latency average = 40.923 ms\n> > latency average = 41.415 ms\n> >\n> > i.e. no meaningful change from the refactor, but a regression from a\n> > cached workload that changes the page often without doing much work in\n> > between with the read stread patch.\n>\n> I ran Heikki's test except I ran the \"insert\" 4 times to get a table\n> of 4376MB according to \\d+. On my random cloud ARM server (SB=8GB,\n> huge pages, parallelism disabled), I see a speedup 1290ms -> 1046ms\n> when the data is in LInux cache and PG is not prewarmed, roughly as he\n> reported. Good.\n>\n> If I pg_prewarm first, I see that slowdown 260ms -> 294ms. Trying\n> things out to see what works, I got that down to 243ms (ie beat\n> master) by inserting a memory prefetch:\n>\n> --- a/src/backend/storage/aio/read_stream.c\n> +++ b/src/backend/storage/aio/read_stream.c\n> @@ -757,6 +757,8 @@ read_stream_next_buffer(ReadStream *stream, void\n> **per_buffer_data)\n> /* Prepare for the next call. */\n> read_stream_look_ahead(stream, false);\n>\n> + __builtin_prefetch(BufferGetPage(stream->buffers[stream->oldest_buffer_index]));\n>\n> Maybe that's a solution to a different problem that just happens to\n> more than make up the difference in this case, and it may be\n> questionable whether that cache line will survive long enough to help\n> you, but this one-tuple-per-page test likes it... Hmm, to get a more\n> realistic table than the one-tuple-per-page on, I tried doubling a\n> tenk1 table until it reached 2759MB and then I got a post-prewarm\n> regression 702ms -> 721ms, and again I can beat master by memory\n> prefetching: 689ms.\n>\n> Annoyingly, with the same table I see no difference between the actual\n> pg_prewarm('giga') time: around 155ms for both. pg_prewarm is able to\n> use the 'fast path' I made pretty much just to be able to minimise\n> regression in that (probably stupid) all-cached tes that doesn't even\n> look at the page contents. Unfortunately seq scan can't use it\n> because it has per-buffer data, which is one of the things it can't do\n> (because of a space management issue). Maybe I should try to find a\n> way to fix that.\n\nSo, sequential scan does not have per-buffer data. I did some logging\nand the reason most fully-in-SB sequential scans don't use the fast\npath is because read_stream->pending_read_nblocks is always 0.\n\nWhen when read_stream->distance stays 1 (expected for all-in-SB as it\nis initialized to 1 and we don't want distance to ramp up),\nread_stream_look_ahead() never increments\nread_stream->pending_read_nblocks because it sets it to 1 the first\ntime it is called and then the conditions of the while loop are not\nmet again\n\n while (stream->ios_in_progress < stream->max_ios &&\n stream->pinned_buffers + stream->pending_read_nblocks <\nstream->distance)\n\ndistance is 1, pending_read_nblocks is 1, thus we only loop once and\ndon't increment pending_read_nblocks.\n\nprewarm is only able to use the fast path because it passes\nREAD_STREAM_FULL and thus initializes read_stream->distance to a\nhigher initial value.\n\nI added some logging to see if any of the sequential scans in the\nregression suite used the fast path. The one example I see of the fast\npath being used is a temp table IO stats test in\nsrc/test/regress/sql/stats.sql. I didn't check exactly what conditions\nled it to do this. But we probably want seq scans which are all in SB\nto use the fast path.\n\n- Melanie\n\n\n",
"msg_date": "Thu, 4 Apr 2024 11:20:35 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "Hi,\n\nOn 2024-04-04 22:37:39 +1300, Thomas Munro wrote:\n> On Thu, Apr 4, 2024 at 10:31 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> > Alright what about this?\n\nI think it's probably worth adding a bit more of the commit message to the\nfunction comment. Yes, there's a bit in one of the return branches, but that's\nnot what you're going to look at when just checking what the function does.\n\n\n> From e610bc78a2e3ecee50bd897e35084469d00bbac5 Mon Sep 17 00:00:00 2001\n> From: Thomas Munro <thomas.munro@gmail.com>\n> Date: Thu, 4 Apr 2024 21:11:06 +1300\n> Subject: [PATCH v2 2/2] Increase default vacuum_buffer_usage_limit to 2MB.\n> \n> The BAS_VACUUM ring size has been 256kB since commit d526575f. Commit\n> 1cbbee03 made it configurable but retained the traditional default.\n> The correct default size has been debated for years, but 256kB is\n> certainly very small. VACUUM soon needs to write back data it dirtied\n> only 32 blocks ago, which usually requires flushing the WAL. New\n> experiments in prefetching pages for VACUUM exacerbated the problem by\n> crashing into dirty data even sooner. Let's make the default 2MB.\n> That's 1.5% of the default toy buffer pool size, and 0.2% of 1GB, which\n> would be a considered a small shared_buffers setting for a real system\n> these days. Users are still free to set the GUC to a different value.\n\n+1. Independent of any other changes, this improves the default vacuum\nperformance substantially. We might want to dynamically size the default at\nsome point - but we probably should overhaul the infrastructure first...\n\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Thu, 4 Apr 2024 09:39:36 -0700",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Fri, Apr 5, 2024 at 4:20 AM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n> So, sequential scan does not have per-buffer data. I did some logging\n> and the reason most fully-in-SB sequential scans don't use the fast\n> path is because read_stream->pending_read_nblocks is always 0.\n\nHnghghghgh... right, sorry I guessed the wrong reason, it turns out\nthat I made a fast path just a little too specialised for pg_prewarm.\nWorking on it...\n\n\n",
"msg_date": "Fri, 5 Apr 2024 10:00:51 +1300",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "Yeah, I plead benchmarking myopia, sorry. The fastpath as committed\nis only reached when distance goes 2->1, as pg_prewarm does. Oops.\nWith the attached minor rearrangement, it works fine. I also poked\nsome more at that memory prefetcher. Here are the numbers I got on a\ndesktop system (Intel i9-9900 @ 3.1GHz, Linux 6.1, turbo disabled,\ncpufreq governor=performance, 2MB huge pages, SB=8GB, consumer NMVe,\nGCC -O3).\n\ncreate table t (i int, filler text) with (fillfactor=10);\ninsert into t\nselect g, repeat('x', 900) from generate_series(1, 560000) g;\nvacuum freeze t;\nset max_parallel_workers_per_gather = 0;\n\nselect count(*) from t;\n\ncold = must be read from actual disk (Linux drop_caches)\nwarm = read from linux page cache\nhot = already in pg cache via pg_prewarm\n\n cold warm hot\nmaster 2479ms 886ms 200ms\nseqscan 2498ms 716ms 211ms <-- regression\nseqscan + fastpath 2493ms 711ms 200ms <-- fixed, I think?\nseqscan + memprefetch 2499ms 716ms 182ms\nseqscan + fastpath + memprefetch 2505ms 710ms 170ms <-- \\O/\n\nCold has no difference. That's just my disk demonstrating Linux RA at\n128kB (default); random I/O is obviously a more interesting story.\nIt's consistently a smidgen faster with Linux RA set to 2MB (as in\nblockdev --setra 4096 /dev/nvmeXXX), and I believe this effect\nprobably also increases on fancier faster storage than what I have on\nhand:\n\n cold\nmaster 1775ms\nseqscan + fastpath + memprefetch 1700ms\n\nWarm is faster as expected (fewer system calls schlepping data\nkernel->userspace).\n\nThe interesting column is hot. The 200ms->211ms regression is due to\nthe extra bookkeeping in the slow path. The rejiggered fastpath code\nfixes it for me, or maybe sometimes shows an extra 1ms. Phew. Can\nyou reproduce that?\n\nThe memory prefetching trick, on top of that, seems to be a good\noptimisation so far. Note that that's not an entirely independent\ntrick, it's something we can only do now that we can see into the\nfuture; it's the next level up of prefetching, worth doing around 60ns\nbefore you need the data I guess. Who knows how thrashed the cache\nmight be before the caller gets around to accessing that page, but\nthere doesn't seem to be much of a cost or downside to this bet. We\nknow there are many more opportunities like that[1] but I don't want\nto second-guess the AM here, I'm just betting that the caller is going\nto look at the header.\n\nUnfortunately there seems to be a subtle bug hiding somewhere in here,\nvisible on macOS on CI. Looking into that, going to find my Mac...\n\n[1] https://www.postgresql.org/message-id/flat/CAApHDvpTRx7hqFZGiZJ%3Dd9JN4h1tzJ2%3Dxt7bM-9XRmpVj63psQ%40mail.gmail.com",
"msg_date": "Fri, 5 Apr 2024 17:14:53 +1300",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Thu, Apr 4, 2024 at 12:39 PM Andres Freund <andres@anarazel.de> wrote:\n>\n> On 2024-04-04 22:37:39 +1300, Thomas Munro wrote:\n> > On Thu, Apr 4, 2024 at 10:31 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> > > Alright what about this?\n>\n> I think it's probably worth adding a bit more of the commit message to the\n> function comment. Yes, there's a bit in one of the return branches, but that's\n> not what you're going to look at when just checking what the function does.\n\nAgreed about the comment. I kept thinking that BAS_BULKREAD should\nmaybe return nbuffers - 1, but I couldn't convince myself why.\nOtherwise v2-0001-Allow-BufferAccessStrategy-to-limit-pin-count LGTM.\n\n- Melanie\n\n\n",
"msg_date": "Fri, 5 Apr 2024 11:31:08 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Fri, Apr 5, 2024 at 12:15 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n>\n> Yeah, I plead benchmarking myopia, sorry. The fastpath as committed\n> is only reached when distance goes 2->1, as pg_prewarm does. Oops.\n> With the attached minor rearrangement, it works fine. I also poked\n> some more at that memory prefetcher. Here are the numbers I got on a\n> desktop system (Intel i9-9900 @ 3.1GHz, Linux 6.1, turbo disabled,\n> cpufreq governor=performance, 2MB huge pages, SB=8GB, consumer NMVe,\n> GCC -O3).\n>\n> create table t (i int, filler text) with (fillfactor=10);\n> insert into t\n> select g, repeat('x', 900) from generate_series(1, 560000) g;\n> vacuum freeze t;\n> set max_parallel_workers_per_gather = 0;\n>\n> select count(*) from t;\n>\n> cold = must be read from actual disk (Linux drop_caches)\n> warm = read from linux page cache\n> hot = already in pg cache via pg_prewarm\n>\n> cold warm hot\n> master 2479ms 886ms 200ms\n> seqscan 2498ms 716ms 211ms <-- regression\n> seqscan + fastpath 2493ms 711ms 200ms <-- fixed, I think?\n> seqscan + memprefetch 2499ms 716ms 182ms\n> seqscan + fastpath + memprefetch 2505ms 710ms 170ms <-- \\O/\n>\n> Cold has no difference. That's just my disk demonstrating Linux RA at\n> 128kB (default); random I/O is obviously a more interesting story.\n> It's consistently a smidgen faster with Linux RA set to 2MB (as in\n> blockdev --setra 4096 /dev/nvmeXXX), and I believe this effect\n> probably also increases on fancier faster storage than what I have on\n> hand:\n>\n> cold\n> master 1775ms\n> seqscan + fastpath + memprefetch 1700ms\n>\n> Warm is faster as expected (fewer system calls schlepping data\n> kernel->userspace).\n>\n> The interesting column is hot. The 200ms->211ms regression is due to\n> the extra bookkeeping in the slow path. The rejiggered fastpath code\n> fixes it for me, or maybe sometimes shows an extra 1ms. Phew. Can\n> you reproduce that?\n\nI am able to reproduce the fast path solving the issue using Heikki's\nexample here [1] but in shared buffers (hot).\n\nmaster: 25 ms\nstream read: 29 ms\nstream read + fast path: 25 ms\n\nI haven't looked into or reviewed the memory prefetching part.\n\nWhile reviewing 0002, I realized that I don't quite see how\nread_stream_get_block() will be used in the fastpath -- which it\nclaims in its comments.\nread_stream_next_buffer() is the only caller of\nread_stream_look_ahead()->read_stream_get_block(), and if fast_path is\ntrue, read_stream_next_buffer() always returns before calling\nread_stream_look_ahead(). Maybe I am missing something. I see\nfast_path uses read_stream_fill_blocknums() to invoke the callback.\n\nOh and why does READ_STREAM_DISABLE_FAST_PATH macro exist?\n\nOtherwise 0002 looks good to me.\n\nI haven't reviewed 0003 or 0004. I attached a new version (v11)\nbecause I noticed an outdated comment in my seq scan streaming read\nuser patch (0001). The other patches in the set are untouched from\nyour versions besides adding author/reviewer info in commit message\nfor 0002.\n\n- Melanie\n\n[1] https://www.postgresql.org/message-id/3b0f3701-addd-4629-9257-cf28e1a6e6a1%40iki.fi",
"msg_date": "Fri, 5 Apr 2024 13:55:37 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Sat, Apr 6, 2024 at 6:55 AM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n> On Fri, Apr 5, 2024 at 12:15 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> > The interesting column is hot. The 200ms->211ms regression is due to\n> > the extra bookkeeping in the slow path. The rejiggered fastpath code\n> > fixes it for me, or maybe sometimes shows an extra 1ms. Phew. Can\n> > you reproduce that?\n>\n> I am able to reproduce the fast path solving the issue using Heikki's\n> example here [1] but in shared buffers (hot).\n>\n> master: 25 ms\n> stream read: 29 ms\n> stream read + fast path: 25 ms\n\nGreat, thanks.\n\n> I haven't looked into or reviewed the memory prefetching part.\n>\n> While reviewing 0002, I realized that I don't quite see how\n> read_stream_get_block() will be used in the fastpath -- which it\n> claims in its comments.\n\nComments improved.\n\n> Oh and why does READ_STREAM_DISABLE_FAST_PATH macro exist?\n\nJust for testing purposes. Behaviour should be identical to external\nobservers either way, it's just a hand-rolled specialisation for\ncertain parameters, and it's useful to be able to verify that and\nmeasure the speedup. I think it's OK to leave a bit of\ndeveloper/testing scaffolding in the tree if it's likely to be useful\nagain and especially if like this case it doesn't create any dead\ncode. (Perhaps in later work we might find the right way to get the\ncompiler to do the specialisation? It's so simple though.)\n\nThe occasional CI problem I mentioned turned out to be\nread_stream_reset() remembering a little too much state across\nrescans. Fixed.\n\nThanks both for the feedback on the ring buffer tweaks. Comments\nupdated. Here is the full stack of patches I would like to commit\nvery soon, though I may leave the memory prefetching part out for a\nbit longer to see if I can find any downside.",
"msg_date": "Sat, 6 Apr 2024 12:28:19 +1300",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Fri, Apr 5, 2024 at 7:28 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n>\n> On Sat, Apr 6, 2024 at 6:55 AM Melanie Plageman\n> <melanieplageman@gmail.com> wrote:\n> > I haven't looked into or reviewed the memory prefetching part.\n> >\n> > While reviewing 0002, I realized that I don't quite see how\n> > read_stream_get_block() will be used in the fastpath -- which it\n> > claims in its comments.\n>\n> Comments improved.\n\nAh, makes sense now.\n\n> The occasional CI problem I mentioned turned out to be\n> read_stream_reset() remembering a little too much state across\n> rescans. Fixed.\n\nNice investigative work figuring this out.\n\n> Thanks both for the feedback on the ring buffer tweaks. Comments\n> updated. Here is the full stack of patches I would like to commit\n> very soon, though I may leave the memory prefetching part out for a\n> bit longer to see if I can find any downside.\n\n0001 LGTM. I did not review 0002 or 0003.\n\n0004 looks good except for one comment typo:\n\n /*\n * Tell call not to pin more than half the buffers in the ring.\n * This is a trade-off between look ahead distance and deferring\n * writeback and associated WAL traffic.\n */\n\ncall -> caller\n\n0006, I noticed the commit message is missing an important comma:\n\nInstead of calling ReadBuffer() for each block heap sequential scans and\nTID range scans now use the streaming read API introduced in b5a9b18cd0.\n\nshould be\n\nInstead of calling ReadBuffer() for each block, heap sequential scans and\nTID range scans now use the streaming read API introduced in b5a9b18cd0.\n\n- Melanie\n\n\n",
"msg_date": "Fri, 5 Apr 2024 22:00:01 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "I found a bug in read_stream.c that could be hit with Melanie's\nstreaming seq scan patch with parallelism enabled and certain buffer\npool conditions. Short version: there is an edge case where an \"if\"\nneeded to be a \"while\", or we could lose a few blocks. Here's the fix\nfor that, longer explanation in commit message.",
"msg_date": "Sun, 7 Apr 2024 13:25:11 +1200",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Sat, Apr 6, 2024 at 9:25 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n>\n> I found a bug in read_stream.c that could be hit with Melanie's\n> streaming seq scan patch with parallelism enabled and certain buffer\n> pool conditions. Short version: there is an edge case where an \"if\"\n> needed to be a \"while\", or we could lose a few blocks. Here's the fix\n> for that, longer explanation in commit message.\n\nAttached v13 0001 is your fix and 0002 is a new version of the\nsequential scan streaming read user. Off-list Andres mentioned that I\nreally ought to separate the parallel and serial sequential scan users\ninto two different callbacks. I've done that in the attached. It\nactually makes the code used by the callbacks nicer and more readable\nanyway (putting aside performance). I was able to measure a small\nperformance difference as well.\n\nI've also added a few comments and improved existing comments.\n\n- Melanie",
"msg_date": "Sat, 6 Apr 2024 21:33:51 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Sun, Apr 7, 2024 at 1:34 PM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n> Attached v13 0001 is your fix and 0002 is a new version of the\n> sequential scan streaming read user. Off-list Andres mentioned that I\n> really ought to separate the parallel and serial sequential scan users\n> into two different callbacks. I've done that in the attached. It\n> actually makes the code used by the callbacks nicer and more readable\n> anyway (putting aside performance). I was able to measure a small\n> performance difference as well.\n\nThanks. I changed a couple of very trivial things before pushing.\n\n+ BlockNumber (*cb) (ReadStream *pgsr, void *private_data,\n+ void *per_buffer_data);\n\nThis type has a friendly name: ReadStreamBlockNumberCB.\n\n+ scan->rs_read_stream =\nread_stream_begin_relation(READ_STREAM_SEQUENTIAL,\n\nI've been on the fence about that flag for sequential scan... Some\ndays I want to consider changing to READ_STREAM_DEFAULT and relying on\nour \"anti-heuristics\" to suppress advice, which would work out the\nsame in most cases but might occasionally win big. It might also\nhurt, I dunno, so I suspect we'd have to make it better first, which\nmy patch in [1] was a first swing at, but I haven't researched that\nenough. So, kept this way!\n\n- * Read the next block of the scan relation into a buffer and pin that buffer\n- * before saving it in the scan descriptor.\n+ * Read the next block of the scan relation from the read stream and pin that\n+ * buffer before saving it in the scan descriptor.\n\nChanged to:\n\n * Read the next block of the scan relation from the read stream and save it\n * in the scan descriptor. It is already pinned.\n\n+static BlockNumber\n+heap_scan_stream_read_next_parallel(ReadStream *pgsr, void *private_data,\n+ void *per_buffer_data)\n\nChanged argument names to match the function pointer type definition,\n\"stream\" and \"callback_private_data\".\n\nBTW looking at the branching in read-stream user patches that have an\ninitialisation step like yours, I wonder if it might every make sense\nto be able to change the callback on the fly from inside the callback,\nso that you finish up with a branchless one doing most of the work. I\nhave no idea if it's worth it...\n\n[1] https://www.postgresql.org/message-id/CA%2BhUKGLLFvou5rx5FDhm-Pc9r4STQTFFmrx6SUV%2Bvk8fwMbreA%40mail.gmail.com\n\n\n",
"msg_date": "Mon, 8 Apr 2024 09:36:59 +1200",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "Hi,\n\nOn 2024-04-08 09:36:59 +1200, Thomas Munro wrote:\n> I've been on the fence about that flag for sequential scan... Some\n> days I want to consider changing to READ_STREAM_DEFAULT and relying on\n> our \"anti-heuristics\" to suppress advice, which would work out the\n> same in most cases but might occasionally win big.\n\nAgreed, it's pretty easy to end up with a fairly \"fragmented\" set of a\nrelation's buffers in s_b. OTOH, there might not be any need for the\nheuristic if we actually trigger reads asynchronously.\n\n\n> BTW looking at the branching in read-stream user patches that have an\n> initialisation step like yours, I wonder if it might every make sense\n> to be able to change the callback on the fly from inside the callback,\n> so that you finish up with a branchless one doing most of the work. I\n> have no idea if it's worth it...\n\nI was wondering about that too, I dislike those branches. But instead of\nchanging the callback, it seems like a better design would be to have another\ndedicated callback for that? There already is a dedicated branch for the\n\"just starting up\" path in read_stream_next_buffer(), so it'd be pretty much\nfree to call another callback there.\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Sun, 7 Apr 2024 15:12:29 -0700",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "Hello,\n\nI decided to compare v17 vs v16 performance (as I did the last year [1])\nand discovered that v17 loses to v16 in the pg_tpcds (s64da_tpcds)\nbenchmark, query15 (and several others, but I focused on this one):\nBest pg-src-master--.* worse than pg-src-16--.* by 52.2 percents (229.84 > 151.03): pg_tpcds.query15\nAverage pg-src-master--.* worse than pg-src-16--.* by 53.4 percents (234.20 > 152.64): pg_tpcds.query15\nPlease look at the full html report attached in case you're interested.\n\n(I used my pg-mark tool to measure/analyze performance, but I believe the\nsame results can be seen without it.)\n\n`git bisect` for this performance degradation pointed at b7b0f3f27...\n\n[1] https://www.postgresql.org/message-id/b32bed1b-0746-9b20-1472-4bdc9ca66d52%40gmail.com\n\nBest regards,\nAlexander",
"msg_date": "Fri, 17 May 2024 16:00:00 +0300",
"msg_from": "Alexander Lakhin <exclusion@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Sat, May 18, 2024 at 1:00 AM Alexander Lakhin <exclusion@gmail.com> wrote:\n> I decided to compare v17 vs v16 performance (as I did the last year [1])\n> and discovered that v17 loses to v16 in the pg_tpcds (s64da_tpcds)\n> benchmark, query15 (and several others, but I focused on this one):\n> Best pg-src-master--.* worse than pg-src-16--.* by 52.2 percents (229.84 > 151.03): pg_tpcds.query15\n> Average pg-src-master--.* worse than pg-src-16--.* by 53.4 percents (234.20 > 152.64): pg_tpcds.query15\n> Please look at the full html report attached in case you're interested.\n>\n> (I used my pg-mark tool to measure/analyze performance, but I believe the\n> same results can be seen without it.)\n\nWill investigate, but if it's easy for you to rerun, does it help if\nyou increase Linux readahead, eg blockdev --setra setting?\n\n\n",
"msg_date": "Sat, 18 May 2024 08:09:47 +1200",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Sat, May 18, 2024 at 8:09 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> On Sat, May 18, 2024 at 1:00 AM Alexander Lakhin <exclusion@gmail.com> wrote:\n> > I decided to compare v17 vs v16 performance (as I did the last year [1])\n> > and discovered that v17 loses to v16 in the pg_tpcds (s64da_tpcds)\n> > benchmark, query15 (and several others, but I focused on this one):\n> > Best pg-src-master--.* worse than pg-src-16--.* by 52.2 percents (229.84 > 151.03): pg_tpcds.query15\n> > Average pg-src-master--.* worse than pg-src-16--.* by 53.4 percents (234.20 > 152.64): pg_tpcds.query15\n> > Please look at the full html report attached in case you're interested.\n> >\n> > (I used my pg-mark tool to measure/analyze performance, but I believe the\n> > same results can be seen without it.)\n>\n> Will investigate, but if it's easy for you to rerun, does it help if\n> you increase Linux readahead, eg blockdev --setra setting?\n\nAndres happened to have TPC-DS handy, and reproduced that regression\nin q15. We tried some stuff and figured out that it requires\nparallel_leader_participation=on, ie that this looks like some kind of\nparallel fairness and/or timing problem. It seems to be a question of\nwhich worker finishes up processing matching rows, and the leader gets\na ~10ms head start but may be a little more greedy with the new\nstreaming code. He tried reordering the table contents and then saw\n17 beat 16. So for q15, initial indications are that this isn't a\nfundamental regression, it's just a test that is sensitive to some\narbitrary conditions.\n\nI'll try to figure out some more details about that, ie is it being\ntoo greedy on small-ish tables, and generally I do wonder about the\ninteractions between the heuristics and batching working at different\nlevels (OS, seq scan, read stream, hence my earlier ra question which\nis likely a red herring) and how there might be unintended\nconsequences/interference patterns, but this particular case seems\nmore data dependent.\n\n\n",
"msg_date": "Sat, 18 May 2024 11:30:35 +1200",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Sat, May 18, 2024 at 11:30 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> Andres happened to have TPC-DS handy, and reproduced that regression\n> in q15. We tried some stuff and figured out that it requires\n> parallel_leader_participation=on, ie that this looks like some kind of\n> parallel fairness and/or timing problem. It seems to be a question of\n> which worker finishes up processing matching rows, and the leader gets\n> a ~10ms head start but may be a little more greedy with the new\n> streaming code. He tried reordering the table contents and then saw\n> 17 beat 16. So for q15, initial indications are that this isn't a\n> fundamental regression, it's just a test that is sensitive to some\n> arbitrary conditions.\n>\n> I'll try to figure out some more details about that, ie is it being\n> too greedy on small-ish tables,\n\nAfter more debugging, we learned a lot more things...\n\n1. That query produces spectacularly bad estimates, so we finish up\nhaving to increase the number of buckets in a parallel hash join many\ntimes. That is quite interesting, but unrelated to new code.\n2. Parallel hash join is quite slow at negotiating an increase in the\nnumber of hash bucket, if all of the input tuples are being filtered\nout by quals, because of the choice of where workers check for\nPHJ_GROWTH_NEED_MORE_BUCKETS. That could be improved quite easily I\nthink. I have put that on my todo list 'cause that's also my code,\nbut it's not a new issue it's just one that is now highlighted...\n3. This bit of read_stream.c is exacerbating unfairness in the\nunderlying scan, so that 1 and 2 come together and produce a nasty\nslowdown, which goes away if you change it like so:\n\n- BlockNumber blocknums[16];\n+ BlockNumber blocknums[1];\n\nI will follow up after some more study.\n\n\n",
"msg_date": "Sat, 18 May 2024 16:47:20 +1200",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "Hello Thomas,\n\n18.05.2024 07:47, Thomas Munro wrote:\n> After more debugging, we learned a lot more things...\n>\n> 1. That query produces spectacularly bad estimates, so we finish up\n> having to increase the number of buckets in a parallel hash join many\n> times. That is quite interesting, but unrelated to new code.\n> 2. Parallel hash join is quite slow at negotiating an increase in the\n> number of hash bucket, if all of the input tuples are being filtered\n> out by quals, because of the choice of where workers check for\n> PHJ_GROWTH_NEED_MORE_BUCKETS. That could be improved quite easily I\n> think. I have put that on my todo list 'cause that's also my code,\n> but it's not a new issue it's just one that is now highlighted...\n> 3. This bit of read_stream.c is exacerbating unfairness in the\n> underlying scan, so that 1 and 2 come together and produce a nasty\n> slowdown, which goes away if you change it like so:\n>\n> - BlockNumber blocknums[16];\n> + BlockNumber blocknums[1];\n>\n> I will follow up after some more study.\n\nThank you for the information!\n\nUnfortunately, I can't see significant differences in my environment with\nparallel_leader_participation=off.\n\nWith blocknums[1], timing is changed, but the effect is not persistent.\n10 query15 executions in a row, b7b0f3f27:\n277.932 ms\n281.805 ms\n278.335 ms\n281.565 ms\n284.167 ms\n283.171 ms\n281.165 ms\n281.615 ms\n285.394 ms\n277.301 ms\n\nb7b0f3f27~1:\n159.789 ms\n165.407 ms\n160.893 ms\n159.343 ms\n160.936 ms\n161.577 ms\n161.637 ms\n163.421 ms\n163.143 ms\n167.109 ms\n\nb7b0f3f27 + blocknums[1]:\n164.133 ms\n280.920 ms\n160.748 ms\n163.182 ms\n161.709 ms\n161.998 ms\n161.239 ms\n276.256 ms\n161.601 ms\n160.384 ms\n\nI placed PGDATA on tmpfs to rule out any blockdev specifics (increasing\nblockdev ra from 256 to 4096 didn't help me with PGDATA on NVME either.)\n\nBest regards,\nAlexander\n\n\n",
"msg_date": "Sat, 18 May 2024 22:00:00 +0300",
"msg_from": "Alexander Lakhin <exclusion@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Sun, May 19, 2024 at 7:00 AM Alexander Lakhin <exclusion@gmail.com> wrote:\n> With blocknums[1], timing is changed, but the effect is not persistent.\n> 10 query15 executions in a row, b7b0f3f27:\n> 277.932 ms\n> 281.805 ms\n> 278.335 ms\n> 281.565 ms\n> 284.167 ms\n> 283.171 ms\n> 281.165 ms\n> 281.615 ms\n> 285.394 ms\n> 277.301 ms\n\nThe bad time 10/10.\n\n> b7b0f3f27~1:\n> 159.789 ms\n> 165.407 ms\n> 160.893 ms\n> 159.343 ms\n> 160.936 ms\n> 161.577 ms\n> 161.637 ms\n> 163.421 ms\n> 163.143 ms\n> 167.109 ms\n\nThe good time 10/10.\n\n> b7b0f3f27 + blocknums[1]:\n> 164.133 ms\n> 280.920 ms\n> 160.748 ms\n> 163.182 ms\n> 161.709 ms\n> 161.998 ms\n> 161.239 ms\n> 276.256 ms\n> 161.601 ms\n> 160.384 ms\n\nThe good time 8/10, the bad time 2/10.\n\nThanks for checking! I bet all branches can show that flip/flop\ninstability in these adverse conditions, depending on random\nscheduling details. I will start a new thread with a patch for the\nroot cause of that, ie problem #2 (this will need back-patching), and\npost a fix for #3 (v17 blocknums[N] tweak affecting\nfairness/likelihood, which was probably basically a bit of ill-advised\npremature optimisation) here in a few days.\n\n\n",
"msg_date": "Sun, 19 May 2024 11:47:52 +1200",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "Thank you to all of you for looking into this.\n\nOn Sat, May 18, 2024 at 12:47 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n>\n> On Sat, May 18, 2024 at 11:30 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> > Andres happened to have TPC-DS handy, and reproduced that regression\n> > in q15. We tried some stuff and figured out that it requires\n> > parallel_leader_participation=on, ie that this looks like some kind of\n> > parallel fairness and/or timing problem. It seems to be a question of\n> > which worker finishes up processing matching rows, and the leader gets\n> > a ~10ms head start but may be a little more greedy with the new\n> > streaming code. He tried reordering the table contents and then saw\n> > 17 beat 16. So for q15, initial indications are that this isn't a\n> > fundamental regression, it's just a test that is sensitive to some\n> > arbitrary conditions.\n> >\n> > I'll try to figure out some more details about that, ie is it being\n> > too greedy on small-ish tables,\n>\n> After more debugging, we learned a lot more things...\n>\n> 1. That query produces spectacularly bad estimates, so we finish up\n> having to increase the number of buckets in a parallel hash join many\n> times. That is quite interesting, but unrelated to new code.\n> 2. Parallel hash join is quite slow at negotiating an increase in the\n> number of hash bucket, if all of the input tuples are being filtered\n> out by quals, because of the choice of where workers check for\n> PHJ_GROWTH_NEED_MORE_BUCKETS. That could be improved quite easily I\n> think. I have put that on my todo list 'cause that's also my code,\n> but it's not a new issue it's just one that is now highlighted...\n> 3. This bit of read_stream.c is exacerbating unfairness in the\n> underlying scan, so that 1 and 2 come together and produce a nasty\n> slowdown, which goes away if you change it like so:\n>\n> - BlockNumber blocknums[16];\n> + BlockNumber blocknums[1];\n>\n> I will follow up after some more study.\n\nSo, if you are seeing the slow-down mostly go away by reducing\nblocknums array size, does the regression only appear when the scan\ndata is fully in shared buffers? Or is this blocknums other use\n(dealing with short reads)?\n\nIs your theory that one worker ends up reading 16 blocks that should\nhave been distributed across multiple workers?\n\n- Melanie\n\n\n",
"msg_date": "Mon, 20 May 2024 17:10:57 -0400",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Tue, May 21, 2024 at 9:11 AM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n> So, if you are seeing the slow-down mostly go away by reducing\n> blocknums array size, does the regression only appear when the scan\n> data is fully in shared buffers? Or is this blocknums other use\n> (dealing with short reads)?\n\nThat must be true (that blocknums array is normally only \"filled\" in\nthe \"fast path\", where all buffers are found in cache).\n\n> Is your theory that one worker ends up reading 16 blocks that should\n> have been distributed across multiple workers?\n\nYes, it just jiggles the odds around a bit, introducing a bit of extra\nunfairness by calling the callback in a tighter loop to build a little\nbatch, revealing a pre-existing problem.\n\nThe mistake in PHJ (problem #2 above) is that, once a worker decides\nit would like all workers to stop inserting so it can increase the\nnumber of buckets, it sets a flag to ask them to do that, and waits\nfor them to see it, but if there is a worker filtering all tuples out,\nit never checks the \"growth\" flag. So it scans all the way to the end\nwhile the other guy waits. Normally it checks that flag when it is\ntime to allocate a new chunk of memory, which seemed to make sense to\nme at the time: if we've hit the needs-more-buckets (or\nneeds-more-batches) logic, then surely workers are inserting tuples\nand will soon allocate a new chunk! But, of course, here is the edge\ncase where that isn't true: we had bad estimates so hash table too\nsmall (problem #1), we got lots of tuples clustered over a few heap\npages and decided to expand the hash table, but right at that moment,\nmatching tuples ran out so somebody had to finish the whole scan\nwithout ever checking the flag (problem #2), and that someone happened\nto have all the rest of the pages because we made the lookahead a bit\nless fair (problem #3). Nice confluence of problems. I expect #2 and\n#3 to be easy to fix, and I didn't look at the estimation problem #1\nat all (perhaps a stats puzzle designed by the TPC to trip us up?).\n\n\n",
"msg_date": "Tue, 21 May 2024 09:34:52 +1200",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "Here's a really simple way to see the new unfairness at the end of a\nparallel scan:\n\ndrop table if exists t;\ncreate table t (i int);\ninsert into t select generate_series(1, 100000);\nalter table t set (parallel_workers = 2);\nset parallel_setup_cost = 0;\nset parallel_leader_participation = off;\nexplain (analyze, buffers, verbose) select count(*) from t;\n\nOn my machine, unpatched master shows:\n\n Worker 0: actual time=0.036..12.452 rows=51076 loops=1\n Buffers: shared hit=226\n Worker 1: actual time=0.037..12.003 rows=48924 loops=1\n Buffers: shared hit=217\n\nThe attached patch, which I'd like to push, is effectively what\nAlexander tested (blocknums[16] -> blocknums[1]). There's no point in\nusing an array of size 1, so I've turned it into a simple variable and\ndeleted the relevant comments. My machine shows:\n\n Worker 0: actual time=0.038..12.115 rows=49946 loops=1\n Buffers: shared hit=221\n Worker 1: actual time=0.038..12.109 rows=50054 loops=1\n Buffers: shared hit=222\n\nThat difference may not seem huge, but other pre-existing things are\ngoing pathologically wrong in the reported query that magnify it (see\nmy earlier analysis). It's an interesting problem that will require\nmore study (my earlier analysis missed a detail that I'll write about\nseparately), but it doesn't seem to be new or have easy fixes, so that\nwill have to be for later work.",
"msg_date": "Tue, 27 Aug 2024 18:52:44 +1200",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "Hello Thomas,\n\n27.08.2024 09:52, Thomas Munro wrote:\n> Here's a really simple way to see the new unfairness at the end of a\n> parallel scan:\n>\n> drop table if exists t;\n> create table t (i int);\n> insert into t select generate_series(1, 100000);\n> alter table t set (parallel_workers = 2);\n> set parallel_setup_cost = 0;\n> set parallel_leader_participation = off;\n> explain (analyze, buffers, verbose) select count(*) from t;\n>\n> On my machine, unpatched master shows:\n>\n> Worker 0: actual time=0.036..12.452 rows=51076 loops=1\n> Buffers: shared hit=226\n> Worker 1: actual time=0.037..12.003 rows=48924 loops=1\n> Buffers: shared hit=217\n>\n> The attached patch, which I'd like to push, is effectively what\n> Alexander tested (blocknums[16] -> blocknums[1]). There's no point in\n> using an array of size 1, so I've turned it into a simple variable and\n> deleted the relevant comments. My machine shows:\n>\n> Worker 0: actual time=0.038..12.115 rows=49946 loops=1\n> Buffers: shared hit=221\n> Worker 1: actual time=0.038..12.109 rows=50054 loops=1\n> Buffers: shared hit=222\n>\n> That difference may not seem huge, but other pre-existing things are\n> going pathologically wrong in the reported query that magnify it (see\n> my earlier analysis). It's an interesting problem that will require\n> more study (my earlier analysis missed a detail that I'll write about\n> separately), but it doesn't seem to be new or have easy fixes, so that\n> will have to be for later work.\n\nI've tried your query and could not get sustainable results, unfortunately.\nThe following script:\nrm -rf \"$PGDATA\"; initdb -D \"$PGDATA\" >initdb.log 2>&1\n\npg_ctl -s -l server.log start\n\ncat << EOF | psql | grep 'Parallel Seq Scan' -A10 | grep 'Worker ' -A1\ncreate table t (i int);\ninsert into t select generate_series(1, 100000);\nalter table t set (parallel_workers = 2);\nset parallel_setup_cost = 0;\nset parallel_leader_participation = off;\nexplain (analyze, buffers, verbose) select count(*) from t;\nEOF\n\npg_ctl -s stop\n\ngives me unstable numbers on unpatched master:\n Worker 0: actual time=0.024..5.814 rows=51076 loops=1\n Buffers: shared hit=226\n Worker 1: actual time=0.023..5.614 rows=48924 loops=1\n Buffers: shared hit=217\n---\n Worker 0: actual time=0.027..5.130 rows=36612 loops=1\n Buffers: shared hit=162\n Worker 1: actual time=0.013..5.605 rows=63388 loops=1\n Buffers: shared hit=281\n---\n Worker 0: actual time=0.025..5.447 rows=47460 loops=1\n Buffers: shared hit=210\n Worker 1: actual time=0.019..5.688 rows=52540 loops=1\n Buffers: shared hit=233\n\nand also with the patch applied:\n Worker 0: actual time=0.012..4.486 rows=55478 loops=1\n Buffers: shared hit=246\n Worker 1: actual time=0.014..4.430 rows=44522 loops=1\n Buffers: shared hit=197\n---\n Worker 0: actual time=0.013..4.269 rows=55822 loops=1\n Buffers: shared hit=247\n Worker 1: actual time=0.017..4.238 rows=44178 loops=1\n Buffers: shared hit=196\n---\n Worker 0: actual time=0.014..4.974 rows=50624 loops=1\n Buffers: shared hit=224\n Worker 1: actual time=0.016..4.932 rows=49376 loops=1\n Buffers: shared hit=219\n---\n Worker 0: actual time=0.012..5.459 rows=65648 loops=1\n Buffers: shared hit=291\n Worker 1: actual time=0.022..5.109 rows=34352 loops=1\n Buffers: shared hit=152\n\nPlease correct me, if I'm doing something wrong.\n\nBest regards,\nAlexander\n\n\n",
"msg_date": "Tue, 27 Aug 2024 16:00:00 +0300",
"msg_from": "Alexander Lakhin <exclusion@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Wed, Aug 28, 2024 at 1:00 AM Alexander Lakhin <exclusion@gmail.com> wrote:\n> gives me unstable numbers on unpatched master:\n> Buffers: shared hit=226\n> Buffers: shared hit=217\n\n> Buffers: shared hit=162\n> Buffers: shared hit=281\n\n> Buffers: shared hit=210\n> Buffers: shared hit=233\n\n> and also with the patch applied:\n> Buffers: shared hit=246\n> Buffers: shared hit=197\n\n> Buffers: shared hit=247\n> Buffers: shared hit=196\n\n> Buffers: shared hit=224\n> Buffers: shared hit=219\n\n> Buffers: shared hit=291\n> Buffers: shared hit=152\n>\n> Please correct me, if I'm doing something wrong.\n\nHuh. I can reproduce what I showed with pretty low variance, on my\nFreeBSD, Linux and macOS systems. I included\nparallel_leader_participation=off so that the workers would hopefully\nstart as closely together in time as possible, and hopefully allow\nonly a block or so of variation in the outcome. If I do:\n\ncreate or replace function f(i int) returns int language plpgsql\nparallel safe as $$\nbegin\n raise notice '% pid %', clock_timestamp(), pg_backend_pid();\n return i;\nend;\n$$;\n\nthen\n\npostgres=# explain (analyze) select f(i) from t limit 1;\nNOTICE: 2024-08-28 16:41:32.845747+12 pid 47019\nNOTICE: 2024-08-28 16:41:32.845746+12 pid 47018\n\nshows start times differ by only a few microseconds at most, often 0.\nI wonder if your system is more variable at beginning execution?\nMaybe you're on a multi-socket system and forking/startup times vary\nin some way I can't see on small systems or something like that?\n\n\n",
"msg_date": "Wed, 28 Aug 2024 16:45:45 +1200",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "28.08.2024 07:45, Thomas Munro wrote:\n> Huh. I can reproduce what I showed with pretty low variance, on my\n> FreeBSD, Linux and macOS systems. I included\n> parallel_leader_participation=off so that the workers would hopefully\n> start as closely together in time as possible, and hopefully allow\n> only a block or so of variation in the outcome. If I do:\n>\n> create or replace function f(i int) returns int language plpgsql\n> parallel safe as $$\n> begin\n> raise notice '% pid %', clock_timestamp(), pg_backend_pid();\n> return i;\n> end;\n> $$;\n>\n> then\n>\n> postgres=# explain (analyze) select f(i) from t limit 1;\n> NOTICE: 2024-08-28 16:41:32.845747+12 pid 47019\n> NOTICE: 2024-08-28 16:41:32.845746+12 pid 47018\n>\n> shows start times differ by only a few microseconds at most, often 0.\n> I wonder if your system is more variable at beginning execution?\n> Maybe you're on a multi-socket system and forking/startup times vary\n> in some way I can't see on small systems or something like that?\n\nI use a single-socket system with AMD Ryzen 5900X, running Ubuntu 20.04.\nWith no active background tasks running, I'm seeing:\nNOTICE: 2024-08-28 08:17:36.917162+00 pid 320103\nNOTICE: 2024-08-28 08:17:36.917163+00 pid 320102\n\nNOTICE: 2024-08-28 08:17:40.592333+00 pid 320143\nNOTICE: 2024-08-28 08:17:40.592645+00 pid 320144\n\nWith log_min_messages = DEBUG3, I get:\nNOTICE: 2024-08-28 08:41:59.309364+00 pid 338263\nNOTICE: 2024-08-28 08:41:59.310079+00 pid 338264\n\nAnd the following messages in the server.log:\n2024-08-28 08:41:59.304 UTC [338251] DEBUG: starting background worker process \"parallel worker for PID 338262\"\n2024-08-28 08:41:59.304 UTC [338251] DEBUG: starting background worker process \"parallel worker for PID 338262\"\n2024-08-28 08:41:59.305 UTC [338263] DEBUG: InitPostgres\n2024-08-28 08:41:59.305 UTC [338264] DEBUG: InitPostgres\n2024-08-28 08:41:59.309 UTC [338263] NOTICE: 2024-08-28 08:41:59.309364+00 pid 338263\n2024-08-28 08:41:59.309 UTC [338263] CONTEXT: PL/pgSQL function f(integer) line 3 at RAISE\n2024-08-28 08:41:59.309 UTC [338262] NOTICE: 2024-08-28 08:41:59.309364+00 pid 338263\n2024-08-28 08:41:59.309 UTC [338262] CONTEXT: PL/pgSQL function f(integer) line 3 at RAISE\n parallel worker\n2024-08-28 08:41:59.309 UTC [338263] DEBUG: shmem_exit(0): 5 before_shmem_exit callbacks to make\n2024-08-28 08:41:59.309 UTC [338263] DEBUG: shmem_exit(0): 6 on_shmem_exit callbacks to make\n2024-08-28 08:41:59.309 UTC [338263] DEBUG: proc_exit(0): 1 callbacks to make\n2024-08-28 08:41:59.309 UTC [338263] DEBUG: exit(0)\n2024-08-28 08:41:59.309 UTC [338263] DEBUG: shmem_exit(-1): 0 before_shmem_exit callbacks to make\n2024-08-28 08:41:59.309 UTC [338263] DEBUG: shmem_exit(-1): 0 on_shmem_exit callbacks to make\n2024-08-28 08:41:59.309 UTC [338263] DEBUG: proc_exit(-1): 0 callbacks to make\n2024-08-28 08:41:59.310 UTC [338264] NOTICE: 2024-08-28 08:41:59.310079+00 pid 338264\n2024-08-28 08:41:59.310 UTC [338264] CONTEXT: PL/pgSQL function f(integer) line 3 at RAISE\n\nIt looks like the two parallel workers were started simultaneously, but\nthen the second one lagged behind...\n\nBest regards,\nAlexander\n\n\n",
"msg_date": "Wed, 28 Aug 2024 12:00:00 +0300",
"msg_from": "Alexander Lakhin <exclusion@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Wed, Aug 28, 2024 at 9:00 PM Alexander Lakhin <exclusion@gmail.com> wrote:\n> 2024-08-28 08:41:59.304 UTC [338251] DEBUG: starting background worker process \"parallel worker for PID 338262\"\n> 2024-08-28 08:41:59.304 UTC [338251] DEBUG: starting background worker process \"parallel worker for PID 338262\"\n\n> 2024-08-28 08:41:59.305 UTC [338263] DEBUG: InitPostgres\n> 2024-08-28 08:41:59.305 UTC [338264] DEBUG: InitPostgres\n\n> 2024-08-28 08:41:59.309 UTC [338263] NOTICE: 2024-08-28 08:41:59.309364+00 pid 338263\n> 2024-08-28 08:41:59.310 UTC [338264] NOTICE: 2024-08-28 08:41:59.310079+00 pid 338264\n\n> It looks like the two parallel workers were started simultaneously, but\n> then the second one lagged behind...\n\nYeah. That's quite interesting, and must destabilise that\nsimple-minded demo. I'm curious to know exactly what contention is\ncausing that (about 3/4 of a millisecond that I don't see and now I\nwant to know what it's waiting for), but it's a very crude test\nlacking timer resolution in the earlier messages, and it's an\nunrelated topic and a distraction. Perhaps it explains why you saw\ntwo different behaviours in Q15 with the patch and I didn't, though.\nReally it shouldn't be so sensitive to such variations, it's obviously\na terrible plan, and TPC-DS needs a planner hacker mega-brain applied\nto it; I'm going to try to nerd-snipe one...\n\n\n",
"msg_date": "Thu, 29 Aug 2024 10:16:46 +1200",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "Hello Thomas,\n\n29.08.2024 01:16, Thomas Munro wrote:\n> Yeah. That's quite interesting, and must destabilise that\n> simple-minded demo. I'm curious to know exactly what contention is\n> causing that (about 3/4 of a millisecond that I don't see and now I\n> want to know what it's waiting for), but it's a very crude test\n> lacking timer resolution in the earlier messages, and it's an\n> unrelated topic and a distraction. Perhaps it explains why you saw\n> two different behaviours in Q15 with the patch and I didn't, though.\n> Really it shouldn't be so sensitive to such variations, it's obviously\n> a terrible plan, and TPC-DS needs a planner hacker mega-brain applied\n> to it; I'm going to try to nerd-snipe one...\n\nI looked at two perf profiles of such out-of-sync processes and found no\nextra calls or whatsoever in the slow one, it just has the number of perf\nsamples increased proportionally. It made me suspect CPU frequency\nscaling... Indeed, with the \"performance\" governor set and the boost mode\ndisabled, I'm now seeing much more stable numbers (I do this tuning before\nrunning performance tests, but I had forgotten about that when I ran that\nyour test, my bad).\n\nI'm sorry for the noise and the distraction.\n\nStill, now I can confirm your results. Without the patch, two parallel\nworkers gave \"Buffers: shared hit=217 / Buffers: shared hit=226\" 10 times\nout of 10. And with the patch, I've got\n\"shared hit=219 / shared hit=224\" 3 times,\n\"shared hit=220 / shared hit=223\" 4 times,\n\"shared hit=221 / shared hit=222\" 3 times of 10.\n\nOn b7b0f3f27~1, my results are:\n\"shared hit=219 / shared hit=224\": 2\n\"shared hit=220 / shared hit=223\": 3\n\"shared hit=221 / shared hit=222\": 4\n\"shared hit=218 / shared hit=225\": 1\n\nBest regards,\nAlexander\n\n\n",
"msg_date": "Thu, 29 Aug 2024 16:00:00 +0300",
"msg_from": "Alexander Lakhin <exclusion@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
},
{
"msg_contents": "On Fri, Aug 30, 2024 at 1:00 AM Alexander Lakhin <exclusion@gmail.com> wrote:\n> I looked at two perf profiles of such out-of-sync processes and found no\n> extra calls or whatsoever in the slow one, it just has the number of perf\n> samples increased proportionally. It made me suspect CPU frequency\n> scaling... Indeed, with the \"performance\" governor set and the boost mode\n> disabled, I'm now seeing much more stable numbers (I do this tuning before\n> running performance tests, but I had forgotten about that when I ran that\n> your test, my bad).\n\nAha, mystery solved.\n\nI have pushed the fix. Thanks!\n\n\n",
"msg_date": "Sat, 31 Aug 2024 17:38:33 +1200",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Streaming read-ready sequential scan code"
}
] |
[
{
"msg_contents": "While taking care of a Pgpool-II trouble report from user [1], I found\nan interesting usage pattern of the extended query protocol. In my\nunderstanding a series of queries in the extended query protocol is\nended by a sync message. Then one ReadyForQuery response comes for one\nsync message. However this does not apply if simple query message is\nsent instead of sync.\n\nBelow is outputs from \"pgproto\" command coming with Pgpool-II.\n(Lines starting \"FE\" represents a message from frontend to backend.\nLines starting \"BE\" represents a message from backend to frontend.)\n\nFE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\nFE=> Bind(stmt=\"\", portal=\"\")\nFE=> Execute(portal=\"\")\nFE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\nFE=> Bind(stmt=\"\", portal=\"\")\nFE=> Execute(portal=\"\")\nFE=> Query (query=\"SET extra_float_digits = 3\")\n<= BE ParseComplete\n<= BE BindComplete\n<= BE CommandComplete(SET)\n<= BE ParseComplete\n<= BE BindComplete\n<= BE CommandComplete(SET)\n<= BE CommandComplete(SET)\n<= BE ReadyForQuery(I)\nFE=> Terminate\n\nAs you can see, two \"SET extra_float_digits = 3\" is sent in the\nextended query protocol, then one \"SET extra_float_digits = 3\" follows\nin the simple query protocol. No sync message is sent. However, I get\nReadyForQuery at the end. It seems the extended query protocol is\nended by a simple query protocol message instead of a sync message.\n\nMy question is, is this legal in terms of fronted/backend protocol?\nIf it's legal, I think we'd better to explicitly mention in our\ndocument. Otherwise, users may be confused. For example, in\n\"55.2.4. Pipelining\":\n\n\"When using this method, completion of the pipeline must be determined\nby counting ReadyForQuery messages and waiting for that to reach the\nnumber of Syncs sent.\"\n\nApparently this does not apply to the above example because there's 0\nsync message.\n\nBest reagards,\n\n[1] https://www.pgpool.net/pipermail/pgpool-general/2023-December/009051.html\n--\nTatsuo Ishii\nSRA OSS LLC\nEnglish: http://www.sraoss.co.jp/index_en/\nJapanese:http://www.sraoss.co.jp\n\n\n",
"msg_date": "Tue, 30 Jan 2024 08:22:57 +0900 (JST)",
"msg_from": "Tatsuo Ishii <ishii@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "When extended query protocol ends?"
},
{
"msg_contents": "Tatsuo Ishii <ishii@sraoss.co.jp> writes:\n> Below is outputs from \"pgproto\" command coming with Pgpool-II.\n> (Lines starting \"FE\" represents a message from frontend to backend.\n> Lines starting \"BE\" represents a message from backend to frontend.)\n\n> FE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\n> FE=> Bind(stmt=\"\", portal=\"\")\n> FE=> Execute(portal=\"\")\n> FE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\n> FE=> Bind(stmt=\"\", portal=\"\")\n> FE=> Execute(portal=\"\")\n> FE=> Query (query=\"SET extra_float_digits = 3\")\n> <= BE ParseComplete\n> <= BE BindComplete\n> <= BE CommandComplete(SET)\n> <= BE ParseComplete\n> <= BE BindComplete\n> <= BE CommandComplete(SET)\n> <= BE CommandComplete(SET)\n> <= BE ReadyForQuery(I)\n> FE=> Terminate\n\n> As you can see, two \"SET extra_float_digits = 3\" is sent in the\n> extended query protocol, then one \"SET extra_float_digits = 3\" follows\n> in the simple query protocol. No sync message is sent. However, I get\n> ReadyForQuery at the end. It seems the extended query protocol is\n> ended by a simple query protocol message instead of a sync message.\n\n> My question is, is this legal in terms of fronted/backend protocol?\n\nI think it's poor practice, at best. You should end the\nextended-protocol query cycle before invoking simple query.\n\nI'm disinclined to document, or make any promises about,\nwhat happens if you mix the protocols.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Mon, 29 Jan 2024 18:40:15 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "Hello Dave,\n\n> Tatsuo Ishii <ishii@sraoss.co.jp> writes:\n>> Below is outputs from \"pgproto\" command coming with Pgpool-II.\n>> (Lines starting \"FE\" represents a message from frontend to backend.\n>> Lines starting \"BE\" represents a message from backend to frontend.)\n> \n>> FE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\n>> FE=> Bind(stmt=\"\", portal=\"\")\n>> FE=> Execute(portal=\"\")\n>> FE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\n>> FE=> Bind(stmt=\"\", portal=\"\")\n>> FE=> Execute(portal=\"\")\n>> FE=> Query (query=\"SET extra_float_digits = 3\")\n>> <= BE ParseComplete\n>> <= BE BindComplete\n>> <= BE CommandComplete(SET)\n>> <= BE ParseComplete\n>> <= BE BindComplete\n>> <= BE CommandComplete(SET)\n>> <= BE CommandComplete(SET)\n>> <= BE ReadyForQuery(I)\n>> FE=> Terminate\n> \n>> As you can see, two \"SET extra_float_digits = 3\" is sent in the\n>> extended query protocol, then one \"SET extra_float_digits = 3\" follows\n>> in the simple query protocol. No sync message is sent. However, I get\n>> ReadyForQuery at the end. It seems the extended query protocol is\n>> ended by a simple query protocol message instead of a sync message.\n> \n>> My question is, is this legal in terms of fronted/backend protocol?\n> \n> I think it's poor practice, at best. You should end the\n> extended-protocol query cycle before invoking simple query.\n\n From [1] I think the JDBC driver sends something like below if\nautosave=always option is specified.\n\n\"BEGIN READ ONLY\" Parse/Bind/Eexecute (in the extended query protocol)\n\"SAVEPOINT PGJDBC_AUTOSAVE\" (in the simple query protocol) \n\nIt seems the SAVEPOINT is sent without finishing the extended query\nprotocol (i.e. without Sync message). Is it possible for the JDBC\ndriver to issue a Sync message before sending SAVEPOINT in simple\nquery protocol? Or you can send SAVEPOINT using the extended query\nprotocol.\n\n[1] https://www.pgpool.net/pipermail/pgpool-general/2023-December/009051.html\n\nBest reagards,\n--\nTatsuo Ishii\nSRA OSS LLC\nEnglish: http://www.sraoss.co.jp/index_en/\nJapanese:http://www.sraoss.co.jp\n\n\n",
"msg_date": "Tue, 30 Jan 2024 10:15:50 +0900 (JST)",
"msg_from": "Tatsuo Ishii <ishii@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "On Mon, 29 Jan 2024 at 20:15, Tatsuo Ishii <ishii@sraoss.co.jp> wrote:\n\n> Hello Dave,\n>\n> > Tatsuo Ishii <ishii@sraoss.co.jp> writes:\n> >> Below is outputs from \"pgproto\" command coming with Pgpool-II.\n> >> (Lines starting \"FE\" represents a message from frontend to backend.\n> >> Lines starting \"BE\" represents a message from backend to frontend.)\n> >\n> >> FE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\n> >> FE=> Bind(stmt=\"\", portal=\"\")\n> >> FE=> Execute(portal=\"\")\n> >> FE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\n> >> FE=> Bind(stmt=\"\", portal=\"\")\n> >> FE=> Execute(portal=\"\")\n> >> FE=> Query (query=\"SET extra_float_digits = 3\")\n> >> <= BE ParseComplete\n> >> <= BE BindComplete\n> >> <= BE CommandComplete(SET)\n> >> <= BE ParseComplete\n> >> <= BE BindComplete\n> >> <= BE CommandComplete(SET)\n> >> <= BE CommandComplete(SET)\n> >> <= BE ReadyForQuery(I)\n> >> FE=> Terminate\n> >\n> >> As you can see, two \"SET extra_float_digits = 3\" is sent in the\n> >> extended query protocol, then one \"SET extra_float_digits = 3\" follows\n> >> in the simple query protocol. No sync message is sent. However, I get\n> >> ReadyForQuery at the end. It seems the extended query protocol is\n> >> ended by a simple query protocol message instead of a sync message.\n> >\n> >> My question is, is this legal in terms of fronted/backend protocol?\n> >\n> > I think it's poor practice, at best. You should end the\n> > extended-protocol query cycle before invoking simple query.\n>\n> From [1] I think the JDBC driver sends something like below if\n> autosave=always option is specified.\n>\n> \"BEGIN READ ONLY\" Parse/Bind/Eexecute (in the extended query protocol)\n> \"SAVEPOINT PGJDBC_AUTOSAVE\" (in the simple query protocol)\n>\n> It seems the SAVEPOINT is sent without finishing the extended query\n> protocol (i.e. without Sync message). Is it possible for the JDBC\n> driver to issue a Sync message before sending SAVEPOINT in simple\n> query protocol? Or you can send SAVEPOINT using the extended query\n> protocol.\n>\n> [1]\n> https://www.pgpool.net/pipermail/pgpool-general/2023-December/009051.html\n>\n>\nHi Tatsuo,\n\nYes, it would be possible.\n\nCan you create an issue on github? Issues · pgjdbc/pgjdbc (github.com)\n<https://github.com/pgjdbc/pgjdbc/issues>\n\nDave\n\nOn Mon, 29 Jan 2024 at 20:15, Tatsuo Ishii <ishii@sraoss.co.jp> wrote:Hello Dave,\n\n> Tatsuo Ishii <ishii@sraoss.co.jp> writes:\n>> Below is outputs from \"pgproto\" command coming with Pgpool-II.\n>> (Lines starting \"FE\" represents a message from frontend to backend.\n>> Lines starting \"BE\" represents a message from backend to frontend.)\n> \n>> FE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\n>> FE=> Bind(stmt=\"\", portal=\"\")\n>> FE=> Execute(portal=\"\")\n>> FE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\n>> FE=> Bind(stmt=\"\", portal=\"\")\n>> FE=> Execute(portal=\"\")\n>> FE=> Query (query=\"SET extra_float_digits = 3\")\n>> <= BE ParseComplete\n>> <= BE BindComplete\n>> <= BE CommandComplete(SET)\n>> <= BE ParseComplete\n>> <= BE BindComplete\n>> <= BE CommandComplete(SET)\n>> <= BE CommandComplete(SET)\n>> <= BE ReadyForQuery(I)\n>> FE=> Terminate\n> \n>> As you can see, two \"SET extra_float_digits = 3\" is sent in the\n>> extended query protocol, then one \"SET extra_float_digits = 3\" follows\n>> in the simple query protocol. No sync message is sent. However, I get\n>> ReadyForQuery at the end. It seems the extended query protocol is\n>> ended by a simple query protocol message instead of a sync message.\n> \n>> My question is, is this legal in terms of fronted/backend protocol?\n> \n> I think it's poor practice, at best. You should end the\n> extended-protocol query cycle before invoking simple query.\n\n From [1] I think the JDBC driver sends something like below if\nautosave=always option is specified.\n\n\"BEGIN READ ONLY\" Parse/Bind/Eexecute (in the extended query protocol)\n\"SAVEPOINT PGJDBC_AUTOSAVE\" (in the simple query protocol) \n\nIt seems the SAVEPOINT is sent without finishing the extended query\nprotocol (i.e. without Sync message). Is it possible for the JDBC\ndriver to issue a Sync message before sending SAVEPOINT in simple\nquery protocol? Or you can send SAVEPOINT using the extended query\nprotocol.\n\n[1] https://www.pgpool.net/pipermail/pgpool-general/2023-December/009051.html\nHi Tatsuo,Yes, it would be possible. Can you create an issue on github? Issues · pgjdbc/pgjdbc (github.com)Dave",
"msg_date": "Thu, 1 Feb 2024 05:00:17 -0500",
"msg_from": "Dave Cramer <davecramer@postgres.rocks>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": ">> Hello Dave,\n>>\n>> > Tatsuo Ishii <ishii@sraoss.co.jp> writes:\n>> >> Below is outputs from \"pgproto\" command coming with Pgpool-II.\n>> >> (Lines starting \"FE\" represents a message from frontend to backend.\n>> >> Lines starting \"BE\" represents a message from backend to frontend.)\n>> >\n>> >> FE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\n>> >> FE=> Bind(stmt=\"\", portal=\"\")\n>> >> FE=> Execute(portal=\"\")\n>> >> FE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\n>> >> FE=> Bind(stmt=\"\", portal=\"\")\n>> >> FE=> Execute(portal=\"\")\n>> >> FE=> Query (query=\"SET extra_float_digits = 3\")\n>> >> <= BE ParseComplete\n>> >> <= BE BindComplete\n>> >> <= BE CommandComplete(SET)\n>> >> <= BE ParseComplete\n>> >> <= BE BindComplete\n>> >> <= BE CommandComplete(SET)\n>> >> <= BE CommandComplete(SET)\n>> >> <= BE ReadyForQuery(I)\n>> >> FE=> Terminate\n>> >\n>> >> As you can see, two \"SET extra_float_digits = 3\" is sent in the\n>> >> extended query protocol, then one \"SET extra_float_digits = 3\" follows\n>> >> in the simple query protocol. No sync message is sent. However, I get\n>> >> ReadyForQuery at the end. It seems the extended query protocol is\n>> >> ended by a simple query protocol message instead of a sync message.\n>> >\n>> >> My question is, is this legal in terms of fronted/backend protocol?\n>> >\n>> > I think it's poor practice, at best. You should end the\n>> > extended-protocol query cycle before invoking simple query.\n>>\n>> From [1] I think the JDBC driver sends something like below if\n>> autosave=always option is specified.\n>>\n>> \"BEGIN READ ONLY\" Parse/Bind/Eexecute (in the extended query protocol)\n>> \"SAVEPOINT PGJDBC_AUTOSAVE\" (in the simple query protocol)\n>>\n>> It seems the SAVEPOINT is sent without finishing the extended query\n>> protocol (i.e. without Sync message). Is it possible for the JDBC\n>> driver to issue a Sync message before sending SAVEPOINT in simple\n>> query protocol? Or you can send SAVEPOINT using the extended query\n>> protocol.\n>>\n>> [1]\n>> https://www.pgpool.net/pipermail/pgpool-general/2023-December/009051.html\n>>\n>>\n> Hi Tatsuo,\n> \n> Yes, it would be possible.\n> \n> Can you create an issue on github? Issues · pgjdbc/pgjdbc (github.com)\n> <https://github.com/pgjdbc/pgjdbc/issues>\n\nSure.\n\nhttps://github.com/pgjdbc/pgjdbc/issues/3107\n\nBest reagards,\n--\nTatsuo Ishii\nSRA OSS LLC\nEnglish: http://www.sraoss.co.jp/index_en/\nJapanese:http://www.sraoss.co.jp\n\n\n",
"msg_date": "Thu, 01 Feb 2024 20:21:50 +0900 (JST)",
"msg_from": "Tatsuo Ishii <ishii@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "HI Tatsuo,\n\n\n\nOn Mon, 29 Jan 2024 at 20:15, Tatsuo Ishii <ishii@sraoss.co.jp> wrote:\n\n> Hello Dave,\n>\n> > Tatsuo Ishii <ishii@sraoss.co.jp> writes:\n> >> Below is outputs from \"pgproto\" command coming with Pgpool-II.\n> >> (Lines starting \"FE\" represents a message from frontend to backend.\n> >> Lines starting \"BE\" represents a message from backend to frontend.)\n> >\n> >> FE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\n> >> FE=> Bind(stmt=\"\", portal=\"\")\n> >> FE=> Execute(portal=\"\")\n> >> FE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\n> >> FE=> Bind(stmt=\"\", portal=\"\")\n> >> FE=> Execute(portal=\"\")\n> >> FE=> Query (query=\"SET extra_float_digits = 3\")\n> >> <= BE ParseComplete\n> >> <= BE BindComplete\n> >> <= BE CommandComplete(SET)\n> >> <= BE ParseComplete\n> >> <= BE BindComplete\n> >> <= BE CommandComplete(SET)\n> >> <= BE CommandComplete(SET)\n> >> <= BE ReadyForQuery(I)\n> >> FE=> Terminate\n> >\n> >> As you can see, two \"SET extra_float_digits = 3\" is sent in the\n> >> extended query protocol, then one \"SET extra_float_digits = 3\" follows\n> >> in the simple query protocol. No sync message is sent. However, I get\n> >> ReadyForQuery at the end. It seems the extended query protocol is\n> >> ended by a simple query protocol message instead of a sync message.\n> >\n> >> My question is, is this legal in terms of fronted/backend protocol?\n> >\n> > I think it's poor practice, at best. You should end the\n> > extended-protocol query cycle before invoking simple query.\n>\n> From [1] I think the JDBC driver sends something like below if\n> autosave=always option is specified.\n>\n> \"BEGIN READ ONLY\" Parse/Bind/Eexecute (in the extended query protocol)\n> \"SAVEPOINT PGJDBC_AUTOSAVE\" (in the simple query protocol)\n>\n> It seems the SAVEPOINT is sent without finishing the extended query\n> protocol (i.e. without Sync message). Is it possible for the JDBC\n> driver to issue a Sync message before sending SAVEPOINT in simple\n> query protocol? Or you can send SAVEPOINT using the extended query\n> protocol.\n>\n> [1]\n> https://www.pgpool.net/pipermail/pgpool-general/2023-December/009051.html\n\n\nCan you ask the OP what version of the driver they are using. From what I\ncan tell we send BEGIN using SimpleQuery.\n\nDave\n\nHI Tatsuo,On Mon, 29 Jan 2024 at 20:15, Tatsuo Ishii <ishii@sraoss.co.jp> wrote:Hello Dave,\n\n> Tatsuo Ishii <ishii@sraoss.co.jp> writes:\n>> Below is outputs from \"pgproto\" command coming with Pgpool-II.\n>> (Lines starting \"FE\" represents a message from frontend to backend.\n>> Lines starting \"BE\" represents a message from backend to frontend.)\n> \n>> FE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\n>> FE=> Bind(stmt=\"\", portal=\"\")\n>> FE=> Execute(portal=\"\")\n>> FE=> Parse(stmt=\"\", query=\"SET extra_float_digits = 3\")\n>> FE=> Bind(stmt=\"\", portal=\"\")\n>> FE=> Execute(portal=\"\")\n>> FE=> Query (query=\"SET extra_float_digits = 3\")\n>> <= BE ParseComplete\n>> <= BE BindComplete\n>> <= BE CommandComplete(SET)\n>> <= BE ParseComplete\n>> <= BE BindComplete\n>> <= BE CommandComplete(SET)\n>> <= BE CommandComplete(SET)\n>> <= BE ReadyForQuery(I)\n>> FE=> Terminate\n> \n>> As you can see, two \"SET extra_float_digits = 3\" is sent in the\n>> extended query protocol, then one \"SET extra_float_digits = 3\" follows\n>> in the simple query protocol. No sync message is sent. However, I get\n>> ReadyForQuery at the end. It seems the extended query protocol is\n>> ended by a simple query protocol message instead of a sync message.\n> \n>> My question is, is this legal in terms of fronted/backend protocol?\n> \n> I think it's poor practice, at best. You should end the\n> extended-protocol query cycle before invoking simple query.\n\n From [1] I think the JDBC driver sends something like below if\nautosave=always option is specified.\n\n\"BEGIN READ ONLY\" Parse/Bind/Eexecute (in the extended query protocol)\n\"SAVEPOINT PGJDBC_AUTOSAVE\" (in the simple query protocol) \n\nIt seems the SAVEPOINT is sent without finishing the extended query\nprotocol (i.e. without Sync message). Is it possible for the JDBC\ndriver to issue a Sync message before sending SAVEPOINT in simple\nquery protocol? Or you can send SAVEPOINT using the extended query\nprotocol.\n\n[1] https://www.pgpool.net/pipermail/pgpool-general/2023-December/009051.htmlCan you ask the OP what version of the driver they are using. From what I can tell we send BEGIN using SimpleQuery.Dave",
"msg_date": "Tue, 13 Feb 2024 09:34:46 -0500",
"msg_from": "Dave Cramer <davecramer@postgres.rocks>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "Hi Dave,\n\n>> From [1] I think the JDBC driver sends something like below if\n>> autosave=always option is specified.\n>>\n>> \"BEGIN READ ONLY\" Parse/Bind/Eexecute (in the extended query protocol)\n>> \"SAVEPOINT PGJDBC_AUTOSAVE\" (in the simple query protocol)\n>>\n>> It seems the SAVEPOINT is sent without finishing the extended query\n>> protocol (i.e. without Sync message). Is it possible for the JDBC\n>> driver to issue a Sync message before sending SAVEPOINT in simple\n>> query protocol? Or you can send SAVEPOINT using the extended query\n>> protocol.\n>>\n>> [1]\n>> https://www.pgpool.net/pipermail/pgpool-general/2023-December/009051.html\n> \n> \n> Can you ask the OP what version of the driver they are using. From what I\n> can tell we send BEGIN using SimpleQuery.\n\nSure. I will get back once I get the JDBC version.\n\nBest reagards,\n--\nTatsuo Ishii\nSRA OSS LLC\nEnglish: http://www.sraoss.co.jp/index_en/\nJapanese:http://www.sraoss.co.jp\n\n\n",
"msg_date": "Wed, 14 Feb 2024 08:17:03 +0900 (JST)",
"msg_from": "Tatsuo Ishii <ishii@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": ">>> From [1] I think the JDBC driver sends something like below if\n>>> autosave=always option is specified.\n>>>\n>>> \"BEGIN READ ONLY\" Parse/Bind/Eexecute (in the extended query protocol)\n>>> \"SAVEPOINT PGJDBC_AUTOSAVE\" (in the simple query protocol)\n>>>\n>>> It seems the SAVEPOINT is sent without finishing the extended query\n>>> protocol (i.e. without Sync message). Is it possible for the JDBC\n>>> driver to issue a Sync message before sending SAVEPOINT in simple\n>>> query protocol? Or you can send SAVEPOINT using the extended query\n>>> protocol.\n>>>\n>>> [1]\n>>> https://www.pgpool.net/pipermail/pgpool-general/2023-December/009051.html\n>> \n>> \n>> Can you ask the OP what version of the driver they are using. From what I\n>> can tell we send BEGIN using SimpleQuery.\n> \n> Sure. I will get back once I get the JDBC version.\n\nHere it is:\n> JDBC driver version used:42.5.1 Regards, Karel.\n\nBest reagards,\n--\nTatsuo Ishii\nSRA OSS LLC\nEnglish: http://www.sraoss.co.jp/index_en/\nJapanese:http://www.sraoss.co.jp\n\n\n",
"msg_date": "Thu, 15 Feb 2024 07:55:27 +0900 (JST)",
"msg_from": "Tatsuo Ishii <ishii@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "On Wed, 14 Feb 2024 at 17:55, Tatsuo Ishii <ishii@sraoss.co.jp> wrote:\n\n> >>> From [1] I think the JDBC driver sends something like below if\n> >>> autosave=always option is specified.\n> >>>\n> >>> \"BEGIN READ ONLY\" Parse/Bind/Eexecute (in the extended query protocol)\n> >>> \"SAVEPOINT PGJDBC_AUTOSAVE\" (in the simple query protocol)\n> >>>\n> >>> It seems the SAVEPOINT is sent without finishing the extended query\n> >>> protocol (i.e. without Sync message). Is it possible for the JDBC\n> >>> driver to issue a Sync message before sending SAVEPOINT in simple\n> >>> query protocol? Or you can send SAVEPOINT using the extended query\n> >>> protocol.\n> >>>\n> >>> [1]\n> >>>\n> https://www.pgpool.net/pipermail/pgpool-general/2023-December/009051.html\n> >>\n> >>\n> >> Can you ask the OP what version of the driver they are using. From what\n> I\n> >> can tell we send BEGIN using SimpleQuery.\n> >\n> > Sure. I will get back once I get the JDBC version.\n>\n> Here it is:\n> > JDBC driver version used:42.5.1 Regards, Karel.\n>\n\nCan you ask the OP what they are doing in the startup. I'm trying to\nreplicate their situation.\nLooks like possibly 'setReadOnly' and 'select version()'\n\nThanks,\nDave\n\n>\n>\n\nOn Wed, 14 Feb 2024 at 17:55, Tatsuo Ishii <ishii@sraoss.co.jp> wrote:>>> From [1] I think the JDBC driver sends something like below if\n>>> autosave=always option is specified.\n>>>\n>>> \"BEGIN READ ONLY\" Parse/Bind/Eexecute (in the extended query protocol)\n>>> \"SAVEPOINT PGJDBC_AUTOSAVE\" (in the simple query protocol)\n>>>\n>>> It seems the SAVEPOINT is sent without finishing the extended query\n>>> protocol (i.e. without Sync message). Is it possible for the JDBC\n>>> driver to issue a Sync message before sending SAVEPOINT in simple\n>>> query protocol? Or you can send SAVEPOINT using the extended query\n>>> protocol.\n>>>\n>>> [1]\n>>> https://www.pgpool.net/pipermail/pgpool-general/2023-December/009051.html\n>> \n>> \n>> Can you ask the OP what version of the driver they are using. From what I\n>> can tell we send BEGIN using SimpleQuery.\n> \n> Sure. I will get back once I get the JDBC version.\n\nHere it is:\n> JDBC driver version used:42.5.1 Regards, Karel.Can you ask the OP what they are doing in the startup. I'm trying to replicate their situation.Looks like possibly 'setReadOnly' and 'select version()' Thanks,Dave",
"msg_date": "Thu, 15 Feb 2024 08:34:12 -0500",
"msg_from": "Dave Cramer <davecramer@postgres.rocks>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "> Can you ask the OP what they are doing in the startup. I'm trying to\n> replicate their situation.\n> Looks like possibly 'setReadOnly' and 'select version()'\n\nSure I will. By the way 'select version()' may be issued by Pgpool-II\nitself. In this case it should be 'SELECT version()', not 'select\nversion()'.\n\nBest reagards,\n--\nTatsuo Ishii\nSRA OSS LLC\nEnglish: http://www.sraoss.co.jp/index_en/\nJapanese:http://www.sraoss.co.jp\n\n\n",
"msg_date": "Fri, 16 Feb 2024 09:43:31 +0900 (JST)",
"msg_from": "Tatsuo Ishii <ishii@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "Hi Tatsuo,\n\nActually no need, I figured it out.\n\nI don't have a solution yet though.\n\nDave Cramer\nwww.postgres.rocks\n\n\nOn Thu, 15 Feb 2024 at 19:43, Tatsuo Ishii <ishii@sraoss.co.jp> wrote:\n\n> > Can you ask the OP what they are doing in the startup. I'm trying to\n> > replicate their situation.\n> > Looks like possibly 'setReadOnly' and 'select version()'\n>\n> Sure I will. By the way 'select version()' may be issued by Pgpool-II\n> itself. In this case it should be 'SELECT version()', not 'select\n> version()'.\n>\n> Best reagards,\n> --\n> Tatsuo Ishii\n> SRA OSS LLC\n> English: http://www.sraoss.co.jp/index_en/\n> Japanese:http://www.sraoss.co.jp\n>\n\nHi Tatsuo,Actually no need, I figured it out. I don't have a solution yet though.Dave Cramerwww.postgres.rocksOn Thu, 15 Feb 2024 at 19:43, Tatsuo Ishii <ishii@sraoss.co.jp> wrote:> Can you ask the OP what they are doing in the startup. I'm trying to\n> replicate their situation.\n> Looks like possibly 'setReadOnly' and 'select version()'\n\nSure I will. By the way 'select version()' may be issued by Pgpool-II\nitself. In this case it should be 'SELECT version()', not 'select\nversion()'.\n\nBest reagards,\n--\nTatsuo Ishii\nSRA OSS LLC\nEnglish: http://www.sraoss.co.jp/index_en/\nJapanese:http://www.sraoss.co.jp",
"msg_date": "Thu, 15 Feb 2024 19:50:27 -0500",
"msg_from": "Dave Cramer <davecramer@postgres.rocks>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "Hi Dave,\n\nOh, I see.\n\n> Hi Tatsuo,\n> \n> Actually no need, I figured it out.\n> \n> I don't have a solution yet though.\n> \n> Dave Cramer\n> www.postgres.rocks\n> \n> \n> On Thu, 15 Feb 2024 at 19:43, Tatsuo Ishii <ishii@sraoss.co.jp> wrote:\n> \n>> > Can you ask the OP what they are doing in the startup. I'm trying to\n>> > replicate their situation.\n>> > Looks like possibly 'setReadOnly' and 'select version()'\n>>\n>> Sure I will. By the way 'select version()' may be issued by Pgpool-II\n>> itself. In this case it should be 'SELECT version()', not 'select\n>> version()'.\n>>\n>> Best reagards,\n>> --\n>> Tatsuo Ishii\n>> SRA OSS LLC\n>> English: http://www.sraoss.co.jp/index_en/\n>> Japanese:http://www.sraoss.co.jp\n>>\n\n\n",
"msg_date": "Fri, 16 Feb 2024 09:58:41 +0900 (JST)",
"msg_from": "Tatsuo Ishii <ishii@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": ">Is it possible for the JDBC\n>driver to issue a Sync message before sending SAVEPOINT in simple\n>query protocol?\n\nApparently, sending an extra message would increase the overhead of the\nprotocol, thus reducing the efficiency of the application.\nWhat is the benefit of sending extra Sync?\n\nhttps://www.postgresql.org/docs/current/protocol-overview.html#PROTOCOL-MESSAGE-CONCEPTS\nsuggests that is is fine to mix both simple and extended messages\ndepending on the needs of the application.\n\nhttps://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-PIPELINING\nreads that clients can omit sending Sync to make the error handling the way\nthey like.\nI am not that sure we must omit sync there, however, it might be the case.\n\nhttps://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY\nreads \"simple Query message also destroys the unnamed statement\" and\n\"simple Query message also destroys the unnamed portal\"\n\n>Or you can send SAVEPOINT using the extended query protocol.\n\nI am afraid we can't.\nThe purpose of savepoints at the driver's level is to enable migrating\napplications from other databases to PostgreSQL.\nIn PostgreSQL any SQL exception fails the transaction, including errors\nlike \"prepared statement \\\"...\\\" does not exist\", and so on.\nIt might be unexpected for the users to unexpectedly get \"prepared\nstatement is no longer valid\" errors in case somebody adds a column to a\ntable.\n\nWe can't send complete parse-bind-execute commands for every \"savepoint\"\ncall as it would hurt performance.\nWe can't cache the parsed statement as it could be discarded by a random\n\"deallocate all\".\nSo the only way out I see is to use simple query mode for savepoint queries.\n\nVladimir\n\n>Is it possible for the JDBC>driver to issue a Sync message before sending SAVEPOINT in simple>query protocol?Apparently, sending an extra message would increase the overhead of the protocol, thus reducing the efficiency of the application.What is the benefit of sending extra Sync?https://www.postgresql.org/docs/current/protocol-overview.html#PROTOCOL-MESSAGE-CONCEPTSsuggests that is is fine to mix both simple and extended messagesdepending on the needs of the application.https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-PIPELININGreads that clients can omit sending Sync to make the error handling the way they like.I am not that sure we must omit sync there, however, it might be the case.https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERYreads \"simple Query message also destroys the unnamed statement\" and \"simple Query message also destroys the unnamed portal\">Or you can send SAVEPOINT using the extended query protocol.I am afraid we can't.The purpose of savepoints at the driver's level is to enable migrating applications from other databases to PostgreSQL.In PostgreSQL any SQL exception fails the transaction, including errors like \"prepared statement \\\"...\\\" does not exist\", and so on.It might be unexpected for the users to unexpectedly get \"prepared statement is no longer valid\" errors in case somebody adds a column to a table.We can't send complete parse-bind-execute commands for every \"savepoint\" call as it would hurt performance.We can't cache the parsed statement as it could be discarded by a random \"deallocate all\".So the only way out I see is to use simple query mode for savepoint queries.Vladimir",
"msg_date": "Wed, 21 Feb 2024 18:34:49 +0300",
"msg_from": "Vladimir Sitnikov <sitnikov.vladimir@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "On Wed, 21 Feb 2024 at 16:35, Vladimir Sitnikov\n<sitnikov.vladimir@gmail.com> wrote:\n> We can't send complete parse-bind-execute commands for every \"savepoint\" call as it would hurt performance.\n\nWould performance suffer that much? I'd expect the simple and extended\nprotocol to have roughly the same overhead for simple queries without\narguments such SAVEPOINT.\n\n\n",
"msg_date": "Wed, 21 Feb 2024 16:50:03 +0100",
"msg_from": "Jelte Fennema-Nio <postgres@jeltef.nl>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": ">Would performance suffer that much?\n\nI have not benchmarked it much, however, the driver sends \"autosave\"\nqueries once (savepoint) or twice(savepoint+release) for every\nuser-provided query.\nIf we use extended queries (parse+bind+exec) for every savepoint, that\nwould result in 3 or 6 messages overhead for every user query.\n\n From many measurements we know that insert into table(id, name)\nvalues(?,?),(?,?),(?,?) is much more efficient than\nsending individual bind-exec-bind-exec-bind-exec-sync messages like \"insert\ninto table(id, name) values(?,?)\"\nFor instance, here are some measurements:\nhttps://www.baeldung.com/spring-jdbc-batch-inserts#performance-comparisons\nBased on that measurements I assume there's a non-trivial per-message\noverhead.\n\nVladimir\n\n>Would performance suffer that much?I have not benchmarked it much, however, the driver sends \"autosave\" queries once (savepoint) or twice(savepoint+release) for every user-provided query.If we use extended queries (parse+bind+exec) for every savepoint, that would result in 3 or 6 messages overhead for every user query.From many measurements we know that insert into table(id, name) values(?,?),(?,?),(?,?) is much more efficient thansending individual bind-exec-bind-exec-bind-exec-sync messages like \"insert into table(id, name) values(?,?)\"For instance, here are some measurements: https://www.baeldung.com/spring-jdbc-batch-inserts#performance-comparisonsBased on that measurements I assume there's a non-trivial per-message overhead.Vladimir",
"msg_date": "Wed, 21 Feb 2024 19:07:20 +0300",
"msg_from": "Vladimir Sitnikov <sitnikov.vladimir@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "Vladimir Sitnikov <sitnikov.vladimir@gmail.com> writes:\n>> Would performance suffer that much?\n\n> I have not benchmarked it much, however, the driver sends \"autosave\"\n> queries once (savepoint) or twice(savepoint+release) for every\n> user-provided query.\n> If we use extended queries (parse+bind+exec) for every savepoint, that\n> would result in 3 or 6 messages overhead for every user query.\n\nThose should get bundled into single TCP messages, though. Assuming\nthat that's done properly, I share the doubt that you're saving\nanything very meaningful.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Wed, 21 Feb 2024 11:18:42 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "On Wed, 21 Feb 2024 at 17:07, Vladimir Sitnikov\n<sitnikov.vladimir@gmail.com> wrote:\n> From many measurements we know that insert into table(id, name) values(?,?),(?,?),(?,?) is much more efficient than\n> sending individual bind-exec-bind-exec-bind-exec-sync messages like \"insert into table(id, name) values(?,?)\"\n> For instance, here are some measurements: https://www.baeldung.com/spring-jdbc-batch-inserts#performance-comparisons\n> Based on that measurements I assume there's a non-trivial per-message overhead.\n\nThat's quite a different case. When splitting a multi insert statement\nyou're going to duplicate some work, e.g. executor initialization and\npossibly even planning. But when replacing one Query packet with\nParse-Bind-Exec-Sync, these 4 packets are not duplicating such\nexpensive work. The only thing they should be doing extra is a bit of\npacket parsing, which is very cheap.\n\n\n",
"msg_date": "Thu, 22 Feb 2024 10:01:36 +0100",
"msg_from": "Jelte Fennema-Nio <postgres@jeltef.nl>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": ">When splitting a multi insert statement you're going to duplicate some work\n\nI do not understand why I am going to duplicate some work.\nI assume the database does its best to perform all the needed preparation\nwhen processing \"parse\" message,\nand it should perform only the minimum required work when processing\nbind+exec messages.\n\nUnfortunately, it is not completely the case, so using bind+exec+bind+exec\nis suboptimal even for trivial insert statements.\n\nPlease, take into account the following sequence:\nOne-time-only:\nparse S1 as insert into table(id, name) values(?,?)\n\nSome time later:\nbind S1 ...\nexec S1\nbind S1 ...\nexec S1\nbind S1 ...\nexec S1\nbind S1 ...\nexec S1\nsync\n\nI do not know how this could be made more efficient as I execute parse only\nonce, and then I send bind+exec+bind+exec\nwithout intermediate sync messages, so the data should flow nicely in TCP\npackets.\nAs I said above, the same flow for multi-value insert beats the\nbind+exec+bind+exec sequence at a cost of poor reporting.\nFor instance, for multivalue insert we can't tell how many rows are\ngenerated for each statement.\n\n---\n\nHere are some measurements regarding savepoints for simple vs extended\nSure they are not very scientific, however, they show improvement for\nsimple protocol\n\n$ cat svpnt\n\nBEGIN;\nSAVEPOINT PGJDBC_AUTOSAVE;\nRELEASE SAVEPOINT PGJDBC_AUTOSAVE;\nCOMMIT;\n\n$ pgbench -f svpnt --protocol=extended --time=10 --progress=1 -r\n\nprogress: 1.0 s, 4213.8 tps, lat 0.237 ms stddev 0.034, 0 failed\nprogress: 2.0 s, 4367.9 tps, lat 0.229 ms stddev 0.024, 0 failed\nprogress: 3.0 s, 4296.2 tps, lat 0.233 ms stddev 0.038, 0 failed\nprogress: 4.0 s, 4382.0 tps, lat 0.228 ms stddev 0.026, 0 failed\nprogress: 5.0 s, 4374.1 tps, lat 0.228 ms stddev 0.026, 0 failed\nprogress: 6.0 s, 4305.7 tps, lat 0.232 ms stddev 0.035, 0 failed\nprogress: 7.0 s, 4111.1 tps, lat 0.243 ms stddev 0.182, 0 failed\nprogress: 8.0 s, 4245.0 tps, lat 0.235 ms stddev 0.042, 0 failed\nprogress: 9.0 s, 4219.9 tps, lat 0.237 ms stddev 0.036, 0 failed\nprogress: 10.0 s, 4231.1 tps, lat 0.236 ms stddev 0.031, 0 failed\ntransaction type: svpnt\nscaling factor: 1\nquery mode: extended\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nduration: 10 s\nnumber of transactions actually processed: 42748\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.234 ms\nlatency stddev = 0.065 ms\ninitial connection time = 2.178 ms\ntps = 4275.562760 (without initial connection time)\nstatement latencies in milliseconds and failures:\n 0.058 0 BEGIN;\n 0.058 0 SAVEPOINT PGJDBC_AUTOSAVE;\n 0.058 0 RELEASE SAVEPOINT PGJDBC_AUTOSAVE;\n 0.060 0 COMMIT;\n\n$ pgbench -f svpnt --protocol=simple --time=10 --progress=1 -r\n\nprogress: 1.0 s, 4417.7 tps, lat 0.225 ms stddev 0.033, 0 failed\nprogress: 2.0 s, 4446.0 tps, lat 0.225 ms stddev 0.079, 0 failed\nprogress: 3.0 s, 4377.1 tps, lat 0.228 ms stddev 0.048, 0 failed\nprogress: 4.0 s, 4485.0 tps, lat 0.223 ms stddev 0.024, 0 failed\nprogress: 5.0 s, 4355.9 tps, lat 0.229 ms stddev 0.353, 0 failed\nprogress: 6.0 s, 4444.3 tps, lat 0.225 ms stddev 0.035, 0 failed\nprogress: 7.0 s, 4530.7 tps, lat 0.220 ms stddev 0.020, 0 failed\nprogress: 8.0 s, 4431.1 tps, lat 0.225 ms stddev 0.022, 0 failed\nprogress: 9.0 s, 4497.1 tps, lat 0.222 ms stddev 0.027, 0 failed\nprogress: 10.0 s, 4507.0 tps, lat 0.222 ms stddev 0.024, 0 failed\ntransaction type: svpnt\nscaling factor: 1\nquery mode: simple\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nduration: 10 s\nnumber of transactions actually processed: 44493\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.224 ms\nlatency stddev = 0.116 ms\ninitial connection time = 2.690 ms\ntps = 4450.372095 (without initial connection time)\nstatement latencies in milliseconds and failures:\n 0.056 0 BEGIN;\n 0.056 0 SAVEPOINT PGJDBC_AUTOSAVE;\n 0.056 0 RELEASE SAVEPOINT PGJDBC_AUTOSAVE;\n 0.057 0 COMMIT;\n\nVladimir\n\n>When splitting a multi insert statement you're going to duplicate some workI do not understand why I am going to duplicate some work.I assume the database does its best to perform all the needed preparation when processing \"parse\" message,and it should perform only the minimum required work when processing bind+exec messages.Unfortunately, it is not completely the case, so using bind+exec+bind+exec is suboptimal even for trivial insert statements.Please, take into account the following sequence:One-time-only:parse S1 as insert into table(id, name) values(?,?)Some time later:bind S1 ...exec S1bind S1 ...exec S1bind S1 ...exec S1bind S1 ...exec S1syncI do not know how this could be made more efficient as I execute parse only once, and then I send bind+exec+bind+execwithout intermediate sync messages, so the data should flow nicely in TCP packets.As I said above, the same flow for multi-value insert beats the bind+exec+bind+exec sequence at a cost of poor reporting.For instance, for multivalue insert we can't tell how many rows are generated for each statement.---Here are some measurements regarding savepoints for simple vs extendedSure they are not very scientific, however, they show improvement for simple protocol$ cat svpntBEGIN;SAVEPOINT PGJDBC_AUTOSAVE;RELEASE SAVEPOINT PGJDBC_AUTOSAVE;COMMIT;$ pgbench -f svpnt --protocol=extended --time=10 --progress=1 -rprogress: 1.0 s, 4213.8 tps, lat 0.237 ms stddev 0.034, 0 failedprogress: 2.0 s, 4367.9 tps, lat 0.229 ms stddev 0.024, 0 failedprogress: 3.0 s, 4296.2 tps, lat 0.233 ms stddev 0.038, 0 failedprogress: 4.0 s, 4382.0 tps, lat 0.228 ms stddev 0.026, 0 failedprogress: 5.0 s, 4374.1 tps, lat 0.228 ms stddev 0.026, 0 failedprogress: 6.0 s, 4305.7 tps, lat 0.232 ms stddev 0.035, 0 failedprogress: 7.0 s, 4111.1 tps, lat 0.243 ms stddev 0.182, 0 failedprogress: 8.0 s, 4245.0 tps, lat 0.235 ms stddev 0.042, 0 failedprogress: 9.0 s, 4219.9 tps, lat 0.237 ms stddev 0.036, 0 failedprogress: 10.0 s, 4231.1 tps, lat 0.236 ms stddev 0.031, 0 failedtransaction type: svpntscaling factor: 1query mode: extendednumber of clients: 1number of threads: 1maximum number of tries: 1duration: 10 snumber of transactions actually processed: 42748number of failed transactions: 0 (0.000%)latency average = 0.234 mslatency stddev = 0.065 msinitial connection time = 2.178 mstps = 4275.562760 (without initial connection time)statement latencies in milliseconds and failures: 0.058 0 BEGIN; 0.058 0 SAVEPOINT PGJDBC_AUTOSAVE; 0.058 0 RELEASE SAVEPOINT PGJDBC_AUTOSAVE; 0.060 0 COMMIT;$ pgbench -f svpnt --protocol=simple --time=10 --progress=1 -rprogress: 1.0 s, 4417.7 tps, lat 0.225 ms stddev 0.033, 0 failedprogress: 2.0 s, 4446.0 tps, lat 0.225 ms stddev 0.079, 0 failedprogress: 3.0 s, 4377.1 tps, lat 0.228 ms stddev 0.048, 0 failedprogress: 4.0 s, 4485.0 tps, lat 0.223 ms stddev 0.024, 0 failedprogress: 5.0 s, 4355.9 tps, lat 0.229 ms stddev 0.353, 0 failedprogress: 6.0 s, 4444.3 tps, lat 0.225 ms stddev 0.035, 0 failedprogress: 7.0 s, 4530.7 tps, lat 0.220 ms stddev 0.020, 0 failedprogress: 8.0 s, 4431.1 tps, lat 0.225 ms stddev 0.022, 0 failedprogress: 9.0 s, 4497.1 tps, lat 0.222 ms stddev 0.027, 0 failedprogress: 10.0 s, 4507.0 tps, lat 0.222 ms stddev 0.024, 0 failedtransaction type: svpntscaling factor: 1query mode: simplenumber of clients: 1number of threads: 1maximum number of tries: 1duration: 10 snumber of transactions actually processed: 44493number of failed transactions: 0 (0.000%)latency average = 0.224 mslatency stddev = 0.116 msinitial connection time = 2.690 mstps = 4450.372095 (without initial connection time)statement latencies in milliseconds and failures: 0.056 0 BEGIN; 0.056 0 SAVEPOINT PGJDBC_AUTOSAVE; 0.056 0 RELEASE SAVEPOINT PGJDBC_AUTOSAVE; 0.057 0 COMMIT;Vladimir",
"msg_date": "Thu, 22 Feb 2024 12:27:52 +0300",
"msg_from": "Vladimir Sitnikov <sitnikov.vladimir@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "On Thu, 22 Feb 2024 at 10:28, Vladimir Sitnikov\n<sitnikov.vladimir@gmail.com> wrote:\n>\n> >When splitting a multi insert statement you're going to duplicate some work\n>\n> I do not know how this could be made more efficient as I execute parse only once, and then I send bind+exec+bind+exec\n> without intermediate sync messages, so the data should flow nicely in TCP packets.\n\nI agree you cannot change that flow to be more efficient, but I meant\nthat your comparison was not fair:\n1. Multi-insert vs multiple single inserts is actually executing\ndifferent queries\n2. Going from Query -> Parse+Bind+Exec for the same query, only\nchanges protocol related things\n\n> Here are some measurements regarding savepoints for simple vs extended\n> Sure they are not very scientific, however, they show improvement for simple protocol\n\nAlright, those improvements are not huge, but I agree it's clear that\nthe extended protocol has some overhead. So probably you'd want to\nkeep using the simple protocol to send the SAVEPOINT query.\n\n> Apparently, sending an extra message would increase the overhead of the protocol, thus reducing the efficiency of the application.\n> What is the benefit of sending extra Sync?\n>\n> https://www.postgresql.org/docs/current/protocol-overview.html#PROTOCOL-MESSAGE-CONCEPTS\n> suggests that is is fine to mix both simple and extended messages\n> depending on the needs of the application.\n\nYes, it's fine to mix and match extended and simple protocol. But the\nprotocol docs quite clearly state that a sync is required before going\nback to the Simple protocol: \"At completion of each series of\nextended-query messages, the frontend should issue a Sync message.\"\nhttps://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY\n\nTerminating a sequence of extended messages with a Query message\ninstead of a Sync message is definitely undefined behaviour.\n\n\n",
"msg_date": "Thu, 22 Feb 2024 12:09:02 +0100",
"msg_from": "Jelte Fennema-Nio <postgres@jeltef.nl>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "Hi,\n\nOn 2/22/24 14:09, Jelte Fennema-Nio wrote:\n>> Apparently, sending an extra message would increase the overhead of the protocol, thus reducing the efficiency of the application.\n>> What is the benefit of sending extra Sync?\n>>\n>> https://www.postgresql.org/docs/current/protocol-overview.html#PROTOCOL-MESSAGE-CONCEPTS\n>> suggests that is is fine to mix both simple and extended messages\n>> depending on the needs of the application.\n> Yes, it's fine to mix and match extended and simple protocol. But the\n> protocol docs quite clearly state that a sync is required before going\n> back to the Simple protocol: \"At completion of each series of\n> extended-query messages, the frontend should issue a Sync message.\"\n> https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY\nI would like to say this document states that \"at completion... frontend \nshould issue a Sync message... causes the backend to close the current \ntransaction\"\nIt looks like the sense of wording is \"to complete transaction\" at the \neventual end of traffic, but not \"to switch to single protocol\".\nOtherwise, we can't use both protocols under same transaction that looks \ntoo strict limitation.\n> Terminating a sequence of extended messages with a Query message\n> instead of a Sync message is definitely undefined behaviour.\n>\n>\n\n\n-- \nMichael Zhilin\nPostgres Professional\n+7(925)3366270\nhttps://www.postgrespro.ru\n\n\n\n\n\n\nHi,\n\n\n On 2/22/24 14:09, Jelte Fennema-Nio wrote:\n\n\nApparently, sending an extra message would increase the overhead of the protocol, thus reducing the efficiency of the application.\nWhat is the benefit of sending extra Sync?\n\nhttps://www.postgresql.org/docs/current/protocol-overview.html#PROTOCOL-MESSAGE-CONCEPTS\nsuggests that is is fine to mix both simple and extended messages\ndepending on the needs of the application.\n\n\n\nYes, it's fine to mix and match extended and simple protocol. But the\nprotocol docs quite clearly state that a sync is required before going\nback to the Simple protocol: \"At completion of each series of\nextended-query messages, the frontend should issue a Sync message.\"\nhttps://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY\n\n\nI would like to say this document states that\n \"at completion... frontend should issue a Sync message... causes\n the backend to close the current transaction\"\n It looks like the sense of wording is \"to complete transaction\" at\n the eventual end of traffic, but not \"to switch to single\n protocol\". \n Otherwise, we can't use both protocols under same transaction that\n looks too strict limitation. \n\n\nTerminating a sequence of extended messages with a Query message\ninstead of a Sync message is definitely undefined behaviour.\n\n\n\n\n\n\n-- \nMichael Zhilin\nPostgres Professional\n+7(925)3366270\nhttps://www.postgrespro.ru",
"msg_date": "Thu, 22 Feb 2024 15:01:36 +0300",
"msg_from": "Michael Zhilin <m.zhilin@postgrespro.ru>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "On Thu, 22 Feb 2024 at 13:01, Michael Zhilin <m.zhilin@postgrespro.ru> wrote:\n> I would like to say this document states that \"at completion... frontend should issue a Sync message... causes the backend to close the current transaction\"\n> It looks like the sense of wording is \"to complete transaction\" at the eventual end of traffic, but not \"to switch to single protocol\".\n> Otherwise, we can't use both protocols under same transaction that looks too strict limitation.\n\nSync only closes the current transaction when you didn't explicitly\nopen one, i.e. you're using an implicit transaction (part of t. If you\nopen an explicit transaction (, then you can use both extended and\nsimple protocol messages in the same transaction. The way I understand\nit is: Multiple extended messages together form a single pipeline\n(easier understood as SQL statement), until a Sync is reached. So\nParse-Bind-Execute-Parse-Bind-Execute-Sync counts as a single unit\nfrom postgres its visibility/rollback behaviour standpoint.\n\nAnd that's also where sending a Query instead of a Sync introduces a\nproblem: What is supposed to happen if something fails. Let's take the\nsimple example Bind-Execute-Query: If the Execute causes an error, is\nthe Query still executed or not? And what about if the Query fails, is\nthe Execute before committed or rolled back?\n\nThat's why we have the Sync messages, clarify what happens when a\nfailure occurs somewhere in the pipeline. And only extended protocol\nmessages are allowed to be part of a pipeline: \"Use of the extended\nquery protocol allows pipelining\"\n\n\n",
"msg_date": "Thu, 22 Feb 2024 14:16:09 +0100",
"msg_from": "Jelte Fennema-Nio <postgres@jeltef.nl>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "> And that's also where sending a Query instead of a Sync introduces a\n> problem: What is supposed to happen if something fails. Let's take the\n> simple example Bind-Execute-Query: If the Execute causes an error, is\n> the Query still executed or not? And what about if the Query fails, is\n> the Execute before committed or rolled back?\n> \n> That's why we have the Sync messages, clarify what happens when a\n> failure occurs somewhere in the pipeline. And only extended protocol\n> messages are allowed to be part of a pipeline: \"Use of the extended\n> query protocol allows pipelining\"\n\nGood point. If we have started extended protocol messages, I think\nthere's no way to avoid the Sync messages before issuing simple\nprotocol messages.\n\nBest reagards,\n--\nTatsuo Ishii\nSRA OSS LLC\nEnglish: http://www.sraoss.co.jp/index_en/\nJapanese:http://www.sraoss.co.jp\n\n\n\n",
"msg_date": "Wed, 28 Feb 2024 21:05:32 +0900 (JST)",
"msg_from": "Tatsuo Ishii <ishii@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "Jelte> If the Execute causes an error, is\nJelte> the Query still executed or not? And what about if the Query fails,\nis\nJelte> the Execute before committed or rolled back?\n\nFrankly, if there's a requirement from the backend, I would like it to\nproduce a corresponding error message.\n\nWhat do you think of making the backend respond with an error message if\nthe requests come out of sequence?\nFor instance, if execute comes without parse, backend responds with \"ERROR:\n prepared statement \"...\" does not exist\"\n\nCan we have a similar diagnostic to catch the unspoken rule of\n\"sync should be there in-between extended messages and simple/functioncall\nmessages and copy subprotocol\"?\n\nIf \"extended query\" is supposed to be like a subprotocol which allows no\nextra messages,\nthen it would help if the documentation enumerated the subprotocols and\ntheir messages.\n\nFor instance, for copy, the documentation is clear; it goes with a\nsubprotocol, so only specific messages are allowed.\n\n-----\n\nJelte>And only extended protocol\nJelte>messages are allowed to be part of a pipeline: \"Use of the extended\nJelte>query protocol allows pipelining\"\n\nFrankly speaking, I think there's a misunderstanding of \"pipelining\"\n\nThe full quote is\n\npgdoc>\"Use of the extended query protocol allows pipelining,\npgdoc>which means sending a series of queries without waiting for earlier\nones to complete\"\n\nThe key is \"without waiting for earlier ones to complete\".\nHowever, in Simple Query section, the documentation reads that\nthe frontend does not need to wait for the response:\n\npgdoc>It is not actually necessary for the frontend to wait for\nReadyForQuery before issuing another command\"\n\nIn other words, SimpleQuery supports pipelining just as fine, and there's\nnothing special in \"extended query\" in that regard.\n\nVladimir\n\nJelte> If the Execute causes an error, isJelte> the Query still executed or not? And what about if the Query fails, isJelte> the Execute before committed or rolled back?Frankly, if there's a requirement from the backend, I would like it to produce a corresponding error message.What do you think of making the backend respond with an error message if the requests come out of sequence?For instance, if execute comes without parse, backend responds with \"ERROR: prepared statement \"...\" does not exist\"Can we have a similar diagnostic to catch the unspoken rule of\"sync should be there in-between extended messages and simple/functioncall messages and copy subprotocol\"?If \"extended query\" is supposed to be like a subprotocol which allows no extra messages,then it would help if the documentation enumerated the subprotocols and their messages.For instance, for copy, the documentation is clear; it goes with a subprotocol, so only specific messages are allowed.-----Jelte>And only extended protocolJelte>messages are allowed to be part of a pipeline: \"Use of the extendedJelte>query protocol allows pipelining\"Frankly speaking, I think there's a misunderstanding of \"pipelining\"The full quote ispgdoc>\"Use of the extended query protocol allows pipelining,pgdoc>which means sending a series of queries without waiting for earlier ones to complete\"The key is \"without waiting for earlier ones to complete\".However, in Simple Query section, the documentation reads thatthe frontend does not need to wait for the response:pgdoc>It is not actually necessary for the frontend to wait for ReadyForQuery before issuing another command\"In other words, SimpleQuery supports pipelining just as fine, and there's nothing special in \"extended query\" in that regard.Vladimir",
"msg_date": "Wed, 28 Feb 2024 19:51:00 +0300",
"msg_from": "Vladimir Sitnikov <sitnikov.vladimir@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
},
{
"msg_contents": "On Wed, 28 Feb 2024 at 17:51, Vladimir Sitnikov\n<sitnikov.vladimir@gmail.com> wrote:\n>\n> Jelte> If the Execute causes an error, is\n> Jelte> the Query still executed or not? And what about if the Query fails, is\n> Jelte> the Execute before committed or rolled back?\n>\n> Frankly, if there's a requirement from the backend, I would like it to produce a corresponding error message.\n>\n> What do you think of making the backend respond with an error message if the requests come out of sequence?\n> For instance, if execute comes without parse, backend responds with \"ERROR: prepared statement \"...\" does not exist\"\n\nI totally agree that it makes sense to throw an error in this case.\nLibpq actually throws an error client side when a caller attempts to\ndo this, but this is something that should be checked server side,\ngiven that the protocol docs specify this:\ndocs> At completion of each series of extended-query messages, the\nfrontend should issue a Sync message.\n\n> If \"extended query\" is supposed to be like a subprotocol which allows no extra messages,\n> then it would help if the documentation enumerated the subprotocols and their messages.\n>\n> For instance, for copy, the documentation is clear; it goes with a subprotocol, so only specific messages are allowed.\n\nYeah, I think the existence of this thread is proof that the docs are\ncurrently not very clear on this. Feel free to suggest some changes.\n\n> In other words, SimpleQuery supports pipelining just as fine\n\nThat's fair.\n\n> and there's nothing special in \"extended query\" in that regard.\n\nI think the main difference is that pipelining of extended query\nmessages requires more care at the client than pipelining of simple\nQuery messages, because not every extended query message always gets a\nresponse in case of an error.\n\n\n",
"msg_date": "Wed, 28 Feb 2024 20:18:02 +0100",
"msg_from": "Jelte Fennema-Nio <postgres@jeltef.nl>",
"msg_from_op": false,
"msg_subject": "Re: When extended query protocol ends?"
}
] |
[
{
"msg_contents": "Hi,\n\nWhile working on radix tree patch[1], John Naylor found that dsa.c\ndoesn't already use shared locks even in dsa_dump(). dsa_dump() seems\na pure read-only function so I thought we could use a shared lock mode\nthere. Is there any reason to use exclusive mode even in dsa_dump()?\n\nUltimately, since we're trying to add a new function\ndsa_get_total_size() that just returns\ndsa_area_control.total_segment_size and therefore would also be a\nread-only function, I'd like to find out the correct lock mode there.\n\nRegards,\n\n[1] https://www.postgresql.org/message-id/CANWCAZYYzoKp_4%2B1m5mn-TRD62BTwom8iLXLOWMsHkkwFi%3Drzg%40mail.gmail.com\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 30 Jan 2024 09:53:19 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": true,
"msg_subject": "Question on LWLockMode in dsa.c"
},
{
"msg_contents": "On Tue, Jan 30, 2024 at 6:24 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> Hi,\n>\n> While working on radix tree patch[1], John Naylor found that dsa.c\n> doesn't already use shared locks even in dsa_dump(). dsa_dump() seems\n> a pure read-only function so I thought we could use a shared lock mode\n> there. Is there any reason to use exclusive mode even in dsa_dump()?\n\ncheck_for_freed_segments_locked which is called from dsa_dump does\nmark a few variables of the dsa area to NULL right? Are you suggesting\nto take initially a shared lock in dsa_dump and upgrade it to\nexclusive mode in the unlikely event of\nunlikely(area->freed_segment_counter != freed_segment_counter)\noccurring in check_for_freed_segments_locked?\n\n> Ultimately, since we're trying to add a new function\n> dsa_get_total_size() that just returns\n> dsa_area_control.total_segment_size and therefore would also be a\n> read-only function, I'd like to find out the correct lock mode there.\n>\n> [1] https://www.postgresql.org/message-id/CANWCAZYYzoKp_4%2B1m5mn-TRD62BTwom8iLXLOWMsHkkwFi%3Drzg%40mail.gmail.com\n\nDo you see any lock contention or any other issues with exclusive\nlocks on dsa areas?\n\n-- \nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 30 Jan 2024 13:13:01 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Question on LWLockMode in dsa.c"
},
{
"msg_contents": "On Tue, Jan 30, 2024 at 4:43 PM Bharath Rupireddy\n<bharath.rupireddyforpostgres@gmail.com> wrote:\n>\n> On Tue, Jan 30, 2024 at 6:24 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > Hi,\n> >\n> > While working on radix tree patch[1], John Naylor found that dsa.c\n> > doesn't already use shared locks even in dsa_dump(). dsa_dump() seems\n> > a pure read-only function so I thought we could use a shared lock mode\n> > there. Is there any reason to use exclusive mode even in dsa_dump()?\n>\n> check_for_freed_segments_locked which is called from dsa_dump does\n> mark a few variables of the dsa area to NULL right?\n\nRight. But IIUC these are backend-local variables, and we don't change\nany shared variables.\n\n> Are you suggesting\n> to take initially a shared lock in dsa_dump and upgrade it to\n> exclusive mode in the unlikely event of\n> unlikely(area->freed_segment_counter != freed_segment_counter)\n> occurring in check_for_freed_segments_locked?\n\nI thought we could just take a shared lock in dsa_dump().\n\n>\n> > Ultimately, since we're trying to add a new function\n> > dsa_get_total_size() that just returns\n> > dsa_area_control.total_segment_size and therefore would also be a\n> > read-only function, I'd like to find out the correct lock mode there.\n> >\n> > [1] https://www.postgresql.org/message-id/CANWCAZYYzoKp_4%2B1m5mn-TRD62BTwom8iLXLOWMsHkkwFi%3Drzg%40mail.gmail.com\n>\n> Do you see any lock contention or any other issues with exclusive\n> locks on dsa areas?\n\nNot particularly for now. But we don't need to unnecessarily take an\nexclusive lock and even a shared lock looks safe at a glance. So I\nneed to convince myself that we need to take an exclusive lock there\nin order to add a new dsa_get_total_size() function. And we might need\ncomments.\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 30 Jan 2024 21:16:36 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Question on LWLockMode in dsa.c"
},
{
"msg_contents": "On Tue, Jan 30, 2024 at 6:24 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> Hi,\n>\n> While working on radix tree patch[1], John Naylor found that dsa.c\n> doesn't already use shared locks even in dsa_dump(). dsa_dump() seems\n> a pure read-only function so I thought we could use a shared lock mode\n> there. Is there any reason to use exclusive mode even in dsa_dump()?\n>\n> Ultimately, since we're trying to add a new function\n> dsa_get_total_size() that just returns\n> dsa_area_control.total_segment_size and therefore would also be a\n> read-only function, I'd like to find out the correct lock mode there.\n>\n\nDoesn't seem like there is any reason for this to be an exclusive lock.\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n",
"msg_date": "Tue, 6 Feb 2024 15:48:14 +0530",
"msg_from": "Dilip Kumar <dilipbalaut@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Question on LWLockMode in dsa.c"
}
] |
[
{
"msg_contents": "Hi\n\nI have one question, what is a block of implementation of some variant of\nVACUUM FULL like REINDEX CONCURRENTLY? Why similar mechanism of REINDEX\nCONCURRENTLY cannot be used for VACUUM FULL?\n\nRegards\n\nPavel\n\nHiI have one question, what is a block of implementation of some variant of VACUUM FULL like REINDEX CONCURRENTLY? Why similar mechanism of REINDEX CONCURRENTLY cannot be used for VACUUM FULL?RegardsPavel",
"msg_date": "Tue, 30 Jan 2024 09:01:57 +0100",
"msg_from": "Pavel Stehule <pavel.stehule@gmail.com>",
"msg_from_op": true,
"msg_subject": "why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "On Tue, Jan 30, 2024 at 09:01:57AM +0100, Pavel Stehule wrote:\n> I have one question, what is a block of implementation of some variant of\n> VACUUM FULL like REINDEX CONCURRENTLY? Why similar mechanism of REINDEX\n> CONCURRENTLY cannot be used for VACUUM FULL?\n\nYou may be interested in these threads:\nhttps://www.postgresql.org/message-id/CAB7nPqTGmNUFi%2BW6F1iwmf7J-o6sY%2Bxxo6Yb%3DmkUVYT-CG-B5A%40mail.gmail.com\nhttps://www.postgresql.org/message-id/CAB7nPqTys6JUQDxUczbJb0BNW0kPrW8WdZuk11KaxQq6o98PJg%40mail.gmail.com\n\nVACUUM FULL is CLUSTER under the hoods. One may question whether it\nis still a relevant discussion these days if we assume that autovacuum\nis able to keep up, because it always keeps up with the house cleanup,\nright? ;)\n\nMore seriously, we have a lot more options these days with VACUUM like \nPARALLEL, so CONCURRENTLY may still have some uses, but the new toys\navailable may have changed things. So, would it be worth the\ncomplexities around heap manipulations that lower locks would require?\n--\nMichael",
"msg_date": "Tue, 30 Jan 2024 17:14:07 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "út 30. 1. 2024 v 9:14 odesílatel Michael Paquier <michael@paquier.xyz>\nnapsal:\n\n> On Tue, Jan 30, 2024 at 09:01:57AM +0100, Pavel Stehule wrote:\n> > I have one question, what is a block of implementation of some variant of\n> > VACUUM FULL like REINDEX CONCURRENTLY? Why similar mechanism of REINDEX\n> > CONCURRENTLY cannot be used for VACUUM FULL?\n>\n> You may be interested in these threads:\n>\n> https://www.postgresql.org/message-id/CAB7nPqTGmNUFi%2BW6F1iwmf7J-o6sY%2Bxxo6Yb%3DmkUVYT-CG-B5A%40mail.gmail.com\n>\n> https://www.postgresql.org/message-id/CAB7nPqTys6JUQDxUczbJb0BNW0kPrW8WdZuk11KaxQq6o98PJg%40mail.gmail.com\n>\n> VACUUM FULL is CLUSTER under the hoods. One may question whether it\n> is still a relevant discussion these days if we assume that autovacuum\n> is able to keep up, because it always keeps up with the house cleanup,\n> right? ;)\n>\n> More seriously, we have a lot more options these days with VACUUM like\n> PARALLEL, so CONCURRENTLY may still have some uses, but the new toys\n> available may have changed things. So, would it be worth the\n> complexities around heap manipulations that lower locks would require?\n>\n\nOne of my customer today is reducing one table from 140GB to 20GB. Now he\nis able to run archiving. He should play with pg_repack, and it is working\nwell today, but I ask myself, what pg_repack does not be hard to do\ninternally because it should be done for REINDEX CONCURRENTLY. This is not\na common task, and not will be, but on the other hand, it can be nice to\nhave feature, and maybe not too hard to implement today. But I didn't try it\n\nI'll read the threads\n\nPavel\n\n\n--\n> Michael\n>\n\nút 30. 1. 2024 v 9:14 odesílatel Michael Paquier <michael@paquier.xyz> napsal:On Tue, Jan 30, 2024 at 09:01:57AM +0100, Pavel Stehule wrote:\n> I have one question, what is a block of implementation of some variant of\n> VACUUM FULL like REINDEX CONCURRENTLY? Why similar mechanism of REINDEX\n> CONCURRENTLY cannot be used for VACUUM FULL?\n\nYou may be interested in these threads:\nhttps://www.postgresql.org/message-id/CAB7nPqTGmNUFi%2BW6F1iwmf7J-o6sY%2Bxxo6Yb%3DmkUVYT-CG-B5A%40mail.gmail.com\nhttps://www.postgresql.org/message-id/CAB7nPqTys6JUQDxUczbJb0BNW0kPrW8WdZuk11KaxQq6o98PJg%40mail.gmail.com\n\nVACUUM FULL is CLUSTER under the hoods. One may question whether it\nis still a relevant discussion these days if we assume that autovacuum\nis able to keep up, because it always keeps up with the house cleanup,\nright? ;)\n\nMore seriously, we have a lot more options these days with VACUUM like \nPARALLEL, so CONCURRENTLY may still have some uses, but the new toys\navailable may have changed things. So, would it be worth the\ncomplexities around heap manipulations that lower locks would require?One of my customer today is reducing one table from 140GB to 20GB. Now he is able to run archiving. He should play with pg_repack, and it is working well today, but I ask myself, what pg_repack does not be hard to do internally because it should be done for REINDEX CONCURRENTLY. This is not a common task, and not will be, but on the other hand, it can be nice to have feature, and maybe not too hard to implement today. But I didn't try itI'll read the threadsPavel\n--\nMichael",
"msg_date": "Tue, 30 Jan 2024 09:31:12 +0100",
"msg_from": "Pavel Stehule <pavel.stehule@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "On 2024-Jan-30, Pavel Stehule wrote:\n\n> One of my customer today is reducing one table from 140GB to 20GB. Now he\n> is able to run archiving. He should play with pg_repack, and it is working\n> well today, but I ask myself, what pg_repack does not be hard to do\n> internally because it should be done for REINDEX CONCURRENTLY. This is not\n> a common task, and not will be, but on the other hand, it can be nice to\n> have feature, and maybe not too hard to implement today. But I didn't try it\n\nFWIW a newer, more modern and more trustworthy alternative to pg_repack\nis pg_squeeze, which I discovered almost by random chance, and soon\ndiscovered I liked it much more.\n\nSo thinking about your question, I think it might be possible to\nintegrate a tool that works like pg_squeeze, such that it runs when\nVACUUM is invoked -- either under some new option, or just replace the\ncode under FULL, not sure. If the Cybertec people allows it, we could\njust grab the pg_squeeze code and add it to the things that VACUUM can\nrun.\n\nNow, pg_squeeze has some additional features, such as periodic\n\"squeezing\" of tables. In a first attempt, for simplicity, I would\nleave that stuff out and just allow it to run from the user invoking it,\nand then have the command to do a single run. (The scheduling features\ncould be added later, or somehow integrated into autovacuum, or maybe\nsomething else.)\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"We're here to devour each other alive\" (Hobbes)\n\n\n",
"msg_date": "Tue, 30 Jan 2024 11:31:17 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "út 30. 1. 2024 v 11:31 odesílatel Alvaro Herrera <alvherre@alvh.no-ip.org>\nnapsal:\n\n> On 2024-Jan-30, Pavel Stehule wrote:\n>\n> > One of my customer today is reducing one table from 140GB to 20GB. Now\n> he\n> > is able to run archiving. He should play with pg_repack, and it is\n> working\n> > well today, but I ask myself, what pg_repack does not be hard to do\n> > internally because it should be done for REINDEX CONCURRENTLY. This is\n> not\n> > a common task, and not will be, but on the other hand, it can be nice to\n> > have feature, and maybe not too hard to implement today. But I didn't\n> try it\n>\n> FWIW a newer, more modern and more trustworthy alternative to pg_repack\n> is pg_squeeze, which I discovered almost by random chance, and soon\n> discovered I liked it much more.\n>\n> So thinking about your question, I think it might be possible to\n> integrate a tool that works like pg_squeeze, such that it runs when\n> VACUUM is invoked -- either under some new option, or just replace the\n> code under FULL, not sure. If the Cybertec people allows it, we could\n> just grab the pg_squeeze code and add it to the things that VACUUM can\n> run.\n>\n> Now, pg_squeeze has some additional features, such as periodic\n> \"squeezing\" of tables. In a first attempt, for simplicity, I would\n> leave that stuff out and just allow it to run from the user invoking it,\n> and then have the command to do a single run. (The scheduling features\n> could be added later, or somehow integrated into autovacuum, or maybe\n> something else.)\n>\n\nsome basic variant (without autovacuum support) can be good enough. We have\nno autovacuum support for REINDEX CONCURRENTLY and I don't see a necessity\nfor it (sure, it can be limited by my perspective) . The necessity of\nreducing table size is not too common (a lot of use cases are better\ncovered by using partitioning), but sometimes it is, and then buildin\nsimple available solution can be helpful.\n\n\n\n\n\n> --\n> Álvaro Herrera PostgreSQL Developer —\n> https://www.EnterpriseDB.com/\n> \"We're here to devour each other alive\" (Hobbes)\n>\n\nút 30. 1. 2024 v 11:31 odesílatel Alvaro Herrera <alvherre@alvh.no-ip.org> napsal:On 2024-Jan-30, Pavel Stehule wrote:\n\n> One of my customer today is reducing one table from 140GB to 20GB. Now he\n> is able to run archiving. He should play with pg_repack, and it is working\n> well today, but I ask myself, what pg_repack does not be hard to do\n> internally because it should be done for REINDEX CONCURRENTLY. This is not\n> a common task, and not will be, but on the other hand, it can be nice to\n> have feature, and maybe not too hard to implement today. But I didn't try it\n\nFWIW a newer, more modern and more trustworthy alternative to pg_repack\nis pg_squeeze, which I discovered almost by random chance, and soon\ndiscovered I liked it much more.\n\nSo thinking about your question, I think it might be possible to\nintegrate a tool that works like pg_squeeze, such that it runs when\nVACUUM is invoked -- either under some new option, or just replace the\ncode under FULL, not sure. If the Cybertec people allows it, we could\njust grab the pg_squeeze code and add it to the things that VACUUM can\nrun.\n\nNow, pg_squeeze has some additional features, such as periodic\n\"squeezing\" of tables. In a first attempt, for simplicity, I would\nleave that stuff out and just allow it to run from the user invoking it,\nand then have the command to do a single run. (The scheduling features\ncould be added later, or somehow integrated into autovacuum, or maybe\nsomething else.)some basic variant (without autovacuum support) can be good enough. We have no autovacuum support for REINDEX CONCURRENTLY and I don't see a necessity for it (sure, it can be limited by my perspective) . The necessity of reducing table size is not too common (a lot of use cases are better covered by using partitioning), but sometimes it is, and then buildin simple available solution can be helpful. \n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"We're here to devour each other alive\" (Hobbes)",
"msg_date": "Tue, 30 Jan 2024 11:47:49 +0100",
"msg_from": "Pavel Stehule <pavel.stehule@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "On 2024-Jan-30, Pavel Stehule wrote:\n\n> some basic variant (without autovacuum support) can be good enough. We have\n> no autovacuum support for REINDEX CONCURRENTLY and I don't see a necessity\n> for it (sure, it can be limited by my perspective) . The necessity of\n> reducing table size is not too common (a lot of use cases are better\n> covered by using partitioning), but sometimes it is, and then buildin\n> simple available solution can be helpful.\n\nThat's my thinking as well.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\n\n",
"msg_date": "Tue, 30 Jan 2024 12:37:12 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "On Tue, Jan 30, 2024 at 12:37:12PM +0100, Alvaro Herrera wrote:\n> On 2024-Jan-30, Pavel Stehule wrote:\n> \n> > some basic variant (without autovacuum support) can be good enough. We have\n> > no autovacuum support for REINDEX CONCURRENTLY and I don't see a necessity\n> > for it (sure, it can be limited by my perspective) . The necessity of\n> > reducing table size is not too common (a lot of use cases are better\n> > covered by using partitioning), but sometimes it is, and then buildin\n> > simple available solution can be helpful.\n> \n> That's my thinking as well.\n\nOr, yes, I'd agree about that. This can make for a much better user\nexperience. I'm just not sure how that stuff would be shaped and how\nmuch ground it would need to cover.\n--\nMichael",
"msg_date": "Wed, 31 Jan 2024 08:06:17 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n\n> On 2024-Jan-30, Pavel Stehule wrote:\n> \n> > One of my customer today is reducing one table from 140GB to 20GB. Now he\n> > is able to run archiving. He should play with pg_repack, and it is working\n> > well today, but I ask myself, what pg_repack does not be hard to do\n> > internally because it should be done for REINDEX CONCURRENTLY. This is not\n> > a common task, and not will be, but on the other hand, it can be nice to\n> > have feature, and maybe not too hard to implement today. But I didn't try it\n> \n> FWIW a newer, more modern and more trustworthy alternative to pg_repack\n> is pg_squeeze, which I discovered almost by random chance, and soon\n> discovered I liked it much more.\n> \n> So thinking about your question, I think it might be possible to\n> integrate a tool that works like pg_squeeze, such that it runs when\n> VACUUM is invoked -- either under some new option, or just replace the\n> code under FULL, not sure. If the Cybertec people allows it, we could\n> just grab the pg_squeeze code and add it to the things that VACUUM can\n> run.\n\nThere are no objections from Cybertec. Nevertheless, I don't expect much code\nto be just copy & pasted. If I started to implement the extension today, I'd\ndo some things in a different way. (Some things might actually be simpler in\nthe core, i.e. a few small changes in PG core are easier than the related\nworkarounds in the extension.)\n\nThe core idea is that: 1) a \"historic snapshot\" is used to get the current\ncontents of the table, 2) logical decoding is used to capture the changes done\nwhile the data is being copied to new storage, 3) the exclusive lock on the\ntable is only taken for very short time, to swap the storage (relfilenode) of\nthe table.\n\nI think it should be coded in a way that allows use by VACUUM FULL, CLUSTER,\nand possibly some subcommands of ALTER TABLE. For example, some users of\npg_squeeze requested an enhancement that allows the user to change column data\ntype w/o service disruption (typically when it appears that integer type is\ngoing to overflow and change bigint is needed).\n\nOnline (re)partitioning could be another use case, although I admit that\ncommands that change the system catalog are a bit harder to implement than\nVACUUM FULL / CLUSTER.\n\nOne thing that pg_squeeze does not handle is visibility: it uses heap_insert()\nto insert the tuples into the new storage, so the problems described in [1]\ncan appear. The in-core implementation should rather do something like tuple\nrewriting (rewriteheap.c).\n\nIs your plan to work on it soon or should I try to write a draft patch? (I\nassume this is for PG >= 18.)\n\n[1] https://www.postgresql.org/docs/current/mvcc-caveats.html\n\n-- \nAntonin Houska\nWeb: https://www.cybertec-postgresql.com\n\n\n",
"msg_date": "Wed, 31 Jan 2024 10:55:13 +0100",
"msg_from": "Antonin Houska <ah@cybertec.at>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "This is great to hear.\n\nOn 2024-Jan-31, Antonin Houska wrote:\n\n> Is your plan to work on it soon or should I try to write a draft patch? (I\n> assume this is for PG >= 18.)\n\nI don't have plans for it, so if you have resources, please go for it.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\n\n",
"msg_date": "Wed, 31 Jan 2024 11:04:24 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n\n> This is great to hear.\n> \n> On 2024-Jan-31, Antonin Houska wrote:\n> \n> > Is your plan to work on it soon or should I try to write a draft patch? (I\n> > assume this is for PG >= 18.)\n> \n> I don't have plans for it, so if you have resources, please go for it.\n\nok, I'm thinking how can the feature be integrated into the core.\n\nBTW, I'm failing to understand why cluster_rel() has no argument of the\nBufferAccessStrategy type. According to buffer/README, the criterion for using\nspecific strategy is that page \"is unlikely to be needed again\nsoon\". Specifically for cluster_rel(), the page will *definitely* not be used\nagain (unless the VACCUM FULL/CLUSTER command fails): BufferTag contains the\nrelatin file number and the old relation file is eventually dropped.\n\nAm I missing anything?\n\n-- \nAntonin Houska\nWeb: https://www.cybertec-postgresql.com\n\n\n",
"msg_date": "Fri, 16 Feb 2024 18:43:29 +0100",
"msg_from": "Antonin Houska <ah@cybertec.at>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "On 2024-Feb-16, Antonin Houska wrote:\n\n> BTW, I'm failing to understand why cluster_rel() has no argument of the\n> BufferAccessStrategy type. According to buffer/README, the criterion for using\n> specific strategy is that page \"is unlikely to be needed again\n> soon\". Specifically for cluster_rel(), the page will *definitely* not be used\n> again (unless the VACCUM FULL/CLUSTER command fails): BufferTag contains the\n> relatin file number and the old relation file is eventually dropped.\n> \n> Am I missing anything?\n\nNo, that's just an oversight. Access strategies are newer than that\ncluster code.\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n\"Most hackers will be perfectly comfortable conceptualizing users as entropy\n sources, so let's move on.\" (Nathaniel Smith)\n https://mail.gnu.org/archive/html/monotone-devel/2007-01/msg00080.html\n\n\n",
"msg_date": "Thu, 7 Mar 2024 18:56:46 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n\n> > Is your plan to work on it soon or should I try to write a draft patch? (I\n> > assume this is for PG >= 18.)\n> \n> I don't have plans for it, so if you have resources, please go for it.\n\nThe first version is attached. The actual feature is in 0003. 0004 is probably\nnot necessary now, but I haven't realized until I coded it.\n\n-- \nAntonin Houska\nWeb: https://www.cybertec-postgresql.com\n\n\n\n\n From 1cb536663c018d98faf349a680b773364b464026 Mon Sep 17 00:00:00 2001\nFrom: Antonin Houska <ah@cybertec.at>\nDate: Tue, 9 Jul 2024 17:45:59 +0200\nSubject: [PATCH 3/4] Add CONCURRENTLY option to both VACUUM FULL and CLUSTER\n commands.\n\nBoth VACUUM FULL and CLUSTER commands copy the relation data into a new file,\ncreate new indexes and eventually swap the files. To make sure that the old\nfile does not change during the copying, the relation is locked in an\nexclusive mode, which prevents applications from both reading and writing. (To\nkeep the data consistent, we'd only need to prevent the applications from\nwriting, but even reading needs to be blocked before we can swap the files -\notherwise some applications could continue using the old file. Since we cannot\nget stronger lock without releasing the weaker one first, we acquire the\nexclusive lock in the beginning and keep it till the end of the processing.)\n\nThis patch introduces an alternative workflow, which only requires the\nexclusive lock when the relation (and index) files are being swapped.\n(Supposedly, the swapping should be pretty fast.) On the other hand, when we\ncopy the data to the new file, we allow applications to read from the relation\nand even write into it.\n\nFirst, we scan the relation using a \"historic snapshot\", and insert all the\ntuples satisfying this snapshot into the new file. Note that, before creating\nthat snapshot, we need to make sure that all the other backends treat the\nrelation as a system catalog: in particular, they must log information on new\ncommand IDs (CIDs). We achieve that by adding the relation ID into a shared\nhash table and waiting until all the transactions currently writing into the\ntable (i.e. transactions possibly not aware of the new entry) have finished.\n\nSecond, logical decoding is used to capture the data changes done by\napplications during the copying (i.e. changes that do not satisfy the historic\nsnapshot mentioned above), and those are applied to the new file before we\nacquire the exclusive lock we need to swap the files. (Of course, more data\nchanges can take place while we are waiting for the lock - these will be\napplied to the new file after we have acquired the lock, before we swap the\nfiles.)\n\nWhile copying the data into the new file, we hold a lock that prevents\napplications from changing the relation tuple descriptor (tuples inserted into\nthe old file must fit into the new file). However, as we have to release that\nlock before getting the exclusive one, it's possible that someone adds or\ndrops a column, or changes the data type of an existing one. Therefore we have\nto check the tuple descriptor before we swap the files. If we find out that\nthe tuple descriptor changed, ERROR is raised and all the changes are rolled\nback. Since a lot of effort can be wasted in such a case, the ALTER TABLE\ncommand also tries to check if VACUUM FULL / CLUSTER with the CONCURRENTLY\noption is running on the same relation, and raises an ERROR if it is.\n\nLike the existing implementation of both VACUUM FULL and CLUSTER commands, the\nvariant with the CONCURRENTLY option also requires an extra space for the new\nrelation and index files (which coexist with the old files for some time). In\naddition, the CONCURRENTLY option might introduce a lag in releasing WAL\nsegments for archiving / recycling. This is due to the decoding of the data\nchanges done by application concurrently. However, this lag should not be more\nthan a single WAL segment.\n---\n doc/src/sgml/monitoring.sgml | 36 +-\n doc/src/sgml/ref/cluster.sgml | 114 +-\n doc/src/sgml/ref/vacuum.sgml | 27 +-\n src/Makefile | 1 +\n src/backend/access/common/toast_internals.c | 3 +-\n src/backend/access/heap/heapam.c | 80 +-\n src/backend/access/heap/heapam_handler.c | 155 +-\n src/backend/access/heap/heapam_visibility.c | 30 +-\n src/backend/access/transam/xact.c | 52 +\n src/backend/catalog/index.c | 43 +-\n src/backend/catalog/system_views.sql | 17 +-\n src/backend/commands/cluster.c | 2618 ++++++++++++++++-\n src/backend/commands/matview.c | 2 +-\n src/backend/commands/tablecmds.c | 11 +\n src/backend/commands/vacuum.c | 137 +-\n src/backend/replication/logical/decode.c | 58 +-\n src/backend/replication/logical/snapbuild.c | 87 +-\n .../replication/pgoutput_cluster/Makefile | 32 +\n .../replication/pgoutput_cluster/meson.build | 18 +\n .../pgoutput_cluster/pgoutput_cluster.c | 321 ++\n src/backend/storage/ipc/ipci.c | 3 +\n src/backend/tcop/utility.c | 11 +\n src/backend/utils/activity/backend_progress.c | 16 +\n .../utils/activity/wait_event_names.txt | 1 +\n src/backend/utils/cache/inval.c | 22 +\n src/backend/utils/cache/relcache.c | 5 +\n src/backend/utils/time/snapmgr.c | 6 +-\n src/bin/psql/tab-complete.c | 5 +-\n src/include/access/heapam.h | 19 +-\n src/include/access/heapam_xlog.h | 2 +\n src/include/access/tableam.h | 10 +\n src/include/access/xact.h | 2 +\n src/include/catalog/index.h | 3 +\n src/include/commands/cluster.h | 117 +-\n src/include/commands/progress.h | 17 +-\n src/include/commands/vacuum.h | 17 +-\n src/include/replication/snapbuild.h | 2 +\n src/include/storage/lockdefs.h | 2 +-\n src/include/storage/lwlocklist.h | 1 +\n src/include/utils/backend_progress.h | 3 +-\n src/include/utils/inval.h | 2 +\n src/include/utils/rel.h | 7 +-\n src/include/utils/snapmgr.h | 3 +\n src/test/regress/expected/rules.out | 17 +-\n 44 files changed, 3876 insertions(+), 259 deletions(-)\n create mode 100644 src/backend/replication/pgoutput_cluster/Makefile\n create mode 100644 src/backend/replication/pgoutput_cluster/meson.build\n create mode 100644 src/backend/replication/pgoutput_cluster/pgoutput_cluster.c\n\ndiff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml\nindex 991f629907..fe1ba36f40 100644\n--- a/doc/src/sgml/monitoring.sgml\n+++ b/doc/src/sgml/monitoring.sgml\n@@ -5567,14 +5567,35 @@ FROM pg_stat_get_backend_idset() AS backendid;\n \n <row>\n <entry role=\"catalog_table_entry\"><para role=\"column_definition\">\n- <structfield>heap_tuples_written</structfield> <type>bigint</type>\n+ <structfield>heap_tuples_inserted</structfield> <type>bigint</type>\n </para>\n <para>\n- Number of heap tuples written.\n+ Number of heap tuples inserted.\n This counter only advances when the phase is\n <literal>seq scanning heap</literal>,\n- <literal>index scanning heap</literal>\n- or <literal>writing new heap</literal>.\n+ <literal>index scanning heap</literal>,\n+ <literal>writing new heap</literal>\n+ or <literal>catch-up</literal>.\n+ </para></entry>\n+ </row>\n+\n+ <row>\n+ <entry role=\"catalog_table_entry\"><para role=\"column_definition\">\n+ <structfield>heap_tuples_updated</structfield> <type>bigint</type>\n+ </para>\n+ <para>\n+ Number of heap tuples updated.\n+ This counter only advances when the phase is <literal>catch-up</literal>.\n+ </para></entry>\n+ </row>\n+\n+ <row>\n+ <entry role=\"catalog_table_entry\"><para role=\"column_definition\">\n+ <structfield>heap_tuples_deleted</structfield> <type>bigint</type>\n+ </para>\n+ <para>\n+ Number of heap tuples deleted.\n+ This counter only advances when the phase is <literal>catch-up</literal>.\n </para></entry>\n </row>\n \n@@ -5655,6 +5676,13 @@ FROM pg_stat_get_backend_idset() AS backendid;\n <command>CLUSTER</command> is currently writing the new heap.\n </entry>\n </row>\n+ <row>\n+ <entry><literal>catch-up</literal></entry>\n+ <entry>\n+ <command>CLUSTER</command> is currently processing the DML commands\n+ that other transactions executed during any of the preceding phase.\n+ </entry>\n+ </row>\n <row>\n <entry><literal>swapping relation files</literal></entry>\n <entry>\ndiff --git a/doc/src/sgml/ref/cluster.sgml b/doc/src/sgml/ref/cluster.sgml\nindex c5760244e6..0fe4e9603b 100644\n--- a/doc/src/sgml/ref/cluster.sgml\n+++ b/doc/src/sgml/ref/cluster.sgml\n@@ -26,6 +26,7 @@ CLUSTER [ ( <replaceable class=\"parameter\">option</replaceable> [, ...] ) ] [ <r\n <phrase>where <replaceable class=\"parameter\">option</replaceable> can be one of:</phrase>\n \n VERBOSE [ <replaceable class=\"parameter\">boolean</replaceable> ]\n+ CONCURRENTLY [ <replaceable class=\"parameter\">boolean</replaceable> ]\n </synopsis>\n </refsynopsisdiv>\n \n@@ -69,14 +70,18 @@ CLUSTER [ ( <replaceable class=\"parameter\">option</replaceable> [, ...] ) ] [ <r\n <replaceable class=\"parameter\">table_name</replaceable> reclusters all the\n previously-clustered tables in the current database that the calling user\n has privileges for. This form of <command>CLUSTER</command> cannot be\n- executed inside a transaction block.\n+ executed inside a transaction block. Also, if\n+ the <literal>CONCURRENTLY</literal> option is used with this form, system\n+ catalogs and <acronym>TOAST</acronym> tables are not processed.\n </para>\n \n <para>\n- When a table is being clustered, an <literal>ACCESS\n- EXCLUSIVE</literal> lock is acquired on it. This prevents any other\n- database operations (both reads and writes) from operating on the\n- table until the <command>CLUSTER</command> is finished.\n+ When a table is being clustered, an <literal>ACCESS EXCLUSIVE</literal>\n+ lock is acquired on it. This prevents any other database operations (both\n+ reads and writes) from operating on the table until\n+ the <command>CLUSTER</command> is finished. If you want to keep the table\n+ accessible during the clustering, consider using\n+ the <literal>CONCURRENTLY</literal> option.\n </para>\n </refsect1>\n \n@@ -111,6 +116,105 @@ CLUSTER [ ( <replaceable class=\"parameter\">option</replaceable> [, ...] ) ] [ <r\n </listitem>\n </varlistentry>\n \n+ <varlistentry>\n+ <term><literal>CONCURRENTLY</literal></term>\n+ <listitem>\n+ <para>\n+ Allow other transactions to use the table while it is being clustered.\n+ </para>\n+\n+ <para>\n+ Internally, <command>CLUSTER</command> copies the contents of the table\n+ (ignoring dead tuples) into a new file, sorted by the specified index,\n+ and also creates a new file for each index. Then it swaps the old and\n+ new files for the table and all the indexes, and deletes the old\n+ files. The <literal>ACCESS EXCLUSIVE</literal> lock is needed to make\n+ sure that the old files do not change during the processing because the\n+ chnages would get lost due to the swap.\n+ </para>\n+\n+ <para>\n+ With the <literal>CONCURRENTLY</literal> option, the <literal>ACCESS\n+ EXCLUSIVE</literal> lock is only acquired to swap the table and index\n+ files. The data changes that took place during the creation of the new\n+ table and index files are captured using logical decoding\n+ (<xref linkend=\"logicaldecoding\"/>) and applied before\n+ the <literal>ACCESS EXCLUSIVE</literal> lock is requested. Thus the lock\n+ is typically held only for the time needed to swap the files, which\n+ should be pretty short. However, the time might still be noticeable\n+ noticeable if too many data changes have been done to the table\n+ while <command>CLUSTER</command> was waiting for the lock: those changes\n+ must be processed before the files are swapped.\n+ </para>\n+\n+ <para>\n+ Note that <command>CLUSTER</command> with the\n+ the <literal>CONCURRENTLY</literal> option does not try to order the\n+ rows inserted into the table after the clustering started. Also\n+ note <command>CLUSTER</command> might fail to complete due to DDL\n+ commands executed on the table by other transactions during the\n+ clustering.\n+ </para>\n+\n+ <note>\n+ <para>\n+ In addition to the temporary space requirements explained below,\n+ the <literal>CONCURRENTLY</literal> option can add to the usage of\n+ temporary space a bit more. The reason is that other transactions can\n+ perform DML operations which cannot be applied to the new file until\n+ <command>CLUSTER</command> has copied all the tuples from the old\n+ file. Thus the tuples inserted into the old file during the copying are\n+ also stored in separately in a temporary file, so they can eventually\n+ be applied to the new file.\n+ </para>\n+\n+ <para>\n+ Furthermore, the data changes performed during the copying are\n+ extracted from <link linkend=\"wal\">write-ahead log</link> (WAL), and\n+ this extraction (decoding) only takes place when certain amount of WAL\n+ has been written. Therefore, WAL removal can be delayed by this\n+ threshold. Currently the threshold is equal to the value of\n+ the <link linkend=\"guc-wal-segment-size\"><varname>wal_segment_size</varname></link>\n+ configuration parameter.\n+ </para>\n+ </note>\n+\n+ <para>\n+ The <literal>CONCURRENTLY</literal> option cannot be used in the\n+ following cases:\n+\n+ <itemizedlist>\n+ <listitem>\n+ <para>\n+ The table is a system catalog or a <acronym>TOAST</acronym> table.\n+ </para>\n+ </listitem>\n+\n+ <listitem>\n+ <para>\n+ <command>CLUSTER</command> is executed inside a transaction block.\n+ </para>\n+ </listitem>\n+\n+ <listitem>\n+ <para>\n+ The <link linkend=\"guc-wal-level\"><varname>wal_level</varname></link>\n+ configuration parameter is less than <literal>logical</literal>.\n+ </para>\n+ </listitem>\n+\n+ <listitem>\n+ <para>\n+ The <link linkend=\"guc-max-replication-slots\"><varname>max_replication_slots</varname></link>\n+ configuration parameter does not allow for creation of an additional\n+ replication slot.\n+ </para>\n+ </listitem>\n+ </itemizedlist>\n+ </para>\n+ </listitem>\n+ </varlistentry>\n+\n <varlistentry>\n <term><replaceable class=\"parameter\">boolean</replaceable></term>\n <listitem>\ndiff --git a/doc/src/sgml/ref/vacuum.sgml b/doc/src/sgml/ref/vacuum.sgml\nindex 9857b35627..298cf7298d 100644\n--- a/doc/src/sgml/ref/vacuum.sgml\n+++ b/doc/src/sgml/ref/vacuum.sgml\n@@ -39,6 +39,7 @@ VACUUM [ ( <replaceable class=\"parameter\">option</replaceable> [, ...] ) ] [ <re\n SKIP_DATABASE_STATS [ <replaceable class=\"parameter\">boolean</replaceable> ]\n ONLY_DATABASE_STATS [ <replaceable class=\"parameter\">boolean</replaceable> ]\n BUFFER_USAGE_LIMIT <replaceable class=\"parameter\">size</replaceable>\n+ CONCURRENTLY [ <replaceable class=\"parameter\">boolean</replaceable> ]\n \n <phrase>and <replaceable class=\"parameter\">table_and_columns</replaceable> is:</phrase>\n \n@@ -61,8 +62,12 @@ VACUUM [ ( <replaceable class=\"parameter\">option</replaceable> [, ...] ) ] [ <re\n <para>\n Without a <replaceable class=\"parameter\">table_and_columns</replaceable>\n list, <command>VACUUM</command> processes every table and materialized view\n- in the current database that the current user has permission to vacuum.\n- With a list, <command>VACUUM</command> processes only those table(s).\n+ in the current database that the current user has permission to vacuum. If\n+ the <literal>CONCURRENTLY</literal> is specified (see below), tables which\n+ have not been clustered yet are silently skipped. With a\n+ list, <command>VACUUM</command> processes only those table(s). If\n+ the <literal>CONCURRENTLY</literal> is specified, the list may only contain\n+ tables which have already been clustered.\n </para>\n \n <para>\n@@ -360,6 +365,24 @@ VACUUM [ ( <replaceable class=\"parameter\">option</replaceable> [, ...] ) ] [ <re\n </listitem>\n </varlistentry>\n \n+ <varlistentry>\n+ <term><literal>CONCURRENTLY</literal></term>\n+ <listitem>\n+ <para>\n+ Allow other transactions to use the table while it is being vacuumed. If\n+ this option is specified, <command>VACUUM</command> can only process\n+ tables which have already been clustered. For more information, see the\n+ description of the <literal>CONCURRENTLY</literal> of the\n+ <xref linkend=\"sql-cluster\"/> command.\n+ </para>\n+\n+ <para>\n+ The <literal>CONCURRENTLY</literal> option can only be used\n+ if <literal>FULL</literal> is used at the same time.\n+ </para>\n+ </listitem>\n+ </varlistentry>\n+\n <varlistentry>\n <term><replaceable class=\"parameter\">boolean</replaceable></term>\n <listitem>\ndiff --git a/src/Makefile b/src/Makefile\nindex 2f31a2f20a..8b9d30ff72 100644\n--- a/src/Makefile\n+++ b/src/Makefile\n@@ -23,6 +23,7 @@ SUBDIRS = \\\n \tinterfaces \\\n \tbackend/replication/libpqwalreceiver \\\n \tbackend/replication/pgoutput \\\n+\tbackend/replication/pgoutput_cluster \\\n \tfe_utils \\\n \tbin \\\n \tpl \\\ndiff --git a/src/backend/access/common/toast_internals.c b/src/backend/access/common/toast_internals.c\nindex 90d0654e62..183055647b 100644\n--- a/src/backend/access/common/toast_internals.c\n+++ b/src/backend/access/common/toast_internals.c\n@@ -320,7 +320,8 @@ toast_save_datum(Relation rel, Datum value,\n \t\tmemcpy(VARDATA(&chunk_data), data_p, chunk_size);\n \t\ttoasttup = heap_form_tuple(toasttupDesc, t_values, t_isnull);\n \n-\t\theap_insert(toastrel, toasttup, mycid, options, NULL);\n+\t\theap_insert(toastrel, toasttup, GetCurrentTransactionId(), mycid,\n+\t\t\t\t\toptions, NULL);\n \n \t\t/*\n \t\t * Create the index entry. We cheat a little here by not using\ndiff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c\nindex 91b20147a0..493c351d7f 100644\n--- a/src/backend/access/heap/heapam.c\n+++ b/src/backend/access/heap/heapam.c\n@@ -75,7 +75,8 @@ static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup,\n static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf,\n \t\t\t\t\t\t\t\t Buffer newbuf, HeapTuple oldtup,\n \t\t\t\t\t\t\t\t HeapTuple newtup, HeapTuple old_key_tuple,\n-\t\t\t\t\t\t\t\t bool all_visible_cleared, bool new_all_visible_cleared);\n+\t\t\t\t\t\t\t\t bool all_visible_cleared, bool new_all_visible_cleared,\n+\t\t\t\t\t\t\t\t bool wal_logical);\n static Bitmapset *HeapDetermineColumnsInfo(Relation relation,\n \t\t\t\t\t\t\t\t\t\t Bitmapset *interesting_cols,\n \t\t\t\t\t\t\t\t\t\t Bitmapset *external_cols,\n@@ -1975,7 +1976,7 @@ ReleaseBulkInsertStatePin(BulkInsertState bistate)\n /*\n *\theap_insert\t\t- insert tuple into a heap\n *\n- * The new tuple is stamped with current transaction ID and the specified\n+ * The new tuple is stamped with specified transaction ID and the specified\n * command ID.\n *\n * See table_tuple_insert for comments about most of the input flags, except\n@@ -1991,15 +1992,16 @@ ReleaseBulkInsertStatePin(BulkInsertState bistate)\n * reflected into *tup.\n */\n void\n-heap_insert(Relation relation, HeapTuple tup, CommandId cid,\n-\t\t\tint options, BulkInsertState bistate)\n+heap_insert(Relation relation, HeapTuple tup, TransactionId xid,\n+\t\t\tCommandId cid, int options, BulkInsertState bistate)\n {\n-\tTransactionId xid = GetCurrentTransactionId();\n \tHeapTuple\theaptup;\n \tBuffer\t\tbuffer;\n \tBuffer\t\tvmbuffer = InvalidBuffer;\n \tbool\t\tall_visible_cleared = false;\n \n+\tAssert(TransactionIdIsValid(xid));\n+\n \t/* Cheap, simplistic check that the tuple matches the rel's rowtype. */\n \tAssert(HeapTupleHeaderGetNatts(tup->t_data) <=\n \t\t RelationGetNumberOfAttributes(relation));\n@@ -2079,8 +2081,13 @@ heap_insert(Relation relation, HeapTuple tup, CommandId cid,\n \t\t/*\n \t\t * If this is a catalog, we need to transmit combo CIDs to properly\n \t\t * decode, so log that as well.\n+\t\t *\n+\t\t * Currently we only pass HEAP_INSERT_NO_LOGICAL when doing VACUUM\n+\t\t * FULL / CLUSTER, in which case the visibility information does not\n+\t\t * change. Therefore, there's no need to update the decoding snapshot.\n \t\t */\n-\t\tif (RelationIsAccessibleInLogicalDecoding(relation))\n+\t\tif ((options & HEAP_INSERT_NO_LOGICAL) == 0 &&\n+\t\t\tRelationIsAccessibleInLogicalDecoding(relation))\n \t\t\tlog_heap_new_cid(relation, heaptup);\n \n \t\t/*\n@@ -2624,7 +2631,8 @@ heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples,\n void\n simple_heap_insert(Relation relation, HeapTuple tup)\n {\n-\theap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);\n+\theap_insert(relation, tup, GetCurrentTransactionId(),\n+\t\t\t\tGetCurrentCommandId(true), 0, NULL);\n }\n \n /*\n@@ -2681,11 +2689,11 @@ xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)\n */\n TM_Result\n heap_delete(Relation relation, ItemPointer tid,\n-\t\t\tCommandId cid, Snapshot crosscheck, bool wait,\n-\t\t\tTM_FailureData *tmfd, bool changingPart)\n+\t\t\tTransactionId xid, CommandId cid, Snapshot crosscheck, bool wait,\n+\t\t\tTM_FailureData *tmfd, bool changingPart,\n+\t\t\tbool wal_logical)\n {\n \tTM_Result\tresult;\n-\tTransactionId xid = GetCurrentTransactionId();\n \tItemId\t\tlp;\n \tHeapTupleData tp;\n \tPage\t\tpage;\n@@ -2702,6 +2710,7 @@ heap_delete(Relation relation, ItemPointer tid,\n \tbool\t\told_key_copied = false;\n \n \tAssert(ItemPointerIsValid(tid));\n+\tAssert(TransactionIdIsValid(xid));\n \n \t/*\n \t * Forbid this during a parallel operation, lest it allocate a combo CID.\n@@ -2927,7 +2936,8 @@ l1:\n \t * Compute replica identity tuple before entering the critical section so\n \t * we don't PANIC upon a memory allocation failure.\n \t */\n-\told_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);\n+\told_key_tuple = wal_logical ?\n+\t\tExtractReplicaIdentity(relation, &tp, true, &old_key_copied) : NULL;\n \n \t/*\n \t * If this is the first possibly-multixact-able operation in the current\n@@ -2995,8 +3005,12 @@ l1:\n \t\t/*\n \t\t * For logical decode we need combo CIDs to properly decode the\n \t\t * catalog\n+\t\t *\n+\t\t * Like in heap_insert(), visibility is unchanged when called from\n+\t\t * VACUUM FULL / CLUSTER.\n \t\t */\n-\t\tif (RelationIsAccessibleInLogicalDecoding(relation))\n+\t\tif (wal_logical &&\n+\t\t\tRelationIsAccessibleInLogicalDecoding(relation))\n \t\t\tlog_heap_new_cid(relation, &tp);\n \n \t\txlrec.flags = 0;\n@@ -3017,6 +3031,15 @@ l1:\n \t\t\t\txlrec.flags |= XLH_DELETE_CONTAINS_OLD_KEY;\n \t\t}\n \n+\t\t/*\n+\t\t * Unlike UPDATE, DELETE is decoded even if there is no old key, so it\n+\t\t * does not help to clear both XLH_DELETE_CONTAINS_OLD_TUPLE and\n+\t\t * XLH_DELETE_CONTAINS_OLD_KEY. Thus we need an extra flag. TODO\n+\t\t * Consider not decoding tuples w/o the old tuple/key instead.\n+\t\t */\n+\t\tif (!wal_logical)\n+\t\t\txlrec.flags |= XLH_DELETE_NO_LOGICAL;\n+\n \t\tXLogBeginInsert();\n \t\tXLogRegisterData((char *) &xlrec, SizeOfHeapDelete);\n \n@@ -3106,10 +3129,11 @@ simple_heap_delete(Relation relation, ItemPointer tid)\n \tTM_Result\tresult;\n \tTM_FailureData tmfd;\n \n-\tresult = heap_delete(relation, tid,\n+\tresult = heap_delete(relation, tid, GetCurrentTransactionId(),\n \t\t\t\t\t\t GetCurrentCommandId(true), InvalidSnapshot,\n \t\t\t\t\t\t true /* wait for commit */ ,\n-\t\t\t\t\t\t &tmfd, false /* changingPart */ );\n+\t\t\t\t\t\t &tmfd, false, /* changingPart */\n+\t\t\t\t\t\t true /* wal_logical */);\n \tswitch (result)\n \t{\n \t\tcase TM_SelfModified:\n@@ -3148,12 +3172,11 @@ simple_heap_delete(Relation relation, ItemPointer tid)\n */\n TM_Result\n heap_update(Relation relation, ItemPointer otid, HeapTuple newtup,\n-\t\t\tCommandId cid, Snapshot crosscheck, bool wait,\n-\t\t\tTM_FailureData *tmfd, LockTupleMode *lockmode,\n-\t\t\tTU_UpdateIndexes *update_indexes)\n+\t\t\tTransactionId xid, CommandId cid, Snapshot crosscheck,\n+\t\t\tbool wait, TM_FailureData *tmfd, LockTupleMode *lockmode,\n+\t\t\tTU_UpdateIndexes *update_indexes, bool wal_logical)\n {\n \tTM_Result\tresult;\n-\tTransactionId xid = GetCurrentTransactionId();\n \tBitmapset *hot_attrs;\n \tBitmapset *sum_attrs;\n \tBitmapset *key_attrs;\n@@ -3193,6 +3216,7 @@ heap_update(Relation relation, ItemPointer otid, HeapTuple newtup,\n \t\t\t\tinfomask2_new_tuple;\n \n \tAssert(ItemPointerIsValid(otid));\n+\tAssert(TransactionIdIsValid(xid));\n \n \t/* Cheap, simplistic check that the tuple matches the rel's rowtype. */\n \tAssert(HeapTupleHeaderGetNatts(newtup->t_data) <=\n@@ -3981,8 +4005,12 @@ l2:\n \t\t/*\n \t\t * For logical decoding we need combo CIDs to properly decode the\n \t\t * catalog.\n+\t\t *\n+\t\t * Like in heap_insert(), visibility is unchanged when called from\n+\t\t * VACUUM FULL / CLUSTER.\n \t\t */\n-\t\tif (RelationIsAccessibleInLogicalDecoding(relation))\n+\t\tif (wal_logical &&\n+\t\t\tRelationIsAccessibleInLogicalDecoding(relation))\n \t\t{\n \t\t\tlog_heap_new_cid(relation, &oldtup);\n \t\t\tlog_heap_new_cid(relation, heaptup);\n@@ -3992,7 +4020,8 @@ l2:\n \t\t\t\t\t\t\t\t newbuf, &oldtup, heaptup,\n \t\t\t\t\t\t\t\t old_key_tuple,\n \t\t\t\t\t\t\t\t all_visible_cleared,\n-\t\t\t\t\t\t\t\t all_visible_cleared_new);\n+\t\t\t\t\t\t\t\t all_visible_cleared_new,\n+\t\t\t\t\t\t\t\t wal_logical);\n \t\tif (newbuf != buffer)\n \t\t{\n \t\t\tPageSetLSN(BufferGetPage(newbuf), recptr);\n@@ -4225,10 +4254,10 @@ simple_heap_update(Relation relation, ItemPointer otid, HeapTuple tup,\n \tTM_FailureData tmfd;\n \tLockTupleMode lockmode;\n \n-\tresult = heap_update(relation, otid, tup,\n+\tresult = heap_update(relation, otid, tup, GetCurrentTransactionId(),\n \t\t\t\t\t\t GetCurrentCommandId(true), InvalidSnapshot,\n \t\t\t\t\t\t true /* wait for commit */ ,\n-\t\t\t\t\t\t &tmfd, &lockmode, update_indexes);\n+\t\t\t\t\t\t &tmfd, &lockmode, update_indexes, true);\n \tswitch (result)\n \t{\n \t\tcase TM_SelfModified:\n@@ -8357,7 +8386,8 @@ static XLogRecPtr\n log_heap_update(Relation reln, Buffer oldbuf,\n \t\t\t\tBuffer newbuf, HeapTuple oldtup, HeapTuple newtup,\n \t\t\t\tHeapTuple old_key_tuple,\n-\t\t\t\tbool all_visible_cleared, bool new_all_visible_cleared)\n+\t\t\t\tbool all_visible_cleared, bool new_all_visible_cleared,\n+\t\t\t\tbool wal_logical)\n {\n \txl_heap_update xlrec;\n \txl_heap_header xlhdr;\n@@ -8368,10 +8398,12 @@ log_heap_update(Relation reln, Buffer oldbuf,\n \t\t\t\tsuffixlen = 0;\n \tXLogRecPtr\trecptr;\n \tPage\t\tpage = BufferGetPage(newbuf);\n-\tbool\t\tneed_tuple_data = RelationIsLogicallyLogged(reln);\n+\tbool\t\tneed_tuple_data;\n \tbool\t\tinit;\n \tint\t\t\tbufflags;\n \n+\tneed_tuple_data = RelationIsLogicallyLogged(reln) && wal_logical;\n+\n \t/* Caller should not call me on a non-WAL-logged relation */\n \tAssert(RelationNeedsWAL(reln));\n \ndiff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c\nindex 6f8b1b7929..02fd6d2983 100644\n--- a/src/backend/access/heap/heapam_handler.c\n+++ b/src/backend/access/heap/heapam_handler.c\n@@ -33,6 +33,7 @@\n #include \"catalog/index.h\"\n #include \"catalog/storage.h\"\n #include \"catalog/storage_xlog.h\"\n+#include \"commands/cluster.h\"\n #include \"commands/progress.h\"\n #include \"executor/executor.h\"\n #include \"miscadmin.h\"\n@@ -53,6 +54,9 @@ static void reform_and_rewrite_tuple(HeapTuple tuple,\n static bool SampleHeapTupleVisible(TableScanDesc scan, Buffer buffer,\n \t\t\t\t\t\t\t\t HeapTuple tuple,\n \t\t\t\t\t\t\t\t OffsetNumber tupoffset);\n+static bool accept_tuple_for_concurrent_copy(HeapTuple tuple,\n+\t\t\t\t\t\t\t\t\t\t\t Snapshot snapshot,\n+\t\t\t\t\t\t\t\t\t\t\t Buffer buffer);\n \n static BlockNumber heapam_scan_get_blocks_done(HeapScanDesc hscan);\n \n@@ -250,7 +254,8 @@ heapam_tuple_insert(Relation relation, TupleTableSlot *slot, CommandId cid,\n \ttuple->t_tableOid = slot->tts_tableOid;\n \n \t/* Perform the insertion, and copy the resulting ItemPointer */\n-\theap_insert(relation, tuple, cid, options, bistate);\n+\theap_insert(relation, tuple, GetCurrentTransactionId(), cid, options,\n+\t\t\t\tbistate);\n \tItemPointerCopy(&tuple->t_self, &slot->tts_tid);\n \n \tif (shouldFree)\n@@ -273,7 +278,8 @@ heapam_tuple_insert_speculative(Relation relation, TupleTableSlot *slot,\n \toptions |= HEAP_INSERT_SPECULATIVE;\n \n \t/* Perform the insertion, and copy the resulting ItemPointer */\n-\theap_insert(relation, tuple, cid, options, bistate);\n+\theap_insert(relation, tuple, GetCurrentTransactionId(), cid, options,\n+\t\t\t\tbistate);\n \tItemPointerCopy(&tuple->t_self, &slot->tts_tid);\n \n \tif (shouldFree)\n@@ -307,7 +313,8 @@ heapam_tuple_delete(Relation relation, ItemPointer tid, CommandId cid,\n \t * the storage itself is cleaning the dead tuples by itself, it is the\n \t * time to call the index tuple deletion also.\n \t */\n-\treturn heap_delete(relation, tid, cid, crosscheck, wait, tmfd, changingPart);\n+\treturn heap_delete(relation, tid, GetCurrentTransactionId(), cid,\n+\t\t\t\t\t crosscheck, wait, tmfd, changingPart, true);\n }\n \n \n@@ -325,8 +332,9 @@ heapam_tuple_update(Relation relation, ItemPointer otid, TupleTableSlot *slot,\n \tslot->tts_tableOid = RelationGetRelid(relation);\n \ttuple->t_tableOid = slot->tts_tableOid;\n \n-\tresult = heap_update(relation, otid, tuple, cid, crosscheck, wait,\n-\t\t\t\t\t\t tmfd, lockmode, update_indexes);\n+\tresult = heap_update(relation, otid, tuple, GetCurrentTransactionId(),\n+\t\t\t\t\t\t cid, crosscheck, wait,\n+\t\t\t\t\t\t tmfd, lockmode, update_indexes, true);\n \tItemPointerCopy(&tuple->t_self, &slot->tts_tid);\n \n \t/*\n@@ -686,6 +694,8 @@ static void\n heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,\n \t\t\t\t\t\t\t\t Relation OldIndex, bool use_sort,\n \t\t\t\t\t\t\t\t TransactionId OldestXmin,\n+\t\t\t\t\t\t\t\t Snapshot snapshot,\n+\t\t\t\t\t\t\t\t LogicalDecodingContext *decoding_ctx,\n \t\t\t\t\t\t\t\t TransactionId *xid_cutoff,\n \t\t\t\t\t\t\t\t MultiXactId *multi_cutoff,\n \t\t\t\t\t\t\t\t double *num_tuples,\n@@ -706,6 +716,8 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,\n \tbool\t *isnull;\n \tBufferHeapTupleTableSlot *hslot;\n \tBlockNumber prev_cblock = InvalidBlockNumber;\n+\tbool\tconcurrent = snapshot != NULL;\n+\tXLogRecPtr\tend_of_wal_prev = GetFlushRecPtr(NULL);\n \n \t/* Remember if it's a system catalog */\n \tis_system_catalog = IsSystemRelation(OldHeap);\n@@ -786,6 +798,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,\n \t\tHeapTuple\ttuple;\n \t\tBuffer\t\tbuf;\n \t\tbool\t\tisdead;\n+\t\tHTSV_Result\tvis;\n \n \t\tCHECK_FOR_INTERRUPTS();\n \n@@ -840,7 +853,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,\n \n \t\tLockBuffer(buf, BUFFER_LOCK_SHARE);\n \n-\t\tswitch (HeapTupleSatisfiesVacuum(tuple, OldestXmin, buf))\n+\t\tswitch ((vis = HeapTupleSatisfiesVacuum(tuple, OldestXmin, buf)))\n \t\t{\n \t\t\tcase HEAPTUPLE_DEAD:\n \t\t\t\t/* Definitely dead */\n@@ -856,14 +869,15 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,\n \t\t\tcase HEAPTUPLE_INSERT_IN_PROGRESS:\n \n \t\t\t\t/*\n-\t\t\t\t * Since we hold exclusive lock on the relation, normally the\n-\t\t\t\t * only way to see this is if it was inserted earlier in our\n-\t\t\t\t * own transaction. However, it can happen in system\n+\t\t\t\t * As long as we hold exclusive lock on the relation, normally\n+\t\t\t\t * the only way to see this is if it was inserted earlier in\n+\t\t\t\t * our own transaction. However, it can happen in system\n \t\t\t\t * catalogs, since we tend to release write lock before commit\n-\t\t\t\t * there. Give a warning if neither case applies; but in any\n-\t\t\t\t * case we had better copy it.\n+\t\t\t\t * there. Also, there's no exclusive lock during concurrent\n+\t\t\t\t * processing. Give a warning if neither case applies; but in\n+\t\t\t\t * any case we had better copy it.\n \t\t\t\t */\n-\t\t\t\tif (!is_system_catalog &&\n+\t\t\t\tif (!is_system_catalog && !concurrent &&\n \t\t\t\t\t!TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(tuple->t_data)))\n \t\t\t\t\telog(WARNING, \"concurrent insert in progress within table \\\"%s\\\"\",\n \t\t\t\t\t\t RelationGetRelationName(OldHeap));\n@@ -875,7 +889,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,\n \t\t\t\t/*\n \t\t\t\t * Similar situation to INSERT_IN_PROGRESS case.\n \t\t\t\t */\n-\t\t\t\tif (!is_system_catalog &&\n+\t\t\t\tif (!is_system_catalog && !concurrent &&\n \t\t\t\t\t!TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetUpdateXid(tuple->t_data)))\n \t\t\t\t\telog(WARNING, \"concurrent delete in progress within table \\\"%s\\\"\",\n \t\t\t\t\t\t RelationGetRelationName(OldHeap));\n@@ -889,8 +903,6 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,\n \t\t\t\tbreak;\n \t\t}\n \n-\t\tLockBuffer(buf, BUFFER_LOCK_UNLOCK);\n-\n \t\tif (isdead)\n \t\t{\n \t\t\t*tups_vacuumed += 1;\n@@ -901,9 +913,39 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,\n \t\t\t\t*tups_vacuumed += 1;\n \t\t\t\t*tups_recently_dead -= 1;\n \t\t\t}\n+\n+\t\t\tLockBuffer(buf, BUFFER_LOCK_UNLOCK);\n \t\t\tcontinue;\n \t\t}\n \n+\t\t/*\n+\t\t * Ignore concurrent changes now, they'll be processed later via\n+\t\t * logical decoding. INSERT_IN_PROGRESS is rejected right away because\n+\t\t * our snapshot should represent a point in time which should precede\n+\t\t * (or be equal to) the state of transactions as it was when the\n+\t\t * \"SatisfiesVacuum\" test was performed. Thus\n+\t\t * accept_tuple_for_concurrent_copy() should not consider the tuple\n+\t\t * inserted.\n+\t\t */\n+\t\tif (concurrent &&\n+\t\t\t(vis == HEAPTUPLE_INSERT_IN_PROGRESS ||\n+\t\t\t !accept_tuple_for_concurrent_copy(tuple, snapshot, buf)))\n+\t\t{\n+\t\t\tLockBuffer(buf, BUFFER_LOCK_UNLOCK);\n+\t\t\tcontinue;\n+\t\t}\n+\n+\t\t/*\n+\t\t * In the concurrent case, we should not unlock the buffer until the\n+\t\t * tuple has been copied to the new file: if a concurrent transaction\n+\t\t * marked it updated or deleted in between, we'd fail to replay that\n+\t\t * transaction's changes because then we'd try to perform the same\n+\t\t * UPDATE / DELETE twice. XXX Should we instead create a copy of the\n+\t\t * tuple so that the buffer can be unlocked right away?\n+\t\t */\n+\t\tif (!concurrent)\n+\t\t\tLockBuffer(buf, BUFFER_LOCK_UNLOCK);\n+\n \t\t*num_tuples += 1;\n \t\tif (tuplesort != NULL)\n \t\t{\n@@ -920,7 +962,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,\n \t\t{\n \t\t\tconst int\tct_index[] = {\n \t\t\t\tPROGRESS_CLUSTER_HEAP_TUPLES_SCANNED,\n-\t\t\t\tPROGRESS_CLUSTER_HEAP_TUPLES_WRITTEN\n+\t\t\t\tPROGRESS_CLUSTER_HEAP_TUPLES_INSERTED\n \t\t\t};\n \t\t\tint64\t\tct_val[2];\n \n@@ -935,6 +977,35 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,\n \t\t\tct_val[1] = *num_tuples;\n \t\t\tpgstat_progress_update_multi_param(2, ct_index, ct_val);\n \t\t}\n+\n+\t\t/* See the comment on unlocking above. */\n+\t\tif (concurrent)\n+\t\t\tLockBuffer(buf, BUFFER_LOCK_UNLOCK);\n+\n+\t\t/*\n+\t\t * Process the WAL produced by the load, as well as by other\n+\t\t * transactions, so that the replication slot can advance and WAL does\n+\t\t * not pile up. Use wal_segment_size as a threshold so that we do not\n+\t\t * introduce the decoding overhead too often.\n+\t\t *\n+\t\t * Of course, we must not apply the changes until the initial load has\n+\t\t * completed.\n+\t\t *\n+\t\t * Note that our insertions into the new table should not be decoded\n+\t\t * as we (intentionally) do not write the logical decoding specific\n+\t\t * information to WAL.\n+\t\t */\n+\t\tif (concurrent)\n+\t\t{\n+\t\t\tXLogRecPtr\tend_of_wal;\n+\n+\t\t\tend_of_wal = GetFlushRecPtr(NULL);\n+\t\t\tif ((end_of_wal - end_of_wal_prev) > wal_segment_size)\n+\t\t\t{\n+\t\t\t\tcluster_decode_concurrent_changes(decoding_ctx, end_of_wal);\n+\t\t\t\tend_of_wal_prev = end_of_wal;\n+\t\t\t}\n+\t\t}\n \t}\n \n \tif (indexScan != NULL)\n@@ -978,7 +1049,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,\n \t\t\t\t\t\t\t\t\t values, isnull,\n \t\t\t\t\t\t\t\t\t rwstate);\n \t\t\t/* Report n_tuples */\n-\t\t\tpgstat_progress_update_param(PROGRESS_CLUSTER_HEAP_TUPLES_WRITTEN,\n+\t\t\tpgstat_progress_update_param(PROGRESS_CLUSTER_HEAP_TUPLES_INSERTED,\n \t\t\t\t\t\t\t\t\t\t n_tuples);\n \t\t}\n \n@@ -2583,6 +2654,56 @@ SampleHeapTupleVisible(TableScanDesc scan, Buffer buffer,\n \t}\n }\n \n+/*\n+ * Check if the tuple was inserted, updated or deleted while\n+ * heapam_relation_copy_for_cluster() was copying the data.\n+ *\n+ * 'snapshot' is used to determine whether xmin/xmax was set by a transaction\n+ * that is still in-progress, or one that started in the future from the\n+ * snapshot perspective.\n+ *\n+ * Returns true if the insertion is visible to 'snapshot', but clear xmax if\n+ * it was set by a transaction which is in-progress or in the future from the\n+ * snapshot perspective. (The xmax will be set later, when we decode the\n+ * corresponding UPDATE / DELETE from WAL.)\n+ *\n+ * Returns false if the insertion is not visible to 'snapshot'.\n+ */\n+static bool\n+accept_tuple_for_concurrent_copy(HeapTuple tuple, Snapshot snapshot,\n+\t\t\t\t\t\t\t\t Buffer buffer)\n+{\n+\tAssert(snapshot->snapshot_type == SNAPSHOT_MVCC);\n+\n+\t/*\n+\t * First, check if the tuple should be rejected because it was inserted\n+\t * concurrently.\n+\t */\n+\tif (!HeapTupleMVCCInserted(tuple, snapshot, buffer))\n+\t\treturn false;\n+\n+\t/*\n+\t * If the tuple was deleted / updated but our snapshot still sees it, we\n+\t * need to keep it. In that case, clear the information that indicates the\n+\t * deletion / update. Otherwise the tuple chain would stay incomplete (as\n+\t * we will reject the new tuple above), and the delete / update would fail\n+\t * if executed later during logical decoding.\n+\t */\n+\tif (TransactionIdIsNormal(HeapTupleHeaderGetRawXmax(tuple->t_data)) &&\n+\t\tHeapTupleMVCCNotDeleted(tuple, snapshot, buffer))\n+\t{\n+\t\t/* TODO More work needed here?*/\n+\t\ttuple->t_data->t_infomask |= HEAP_XMAX_INVALID;\n+\t\tHeapTupleHeaderSetXmax(tuple->t_data, 0);\n+\t}\n+\n+\t/*\n+\t * Accept the tuple even if our snapshot considers it deleted - older\n+\t * snapshots can still see the tuple.\n+\t */\n+\treturn true;\n+}\n+\n \n /* ------------------------------------------------------------------------\n * Definition of the heap table access method.\ndiff --git a/src/backend/access/heap/heapam_visibility.c b/src/backend/access/heap/heapam_visibility.c\nindex 9243feed01..d702592469 100644\n--- a/src/backend/access/heap/heapam_visibility.c\n+++ b/src/backend/access/heap/heapam_visibility.c\n@@ -955,16 +955,31 @@ HeapTupleSatisfiesDirty(HeapTuple htup, Snapshot snapshot,\n * did TransactionIdIsInProgress in each call --- to no avail, as long as the\n * inserting/deleting transaction was still running --- which was more cycles\n * and more contention on ProcArrayLock.\n+ *\n+ * The checks are split into two functions, HeapTupleMVCCInserted() and\n+ * HeapTupleMVCCNotDeleted(), because they are also useful separately.\n */\n static bool\n HeapTupleSatisfiesMVCC(HeapTuple htup, Snapshot snapshot,\n \t\t\t\t\t Buffer buffer)\n {\n-\tHeapTupleHeader tuple = htup->t_data;\n-\n \tAssert(ItemPointerIsValid(&htup->t_self));\n \tAssert(htup->t_tableOid != InvalidOid);\n \n+\treturn HeapTupleMVCCInserted(htup, snapshot, buffer) &&\n+\t\tHeapTupleMVCCNotDeleted(htup, snapshot, buffer);\n+}\n+\n+/*\n+ * HeapTupleMVCCInserted\n+ *\t\tTrue iff heap tuple was successfully inserted for the given MVCC\n+ *\t\tsnapshot.\n+ */\n+bool\n+HeapTupleMVCCInserted(HeapTuple htup, Snapshot snapshot, Buffer buffer)\n+{\n+\tHeapTupleHeader tuple = htup->t_data;\n+\n \tif (!HeapTupleHeaderXminCommitted(tuple))\n \t{\n \t\tif (HeapTupleHeaderXminInvalid(tuple))\n@@ -1073,6 +1088,17 @@ HeapTupleSatisfiesMVCC(HeapTuple htup, Snapshot snapshot,\n \t}\n \n \t/* by here, the inserting transaction has committed */\n+\treturn true;\n+}\n+\n+/*\n+ * HeapTupleMVCCNotDeleted\n+ *\t\tTrue iff heap tuple was not deleted for the given MVCC snapshot.\n+ */\n+bool\n+HeapTupleMVCCNotDeleted(HeapTuple htup, Snapshot snapshot, Buffer buffer)\n+{\n+\tHeapTupleHeader tuple = htup->t_data;\n \n \tif (tuple->t_infomask & HEAP_XMAX_INVALID)\t/* xid invalid or aborted */\n \t\treturn true;\ndiff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam/xact.c\nindex d119ab909d..f9b8cb4da7 100644\n--- a/src/backend/access/transam/xact.c\n+++ b/src/backend/access/transam/xact.c\n@@ -124,6 +124,18 @@ static FullTransactionId XactTopFullTransactionId = {InvalidTransactionId};\n static int\tnParallelCurrentXids = 0;\n static TransactionId *ParallelCurrentXids;\n \n+/*\n+ * Another case that requires TransactionIdIsCurrentTransactionId() to behave\n+ * specially is when CLUSTER CONCURRENTLY is processing data changes made in\n+ * the old storage of a table by other transactions. When applying the changes\n+ * to the new storage, the backend executing the CLUSTER command needs to act\n+ * on behalf on those other transactions. The transactions responsible for the\n+ * changes in the old storage are stored in this array, sorted by\n+ * xidComparator.\n+ */\n+static int\t\t\t\t nClusterCurrentXids = 0;\n+static TransactionId\t*ClusterCurrentXids = NULL;\n+\n /*\n * Miscellaneous flag bits to record events which occur on the top level\n * transaction. These flags are only persisted in MyXactFlags and are intended\n@@ -970,6 +982,8 @@ TransactionIdIsCurrentTransactionId(TransactionId xid)\n \t\tint\t\t\tlow,\n \t\t\t\t\thigh;\n \n+\t\tAssert(nClusterCurrentXids == 0);\n+\n \t\tlow = 0;\n \t\thigh = nParallelCurrentXids - 1;\n \t\twhile (low <= high)\n@@ -989,6 +1003,21 @@ TransactionIdIsCurrentTransactionId(TransactionId xid)\n \t\treturn false;\n \t}\n \n+\t/*\n+\t * When executing CLUSTER CONCURRENTLY, the array of current transactions\n+\t * is given.\n+\t */\n+\tif (nClusterCurrentXids > 0)\n+\t{\n+\t\tAssert(nParallelCurrentXids == 0);\n+\n+\t\treturn bsearch(&xid,\n+\t\t\t\t\t ClusterCurrentXids,\n+\t\t\t\t\t nClusterCurrentXids,\n+\t\t\t\t\t sizeof(TransactionId),\n+\t\t\t\t\t xidComparator) != NULL;\n+\t}\n+\n \t/*\n \t * We will return true for the Xid of the current subtransaction, any of\n \t * its subcommitted children, any of its parents, or any of their\n@@ -5621,6 +5650,29 @@ EndParallelWorkerTransaction(void)\n \tCurrentTransactionState->blockState = TBLOCK_DEFAULT;\n }\n \n+/*\n+ * SetClusterCurrentXids\n+ *\t\tSet the XID array that TransactionIdIsCurrentTransactionId() should\n+ *\t\tuse.\n+ */\n+void\n+SetClusterCurrentXids(TransactionId *xip, int xcnt)\n+{\n+\tClusterCurrentXids = xip;\n+\tnClusterCurrentXids = xcnt;\n+}\n+\n+/*\n+ * ResetClusterCurrentXids\n+ *\t\tUndo the effect of SetClusterCurrentXids().\n+ */\n+void\n+ResetClusterCurrentXids(void)\n+{\n+\tClusterCurrentXids = NULL;\n+\tnClusterCurrentXids = 0;\n+}\n+\n /*\n * ShowTransactionState\n *\t\tDebug support\ndiff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c\nindex a819b4197c..a25c84d7ae 100644\n--- a/src/backend/catalog/index.c\n+++ b/src/backend/catalog/index.c\n@@ -1415,22 +1415,7 @@ index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId,\n \tfor (int i = 0; i < newInfo->ii_NumIndexAttrs; i++)\n \t\topclassOptions[i] = get_attoptions(oldIndexId, i + 1);\n \n-\t/* Extract statistic targets for each attribute */\n-\tstattargets = palloc0_array(NullableDatum, newInfo->ii_NumIndexAttrs);\n-\tfor (int i = 0; i < newInfo->ii_NumIndexAttrs; i++)\n-\t{\n-\t\tHeapTuple\ttp;\n-\t\tDatum\t\tdat;\n-\n-\t\ttp = SearchSysCache2(ATTNUM, ObjectIdGetDatum(oldIndexId), Int16GetDatum(i + 1));\n-\t\tif (!HeapTupleIsValid(tp))\n-\t\t\telog(ERROR, \"cache lookup failed for attribute %d of relation %u\",\n-\t\t\t\t i + 1, oldIndexId);\n-\t\tdat = SysCacheGetAttr(ATTNUM, tp, Anum_pg_attribute_attstattarget, &isnull);\n-\t\tReleaseSysCache(tp);\n-\t\tstattargets[i].value = dat;\n-\t\tstattargets[i].isnull = isnull;\n-\t}\n+\tstattargets = get_index_stattargets(oldIndexId, newInfo);\n \n \t/*\n \t * Now create the new index.\n@@ -1469,6 +1454,32 @@ index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId,\n \treturn newIndexId;\n }\n \n+NullableDatum *\n+get_index_stattargets(Oid indexid, IndexInfo *indInfo)\n+{\n+\tNullableDatum *stattargets;\n+\n+\t/* Extract statistic targets for each attribute */\n+\tstattargets = palloc0_array(NullableDatum, indInfo->ii_NumIndexAttrs);\n+\tfor (int i = 0; i < indInfo->ii_NumIndexAttrs; i++)\n+\t{\n+\t\tHeapTuple\ttp;\n+\t\tDatum\t\tdat;\n+\t\tbool\t\tisnull;\n+\n+\t\ttp = SearchSysCache2(ATTNUM, ObjectIdGetDatum(indexid), Int16GetDatum(i + 1));\n+\t\tif (!HeapTupleIsValid(tp))\n+\t\t\telog(ERROR, \"cache lookup failed for attribute %d of relation %u\",\n+\t\t\t\t i + 1, indexid);\n+\t\tdat = SysCacheGetAttr(ATTNUM, tp, Anum_pg_attribute_attstattarget, &isnull);\n+\t\tReleaseSysCache(tp);\n+\t\tstattargets[i].value = dat;\n+\t\tstattargets[i].isnull = isnull;\n+\t}\n+\n+\treturn stattargets;\n+}\n+\n /*\n * index_concurrently_build\n *\ndiff --git a/src/backend/catalog/system_views.sql b/src/backend/catalog/system_views.sql\nindex 19cabc9a47..fddab1cfa9 100644\n--- a/src/backend/catalog/system_views.sql\n+++ b/src/backend/catalog/system_views.sql\n@@ -1236,16 +1236,19 @@ CREATE VIEW pg_stat_progress_cluster AS\n WHEN 2 THEN 'index scanning heap'\n WHEN 3 THEN 'sorting tuples'\n WHEN 4 THEN 'writing new heap'\n- WHEN 5 THEN 'swapping relation files'\n- WHEN 6 THEN 'rebuilding index'\n- WHEN 7 THEN 'performing final cleanup'\n+ WHEN 5 THEN 'catch-up'\n+ WHEN 6 THEN 'swapping relation files'\n+ WHEN 7 THEN 'rebuilding index'\n+ WHEN 8 THEN 'performing final cleanup'\n END AS phase,\n CAST(S.param3 AS oid) AS cluster_index_relid,\n S.param4 AS heap_tuples_scanned,\n- S.param5 AS heap_tuples_written,\n- S.param6 AS heap_blks_total,\n- S.param7 AS heap_blks_scanned,\n- S.param8 AS index_rebuild_count\n+ S.param5 AS heap_tuples_inserted,\n+ S.param6 AS heap_tuples_updated,\n+ S.param7 AS heap_tuples_deleted,\n+ S.param8 AS heap_blks_total,\n+ S.param9 AS heap_blks_scanned,\n+ S.param10 AS index_rebuild_count\n FROM pg_stat_get_progress_info('CLUSTER') AS S\n LEFT JOIN pg_database D ON S.datid = D.oid;\n \ndiff --git a/src/backend/commands/cluster.c b/src/backend/commands/cluster.c\nindex 194d143cf4..6397f7f8c4 100644\n--- a/src/backend/commands/cluster.c\n+++ b/src/backend/commands/cluster.c\n@@ -25,6 +25,10 @@\n #include \"access/toast_internals.h\"\n #include \"access/transam.h\"\n #include \"access/xact.h\"\n+#include \"access/xlog.h\"\n+#include \"access/xlog_internal.h\"\n+#include \"access/xloginsert.h\"\n+#include \"access/xlogutils.h\"\n #include \"catalog/catalog.h\"\n #include \"catalog/dependency.h\"\n #include \"catalog/heap.h\"\n@@ -32,6 +36,7 @@\n #include \"catalog/namespace.h\"\n #include \"catalog/objectaccess.h\"\n #include \"catalog/pg_am.h\"\n+#include \"catalog/pg_control.h\"\n #include \"catalog/pg_database.h\"\n #include \"catalog/pg_inherits.h\"\n #include \"catalog/toasting.h\"\n@@ -40,10 +45,15 @@\n #include \"commands/progress.h\"\n #include \"commands/tablecmds.h\"\n #include \"commands/vacuum.h\"\n+#include \"executor/executor.h\"\n #include \"miscadmin.h\"\n #include \"optimizer/optimizer.h\"\n #include \"pgstat.h\"\n+#include \"replication/decode.h\"\n+#include \"replication/logical.h\"\n+#include \"replication/snapbuild.h\"\n #include \"storage/bufmgr.h\"\n+#include \"storage/ipc.h\"\n #include \"storage/lmgr.h\"\n #include \"storage/predicate.h\"\n #include \"utils/acl.h\"\n@@ -57,6 +67,8 @@\n #include \"utils/snapmgr.h\"\n #include \"utils/syscache.h\"\n \n+typedef struct RewriteStateData *RewriteState;\n+\n /*\n * This struct is used to pass around the information on tables to be\n * clustered. We need this so we can make a list of them when invoked without\n@@ -68,17 +80,175 @@ typedef struct\n \tOid\t\t\tindexOid;\n } RelToCluster;\n \n+/*\n+ * The following definitions are used for concurrent processing.\n+ */\n+\n+/*\n+ * OID of the table being processed by CLUSTER CONCURRENTLY by this backend.\n+ */\n+static Oid\tclustered_rel\t= InvalidOid;\n+/* The same for its TOAST relation. */\n+static Oid\tclustered_rel_toast\t= InvalidOid;\n+\n+/* XXX Do we also need to mention VACUUM FULL CONCURRENTLY? */\n+#define CLUSTER_IN_PROGRESS_MESSAGE \\\n+\t\"relation \\\"%s\\\" is already being processed by CLUSTER CONCURRENTLY\"\n+\n+/*\n+ * Everything we need to call ExecInsertIndexTuples().\n+ */\n+typedef struct IndexInsertState\n+{\n+\tResultRelInfo *rri;\n+\tEState\t *estate;\n+\tExprContext *econtext;\n+\n+\tRelation\tident_index;\n+} IndexInsertState;\n \n-static void cluster_multiple_rels(List *rtcs, ClusterParams *params);\n-static void rebuild_relation(Relation OldHeap, Relation index, bool verbose);\n+/*\n+ * Catalog information to check if another backend changed the relation in\n+ * such a way that makes CLUSTER CONCURRENTLY unable to continue. Such changes\n+ * are possible because cluster_rel() has to release its lock on the relation\n+ * in order to acquire AccessExclusiveLock that it needs to swap the relation\n+ * files.\n+ *\n+ * The most obvious problem is that the tuple descriptor has changed, since\n+ * then the tuples we try to insert into the new storage are not guaranteed to\n+ * fit into the storage.\n+ *\n+ * Another problem is that multiple backends might call cluster_rel(). This is\n+ * not necessarily a correctness issue, but it definitely means wasted CPU\n+ * time.\n+ *\n+ * Where possible, commands which might change the relation in an incompatible\n+ * way should check if CLUSTER CONCURRENTLY is running, before they start to\n+ * do the actual changes (see is_concurrent_cluster_in_progress()). Anything\n+ * else must be caught by check_catalog_changes(), which uses this structure.\n+ */\n+typedef struct CatalogState\n+{\n+\t/* Tuple descriptor of the relation. */\n+\tTupleDesc\ttupdesc;\n+\n+\t/* The number of indexes tracked. */\n+\tint\t\tninds;\n+\t/* The index OIDs. */\n+\tOid\t\t*ind_oids;\n+\t/* The index tuple descriptors. */\n+\tTupleDesc\t*ind_tupdescs;\n+\n+\t/* The following are copies of the corresponding fields of pg_class. */\n+\tOid\t\treltoastrelid;\n+\tchar\trelpersistence;\n+\tchar\treplident;\n+\n+\t/* rd_replidindex */\n+\tOid\t\treplidindex;\n+} CatalogState;\n+\n+/* The WAL segment being decoded. */\n+static XLogSegNo\tcluster_current_segment = 0;\n+\n+static void cluster_multiple_rels(List *rtcs, ClusterParams *params,\n+\t\t\t\t\t\t\t\t LOCKMODE lock_mode, bool isTopLevel);\n+static void rebuild_relation(Relation OldHeap, Relation index, bool verbose,\n+\t\t\t\t\t\t\t bool concurrent);\n static void copy_table_data(Relation NewHeap, Relation OldHeap, Relation OldIndex,\n+\t\t\t\t\t\t\tSnapshot snapshot, LogicalDecodingContext *decoding_ctx,\n \t\t\t\t\t\t\tbool verbose, bool *pSwapToastByContent,\n \t\t\t\t\t\t\tTransactionId *pFreezeXid, MultiXactId *pCutoffMulti);\n static List *get_tables_to_cluster(MemoryContext cluster_context);\n static List *get_tables_to_cluster_partitioned(MemoryContext cluster_context,\n \t\t\t\t\t\t\t\t\t\t\t Oid indexOid);\n static bool cluster_is_permitted_for_relation(Oid relid, Oid userid);\n+static void check_concurrent_cluster_requirements(Relation rel,\n+\t\t\t\t\t\t\t\t\t\t\t\t bool isTopLevel,\n+\t\t\t\t\t\t\t\t\t\t\t\t bool isCluster);\n+static void begin_concurrent_cluster(Relation *rel_p, Relation *index_p,\n+\t\t\t\t\t\t\t\t\t bool *entered_p);\n+static void end_concurrent_cluster(Oid relid, bool error);\n+static void cluster_before_shmem_exit_callback(int code, Datum arg);\n+static CatalogState *get_catalog_state(Relation rel);\n+static void free_catalog_state(CatalogState *state);\n+static void check_catalog_changes(Relation rel, CatalogState *cat_state);\n+static LogicalDecodingContext *setup_logical_decoding(Oid relid,\n+\t\t\t\t\t\t\t\t\t\t\t\t\t const char *slotname,\n+\t\t\t\t\t\t\t\t\t\t\t\t\t TupleDesc tupdesc);\n+static HeapTuple get_changed_tuple(ConcurrentChange *change);\n+static void apply_concurrent_changes(ClusterDecodingState *dstate,\n+\t\t\t\t\t\t\t\t\t Relation rel, ScanKey key, int nkeys,\n+\t\t\t\t\t\t\t\t\t IndexInsertState *iistate);\n+static void apply_concurrent_insert(Relation rel, ConcurrentChange *change,\n+\t\t\t\t\t\t\t\t\tHeapTuple tup, IndexInsertState *iistate,\n+\t\t\t\t\t\t\t\t\tTupleTableSlot *index_slot);\n+static void apply_concurrent_update(Relation rel, HeapTuple tup,\n+\t\t\t\t\t\t\t\t\tHeapTuple tup_target,\n+\t\t\t\t\t\t\t\t\tConcurrentChange *change,\n+\t\t\t\t\t\t\t\t\tIndexInsertState *iistate,\n+\t\t\t\t\t\t\t\t\tTupleTableSlot *index_slot);\n+static void apply_concurrent_delete(Relation rel, HeapTuple tup_target,\n+\t\t\t\t\t\t\t\t\tConcurrentChange *change);\n+static HeapTuple find_target_tuple(Relation rel, ScanKey key, int nkeys,\n+\t\t\t\t\t\t\t\t HeapTuple tup_key,\n+\t\t\t\t\t\t\t\t Snapshot snapshot,\n+\t\t\t\t\t\t\t\t IndexInsertState *iistate,\n+\t\t\t\t\t\t\t\t TupleTableSlot *ident_slot,\n+\t\t\t\t\t\t\t\t IndexScanDesc *scan_p);\n+static void process_concurrent_changes(LogicalDecodingContext *ctx,\n+\t\t\t\t\t\t\t\t\t XLogRecPtr end_of_wal,\n+\t\t\t\t\t\t\t\t\t Relation rel_dst,\n+\t\t\t\t\t\t\t\t\t Relation rel_src,\n+\t\t\t\t\t\t\t\t\t ScanKey ident_key,\n+\t\t\t\t\t\t\t\t\t int ident_key_nentries,\n+\t\t\t\t\t\t\t\t\t IndexInsertState *iistate);\n+static IndexInsertState *get_index_insert_state(Relation relation,\n+\t\t\t\t\t\t\t\t\t\t\t\tOid ident_index_id);\n+static ScanKey build_identity_key(Oid ident_idx_oid, Relation rel_src,\n+\t\t\t\t\t\t\t\t int *nentries);\n+static void free_index_insert_state(IndexInsertState *iistate);\n+static void cleanup_logical_decoding(LogicalDecodingContext *ctx);\n+static void rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,\n+\t\t\t\t\t\t\t\t\t\t\t Relation cl_index,\n+\t\t\t\t\t\t\t\t\t\t\t CatalogState\t*cat_state,\n+\t\t\t\t\t\t\t\t\t\t\t LogicalDecodingContext *ctx,\n+\t\t\t\t\t\t\t\t\t\t\t bool swap_toast_by_content,\n+\t\t\t\t\t\t\t\t\t\t\t TransactionId frozenXid,\n+\t\t\t\t\t\t\t\t\t\t\t MultiXactId cutoffMulti);\n+static List *build_new_indexes(Relation NewHeap, Relation OldHeap, List *OldIndexes);\n+\n+/*\n+ * Use this API when relation needs to be unlocked, closed and re-opened. If\n+ * the relation got dropped while being unlocked, raise ERROR that mentions\n+ * the relation name rather than OID.\n+ */\n+typedef struct RelReopenInfo\n+{\n+\t/*\n+\t * The relation to be closed. Pointer to the value is stored here so that\n+\t * the user gets his reference updated automatically on re-opening.\n+\t *\n+\t * When calling unlock_and_close_relations(), 'relid' can be passed\n+\t * instead of 'rel_p' when the caller only needs to gather information for\n+\t * subsequent opening.\n+\t */\n+\tRelation\t*rel_p;\n+\tOid\t\trelid;\n+\n+\tchar\t\trelkind;\n+\tLOCKMODE\tlockmode_orig;\t/* The existing lock mode */\n+\tLOCKMODE\tlockmode_new;\t/* The lock mode after the relation is\n+\t\t\t\t\t\t\t\t * re-opened */\n \n+\tchar\t*relname;\t\t\t/* Relation name, initialized automatically. */\n+} RelReopenInfo;\n+\n+static void init_rel_reopen_info(RelReopenInfo *rri, Relation *rel_p,\n+\t\t\t\t\t\t\t\t Oid relid, LOCKMODE lockmode_orig,\n+\t\t\t\t\t\t\t\t LOCKMODE lockmode_new);\n+static void unlock_and_close_relations(RelReopenInfo *rels, int nrel);\n+static void reopen_relations(RelReopenInfo *rels, int nrel);\n \n /*---------------------------------------------------------------------------\n * This cluster code allows for clustering multiple tables at once. Because\n@@ -110,10 +280,12 @@ cluster(ParseState *pstate, ClusterStmt *stmt, bool isTopLevel)\n \tListCell *lc;\n \tClusterParams params = {0};\n \tbool\t\tverbose = false;\n+\tbool\t\tconcurrent = false;\n \tRelation\trel = NULL;\n \tOid\t\t\tindexOid = InvalidOid;\n \tMemoryContext cluster_context;\n \tList\t *rtcs;\n+\tLOCKMODE lock_mode;\n \n \t/* Parse option list */\n \tforeach(lc, stmt->params)\n@@ -122,6 +294,8 @@ cluster(ParseState *pstate, ClusterStmt *stmt, bool isTopLevel)\n \n \t\tif (strcmp(opt->defname, \"verbose\") == 0)\n \t\t\tverbose = defGetBoolean(opt);\n+\t\telse if (strcmp(opt->defname, \"concurrently\") == 0)\n+\t\t\tconcurrent = defGetBoolean(opt);\n \t\telse\n \t\t\tereport(ERROR,\n \t\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n@@ -130,20 +304,30 @@ cluster(ParseState *pstate, ClusterStmt *stmt, bool isTopLevel)\n \t\t\t\t\t parser_errposition(pstate, opt->location)));\n \t}\n \n-\tparams.options = (verbose ? CLUOPT_VERBOSE : 0);\n+\tparams.options =\n+\t\t(verbose ? CLUOPT_VERBOSE : 0) |\n+\t\t(concurrent ? CLUOPT_CONCURRENT : 0);\n+\n+\t/*\n+\t * Determine the lock mode expected by cluster_rel().\n+\t *\n+\t * In the exclusive case, we obtain AccessExclusiveLock right away to\n+\t * avoid lock-upgrade hazard in the single-transaction case. In the\n+\t * CONCURRENT case, the AccessExclusiveLock will only be used at the end\n+\t * of processing, supposedly for very short time. Until then, we'll have\n+\t * to unlock the relation temporarily, so there's no lock-upgrade hazard.\n+\t */\n+\tlock_mode = (params.options & CLUOPT_CONCURRENT) == 0 ?\n+\t\tAccessExclusiveLock : LOCK_CLUSTER_CONCURRENT;\n \n \tif (stmt->relation != NULL)\n \t{\n \t\t/* This is the single-relation case. */\n \t\tOid\t\t\ttableOid;\n \n-\t\t/*\n-\t\t * Find, lock, and check permissions on the table. We obtain\n-\t\t * AccessExclusiveLock right away to avoid lock-upgrade hazard in the\n-\t\t * single-transaction case.\n-\t\t */\n+\t\t/* Find, lock, and check permissions on the table. */\n \t\ttableOid = RangeVarGetRelidExtended(stmt->relation,\n-\t\t\t\t\t\t\t\t\t\t\tAccessExclusiveLock,\n+\t\t\t\t\t\t\t\t\t\t\tlock_mode,\n \t\t\t\t\t\t\t\t\t\t\t0,\n \t\t\t\t\t\t\t\t\t\t\tRangeVarCallbackMaintainsTable,\n \t\t\t\t\t\t\t\t\t\t\tNULL);\n@@ -198,7 +382,7 @@ cluster(ParseState *pstate, ClusterStmt *stmt, bool isTopLevel)\n \t\t\t * Do the job. (The function will close the relation, lock is kept\n \t\t\t * till commit.)\n \t\t\t */\n-\t\t\tcluster_rel(rel, indexOid, ¶ms);\n+\t\t\tcluster_rel(rel, indexOid, ¶ms, isTopLevel);\n \n \t\t\treturn;\n \t\t}\n@@ -237,7 +421,7 @@ cluster(ParseState *pstate, ClusterStmt *stmt, bool isTopLevel)\n \t\trtcs = get_tables_to_cluster_partitioned(cluster_context, indexOid);\n \n \t\t/* close relation, releasing lock on parent table */\n-\t\ttable_close(rel, AccessExclusiveLock);\n+\t\ttable_close(rel, lock_mode);\n \t}\n \telse\n \t{\n@@ -246,7 +430,7 @@ cluster(ParseState *pstate, ClusterStmt *stmt, bool isTopLevel)\n \t}\n \n \t/* Do the job. */\n-\tcluster_multiple_rels(rtcs, ¶ms);\n+\tcluster_multiple_rels(rtcs, ¶ms, lock_mode, isTopLevel);\n \n \t/* Start a new transaction for the cleanup work. */\n \tStartTransactionCommand();\n@@ -263,7 +447,8 @@ cluster(ParseState *pstate, ClusterStmt *stmt, bool isTopLevel)\n * return.\n */\n static void\n-cluster_multiple_rels(List *rtcs, ClusterParams *params)\n+cluster_multiple_rels(List *rtcs, ClusterParams *params, LOCKMODE lock_mode,\n+\t\t\t\t\t bool isTopLevel)\n {\n \tListCell *lc;\n \n@@ -283,13 +468,19 @@ cluster_multiple_rels(List *rtcs, ClusterParams *params)\n \t\t/* functions in indexes may want a snapshot set */\n \t\tPushActiveSnapshot(GetTransactionSnapshot());\n \n-\t\trel = table_open(rtc->tableOid, AccessExclusiveLock);\n+\t\trel = table_open(rtc->tableOid, lock_mode);\n \n-\t\t/*\n-\t\t * Do the job. (The function will close the relation, lock is kept\n-\t\t * till commit.)\n-\t\t */\n-\t\tcluster_rel(rel, rtc->indexOid, params);\n+\t\t/* Not all relations cannot be processed in the concurrent mode. */\n+\t\tif ((params->options & CLUOPT_CONCURRENT) == 0 ||\n+\t\t\tcheck_relation_is_clusterable_concurrently(rel, DEBUG1,\n+\t\t\t\t\t\t\t\t\t\t\t\t\t \"CLUSTER (CONCURRENTLY)\"))\n+\t\t{\n+\t\t\t/* Do the job. (The function will close the relation, lock is kept\n+\t\t\t * till commit.) */\n+\t\t\tcluster_rel(rel, rtc->indexOid, params, isTopLevel);\n+\t\t}\n+\t\telse\n+\t\t\ttable_close(rel, lock_mode);\n \n \t\tPopActiveSnapshot();\n \t\tCommitTransactionCommand();\n@@ -313,10 +504,21 @@ cluster_multiple_rels(List *rtcs, ClusterParams *params)\n * instead of index order. This is the new implementation of VACUUM FULL,\n * and error messages should refer to the operation as VACUUM not CLUSTER.\n *\n- * We expect that OldHeap is already locked in AccessExclusiveLock mode.\n+ * We expect that OldHeap is already locked. The lock mode is\n+ * AccessExclusiveLock for normal processing and LOCK_CLUSTER_CONCURRENT for\n+ * concurrent processing (so that SELECT, INSERT, UPDATE and DELETE commands\n+ * work, but cluster_rel() cannot be called concurrently for the same\n+ * relation).\n+ *\n+ * Note that, in the concurrent case, the function releases the lock at some\n+ * point, in order to get AccessExclusiveLock for the final steps (i.e. to\n+ * swap the relation files). To make things simpler, the caller should expect\n+ * OldHeap to be closed on return, regardless CLUOPT_CONCURRENT. (The\n+ * AccessExclusiveLock is kept till the end of the transaction.)\n */\n void\n-cluster_rel(Relation OldHeap, Oid indexOid, ClusterParams *params)\n+cluster_rel(Relation OldHeap, Oid indexOid, ClusterParams *params,\n+\t\t\tbool isTopLevel)\n {\n \tOid\t\t\ttableOid = RelationGetRelid(OldHeap);\n \tOid\t\t\tsave_userid;\n@@ -325,6 +527,41 @@ cluster_rel(Relation OldHeap, Oid indexOid, ClusterParams *params)\n \tbool\t\tverbose = ((params->options & CLUOPT_VERBOSE) != 0);\n \tbool\t\trecheck = ((params->options & CLUOPT_RECHECK) != 0);\n \tRelation\tindex = NULL;\n+\tbool\t\tconcurrent = ((params->options & CLUOPT_CONCURRENT) != 0);\n+\tLOCKMODE\tlmode;\n+\tbool\t\tentered, success;\n+\n+\t/* Check that the correct lock is held. */\n+\tlmode = !concurrent ? AccessExclusiveLock : LOCK_CLUSTER_CONCURRENT;\n+\n+\t/*\n+\t * Skip the relation if it's being processed concurrently. In such a case,\n+\t * we cannot rely on a lock because the other backend needs to release it\n+\t * temporarily at some point.\n+\t *\n+\t * This check should not take place until we have a lock that prevents\n+\t * another backend from starting VACUUM FULL / CLUSTER CONCURRENTLY after\n+\t * our check.\n+\t */\n+\tAssert(CheckRelationLockedByMe(OldHeap, lmode, false));\n+\tif (is_concurrent_cluster_in_progress(tableOid))\n+\t{\n+\t\tereport(NOTICE,\n+\t\t\t\t(errmsg(CLUSTER_IN_PROGRESS_MESSAGE,\n+\t\t\t\t\t\tRelationGetRelationName(OldHeap))));\n+\t\ttable_close(OldHeap, lmode);\n+\t\treturn;\n+\t}\n+\n+\t/* There are specific requirements on concurrent processing. */\n+\tif (concurrent)\n+\t{\n+\t\tcheck_concurrent_cluster_requirements(OldHeap, isTopLevel,\n+\t\t\t\t\t\t\t\t\t\t\t OidIsValid(indexOid));\n+\n+\t\tcheck_relation_is_clusterable_concurrently(OldHeap, ERROR,\n+\t\t\t\t\t\t\t\t\t\t\t\t \"CLUSTER (CONCURRENTLY)\");\n+\t}\n \n \t/* Check for user-requested abort. */\n \tCHECK_FOR_INTERRUPTS();\n@@ -361,7 +598,7 @@ cluster_rel(Relation OldHeap, Oid indexOid, ClusterParams *params)\n \t\t/* Check that the user still has privileges for the relation */\n \t\tif (!cluster_is_permitted_for_relation(tableOid, save_userid))\n \t\t{\n-\t\t\trelation_close(OldHeap, AccessExclusiveLock);\n+\t\t\trelation_close(OldHeap, lmode);\n \t\t\tgoto out;\n \t\t}\n \n@@ -376,7 +613,7 @@ cluster_rel(Relation OldHeap, Oid indexOid, ClusterParams *params)\n \t\t */\n \t\tif (RELATION_IS_OTHER_TEMP(OldHeap))\n \t\t{\n-\t\t\trelation_close(OldHeap, AccessExclusiveLock);\n+\t\t\trelation_close(OldHeap, lmode);\n \t\t\tgoto out;\n \t\t}\n \n@@ -387,7 +624,7 @@ cluster_rel(Relation OldHeap, Oid indexOid, ClusterParams *params)\n \t\t\t */\n \t\t\tif (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(indexOid)))\n \t\t\t{\n-\t\t\t\trelation_close(OldHeap, AccessExclusiveLock);\n+\t\t\t\trelation_close(OldHeap, lmode);\n \t\t\t\tgoto out;\n \t\t\t}\n \n@@ -398,7 +635,7 @@ cluster_rel(Relation OldHeap, Oid indexOid, ClusterParams *params)\n \t\t\tif ((params->options & CLUOPT_RECHECK_ISCLUSTERED) != 0 &&\n \t\t\t\t!get_index_isclustered(indexOid))\n \t\t\t{\n-\t\t\t\trelation_close(OldHeap, AccessExclusiveLock);\n+\t\t\t\trelation_close(OldHeap, lmode);\n \t\t\t\tgoto out;\n \t\t\t}\n \t\t}\n@@ -414,6 +651,11 @@ cluster_rel(Relation OldHeap, Oid indexOid, ClusterParams *params)\n \t\tereport(ERROR,\n \t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n \t\t\t\t errmsg(\"cannot cluster a shared catalog\")));\n+\t/*\n+\t * The CONCURRENT case should have been rejected earlier because it does\n+\t * not support system catalogs.\n+\t */\n+\tAssert(!(OldHeap->rd_rel->relisshared && concurrent));\n \n \t/*\n \t * Don't process temp tables of other backends ... their local buffer\n@@ -440,7 +682,7 @@ cluster_rel(Relation OldHeap, Oid indexOid, ClusterParams *params)\n \t/* Check heap and index are valid to cluster on */\n \tif (OidIsValid(indexOid))\n \t{\n-\t\tcheck_index_is_clusterable(OldHeap, indexOid, AccessExclusiveLock);\n+\t\tcheck_index_is_clusterable(OldHeap, indexOid, lmode);\n \t\t/* Open the index (It should already be locked.) */\n \t\tindex = index_open(indexOid, NoLock);\n \t}\n@@ -455,7 +697,8 @@ cluster_rel(Relation OldHeap, Oid indexOid, ClusterParams *params)\n \tif (OldHeap->rd_rel->relkind == RELKIND_MATVIEW &&\n \t\t!RelationIsPopulated(OldHeap))\n \t{\n-\t\trelation_close(OldHeap, AccessExclusiveLock);\n+\t\tindex_close(index, lmode);\n+\t\trelation_close(OldHeap, lmode);\n \t\tgoto out;\n \t}\n \n@@ -468,11 +711,42 @@ cluster_rel(Relation OldHeap, Oid indexOid, ClusterParams *params)\n \t * invalid, because we move tuples around. Promote them to relation\n \t * locks. Predicate locks on indexes will be promoted when they are\n \t * reindexed.\n+\t *\n+\t * During concurrent processing, the heap as well as its indexes stay in\n+\t * operation, so we postpone this step until they are locked using\n+\t * AccessExclusiveLock near the end of the processing.\n \t */\n-\tTransferPredicateLocksToHeapRelation(OldHeap);\n+\tif (!concurrent)\n+\t\tTransferPredicateLocksToHeapRelation(OldHeap);\n \n \t/* rebuild_relation does all the dirty work */\n-\trebuild_relation(OldHeap, index, verbose);\n+\tentered = false;\n+\tsuccess = false;\n+\tPG_TRY();\n+\t{\n+\t\t/*\n+\t\t * For concurrent processing, make sure other transactions treat this\n+\t\t * table as if it was a system / user catalog, and WAL the relevant\n+\t\t * additional information. ERROR is raised if another backend is\n+\t\t * processing the same table.\n+\t\t */\n+\t\tif (concurrent)\n+\t\t{\n+\t\t\tRelation\t*index_p = index ? &index : NULL;\n+\n+\t\t\tbegin_concurrent_cluster(&OldHeap, index_p, &entered);\n+\t\t}\n+\n+\t\trebuild_relation(OldHeap, index, verbose,\n+\t\t\t\t\t\t (params->options & CLUOPT_CONCURRENT) != 0);\n+\t\tsuccess = true;\n+\t}\n+\tPG_FINALLY();\n+\t{\n+\t\tif (concurrent && entered)\n+\t\t\tend_concurrent_cluster(tableOid, !success);\n+\t}\n+\tPG_END_TRY();\n \n \t/*\n \t * NB: rebuild_relation does table_close() on OldHeap, and also on index,\n@@ -622,18 +896,99 @@ mark_index_clustered(Relation rel, Oid indexOid, bool is_internal)\n \ttable_close(pg_index, RowExclusiveLock);\n }\n \n+/*\n+ * Check if the CONCURRENTLY option is legal for the relation.\n+ */\n+bool\n+check_relation_is_clusterable_concurrently(Relation rel, int elevel,\n+\t\t\t\t\t\t\t\t\t\t const char *stmt)\n+{\n+\tchar\trelpersistence, replident;\n+\tOid\t\tident_idx;\n+\n+\t/* Data changes in system relations are not logically decoded. */\n+\tif (IsCatalogRelation(rel))\n+\t{\n+\t\tereport(elevel,\n+\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n+\t\t\t\t errmsg(\"cannot process relation \\\"%s\\\"\",\n+\t\t\t\t\t\tRelationGetRelationName(rel)),\n+\t\t\t\t errhint(\"%s is not supported for catalog relations\", stmt)));\n+\t\treturn false;\n+\t}\n+\n+\tif (IsToastRelation(rel))\n+\t{\n+\t\tereport(elevel,\n+\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n+\t\t\t\t errmsg(\"cannot process relation \\\"%s\\\"\",\n+\t\t\t\t\t\tRelationGetRelationName(rel)),\n+\t\t\t\t errhint(\"%s is not supported for TOAST relations, unless the main relation is processed too\",\n+\t\t\t\t\t\t stmt)));\n+\t\treturn false;\n+\t}\n+\n+\trelpersistence = rel->rd_rel->relpersistence;\n+\tif (relpersistence != RELPERSISTENCE_PERMANENT)\n+\t{\n+\t\tereport(elevel,\n+\t\t\t\t(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n+\t\t\t\t errmsg(\"cannot process relation \\\"%s\\\"\",\n+\t\t\t\t\t\tRelationGetRelationName(rel)),\n+\t\t\t\t errhint(\"CLUSTER CONCURRENTLY is only allowed for permanent relations\")));\n+\t\treturn false;\n+\t}\n+\n+\t/* With NOTHING, WAL does not contain the old tuple. */\n+\treplident = rel->rd_rel->relreplident;\n+\tif (replident == REPLICA_IDENTITY_NOTHING)\n+\t{\n+\t\tereport(elevel,\n+\t\t\t\t(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n+\t\t\t\t errmsg(\"cannot process relation \\\"%s\\\"\",\n+\t\t\t\t\t\tRelationGetRelationName(rel)),\n+\t\t\t\t errhint(\"relation \\\"%s\\\" has insufficient replication identity\",\n+\t\t\t\t\t\t RelationGetRelationName(rel))));\n+\t\treturn false;\n+\t}\n+\n+\t/*\n+\t * Identity index is not set if the replica identity is FULL, but PK might\n+\t * exist in such a case.\n+\t */\n+\tident_idx = RelationGetReplicaIndex(rel);\n+\tif (!OidIsValid(ident_idx) && OidIsValid(rel->rd_pkindex))\n+\t\tident_idx = rel->rd_pkindex;\n+\tif (!OidIsValid(ident_idx))\n+\t{\n+\t\tereport(elevel,\n+\t\t\t\t(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n+\t\t\t\t errmsg(\"cannot process relation \\\"%s\\\"\",\n+\t\t\t\t\t\tRelationGetRelationName(rel)),\n+\t\t\t\t (errhint(\"relation \\\"%s\\\" has no identity index\",\n+\t\t\t\t\t\t RelationGetRelationName(rel)))));\n+\t\treturn false;\n+\t}\n+\n+\treturn true;\n+}\n+\n /*\n * rebuild_relation: rebuild an existing relation in index or physical order\n *\n- * OldHeap: table to rebuild --- must be opened and exclusive-locked!\n+ * OldHeap: table to rebuild --- must be opened and locked. See cluster_rel()\n+ * for comments on the required lock strength.\n+ *\n * index: index to cluster by, or NULL to rewrite in physical order. Must be\n * opened and locked.\n *\n * On exit, the heap (and also the index, if one was passed) are closed, but\n- * still locked with AccessExclusiveLock.\n+ * still locked with AccessExclusiveLock. (The function handles the lock\n+ * upgrade if 'concurrent' is true.)\n */\n static void\n-rebuild_relation(Relation OldHeap, Relation index, bool verbose)\n+rebuild_relation(Relation OldHeap, Relation index, bool verbose,\n+\t\t\t\t bool concurrent)\n {\n \tOid\t\t\ttableOid = RelationGetRelid(OldHeap);\n \tOid\t\t\tindexOid = index ? RelationGetRelid(index) : InvalidOid;\n@@ -642,19 +997,83 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose)\n \tOid\t\t\tOIDNewHeap;\n \tRelation\tNewHeap;\n \tchar\t\trelpersistence;\n-\tbool\t\tis_system_catalog;\n \tbool\t\tswap_toast_by_content;\n \tTransactionId frozenXid;\n \tMultiXactId cutoffMulti;\n+\tNameData\tslotname;\n+\tLogicalDecodingContext *ctx = NULL;\n+\tSnapshot\tsnapshot = NULL;\n+\tCatalogState\t*cat_state = NULL;\n \tLOCKMODE\tlmode_new;\n \n+\tif (concurrent)\n+\t{\n+\t\tTupleDesc\ttupdesc;\n+\t\tRelReopenInfo\trri[2];\n+\t\tint\t\tnrel;\n+\n+\t\t/*\n+\t\t * CLUSTER CONCURRENTLY is not allowed in a transaction block, so this\n+\t\t * should never fire.\n+\t\t */\n+\t\tAssert(GetTopTransactionIdIfAny() == InvalidTransactionId);\n+\n+\t\t/*\n+\t\t * A single backend should not execute multiple CLUSTER commands at a\n+\t\t * time, so use PID to make the slot unique.\n+\t\t */\n+\t\tsnprintf(NameStr(slotname), NAMEDATALEN, \"cluster_%d\", MyProcPid);\n+\n+\t\t/*\n+\t\t * Gather catalog information so that we can check later if the old\n+\t\t * relation has not changed while unlocked.\n+\t\t *\n+\t\t * Since this function also checks if the relation can be processed,\n+\t\t * it's important to call it before we setup the logical decoding,\n+\t\t * because that can take some time. Not sure if it's necessary to do\n+\t\t * it even earlier.\n+\t\t */\n+\t\tcat_state = get_catalog_state(OldHeap);\n+\n+\t\ttupdesc = CreateTupleDescCopy(RelationGetDescr(OldHeap));\n+\n+\t\t/*\n+\t\t * Unlock the relation (and possibly the clustering index) to avoid\n+\t\t * deadlock because setup_logical_decoding() will wait for all the\n+\t\t * running transactions (with XID assigned) to finish. Some of those\n+\t\t * transactions might be waiting for a lock on our relation.\n+\t\t */\n+\t\tnrel = 0;\n+\t\tinit_rel_reopen_info(&rri[nrel++], &OldHeap, InvalidOid,\n+\t\t\t\t\t\t\t LOCK_CLUSTER_CONCURRENT,\n+\t\t\t\t\t\t\t LOCK_CLUSTER_CONCURRENT);\n+\t\tif (index)\n+\t\t\tinit_rel_reopen_info(&rri[nrel++], &index, InvalidOid,\n+\t\t\t\t\t\t\t\t LOCK_CLUSTER_CONCURRENT,\n+\t\t\t\t\t\t\t\t LOCK_CLUSTER_CONCURRENT);\n+\t\tunlock_and_close_relations(rri, nrel);\n+\n+\t\t/* Prepare to capture the concurrent data changes. */\n+\t\tctx = setup_logical_decoding(tableOid, NameStr(slotname), tupdesc);\n+\n+\t\t/* Lock the table (and index) again. */\n+\t\treopen_relations(rri, nrel);\n+\n+\t\t/*\n+\t\t * Check if a 'tupdesc' could have changed while the relation was\n+\t\t * unlocked.\n+\t\t */\n+\t\tcheck_catalog_changes(OldHeap, cat_state);\n+\n+\t\tsnapshot = SnapBuildInitialSnapshotForCluster(ctx->snapshot_builder);\n+\t}\n+\n \tif (OidIsValid(indexOid))\n \t\t/* Mark the correct index as clustered */\n \t\tmark_index_clustered(OldHeap, indexOid, true);\n \n \t/* Remember info about rel before closing OldHeap */\n \trelpersistence = OldHeap->rd_rel->relpersistence;\n-\tis_system_catalog = IsSystemRelation(OldHeap);\n \n \t/*\n \t * Create the transient table that will receive the re-ordered data.\n@@ -673,31 +1092,52 @@ rebuild_relation(Relation OldHeap, Relation index, bool verbose)\n \t\t\t\t\t\t AccessExclusiveLock : NoLock);\n \n \t/* Copy the heap data into the new table in the desired order */\n-\tcopy_table_data(NewHeap, OldHeap, index, verbose,\n+\tcopy_table_data(NewHeap, OldHeap, index, snapshot, ctx, verbose,\n \t\t\t\t\t&swap_toast_by_content, &frozenXid, &cutoffMulti);\n \n+\tif (concurrent)\n+\t{\n+\t\trebuild_relation_finish_concurrent(NewHeap, OldHeap, index,\n+\t\t\t\t\t\t\t\t\t\t cat_state, ctx,\n+\t\t\t\t\t\t\t\t\t\t swap_toast_by_content,\n+\t\t\t\t\t\t\t\t\t\t frozenXid, cutoffMulti);\n+\n+\t\tpgstat_progress_update_param(PROGRESS_CLUSTER_PHASE,\n+\t\t\t\t\t\t\t\t\t PROGRESS_CLUSTER_PHASE_FINAL_CLEANUP);\n+\n+\t\t/* Done with decoding. */\n+\t\tFreeSnapshot(snapshot);\n+\t\tfree_catalog_state(cat_state);\n+\t\tcleanup_logical_decoding(ctx);\n+\t\tReplicationSlotRelease();\n+\t\tReplicationSlotDrop(NameStr(slotname), false);\n+\t}\n+\telse\n+\t{\n+\t\tbool\t\tis_system_catalog = IsSystemRelation(OldHeap);\n \n-\t/* Close relcache entries, but keep lock until transaction commit */\n-\ttable_close(OldHeap, NoLock);\n-\tif (index)\n-\t\tindex_close(index, NoLock);\n+\t\t/* Close relcache entries, but keep lock until transaction commit */\n+\t\ttable_close(OldHeap, NoLock);\n+\t\tif (index)\n+\t\t\tindex_close(index, NoLock);\n \n-\t/*\n-\t * Close the new relation so it can be dropped as soon as the storage is\n-\t * swapped. The relation is not visible to others, so we could unlock it\n-\t * completely, but it's simpler to pass NoLock than to track all the locks\n-\t * acquired so far.\n-\t */\n-\ttable_close(NewHeap, NoLock);\n+\t\t/*\n+\t\t * Close the new relation so it can be dropped as soon as the storage\n+\t\t * is swapped. The relation is not visible to others, so we could\n+\t\t * unlock it completely, but it's simpler to pass NoLock than to track\n+\t\t * all the lock acquired so far.\n+\t\t */\n+\t\ttable_close(NewHeap, NoLock);\n \n-\t/*\n-\t * Swap the physical files of the target and transient tables, then\n-\t * rebuild the target's indexes and throw away the transient table.\n-\t */\n-\tfinish_heap_swap(tableOid, OIDNewHeap, is_system_catalog,\n-\t\t\t\t\t swap_toast_by_content, false, true,\n-\t\t\t\t\t frozenXid, cutoffMulti,\n-\t\t\t\t\t relpersistence);\n+\t\t/*\n+\t\t * Swap the physical files of the target and transient tables, then\n+\t\t * rebuild the target's indexes and throw away the transient table.\n+\t\t */\n+\t\tfinish_heap_swap(tableOid, OIDNewHeap, is_system_catalog,\n+\t\t\t\t\t\t swap_toast_by_content, false, true, true,\n+\t\t\t\t\t\t frozenXid, cutoffMulti,\n+\t\t\t\t\t\t relpersistence);\n+\t}\n }\n \n \n@@ -848,15 +1288,19 @@ make_new_heap(Oid OIDOldHeap, Oid NewTableSpace, Oid NewAccessMethod,\n /*\n * Do the physical copying of table data.\n *\n+ * 'snapshot' and 'decoding_ctx': see table_relation_copy_for_cluster(). Pass\n+ * iff concurrent processing is required.\n+ *\n * There are three output parameters:\n * *pSwapToastByContent is set true if toast tables must be swapped by content.\n * *pFreezeXid receives the TransactionId used as freeze cutoff point.\n * *pCutoffMulti receives the MultiXactId used as a cutoff point.\n */\n static void\n-copy_table_data(Relation NewHeap, Relation OldHeap, Relation OldIndex, bool verbose,\n-\t\t\t\tbool *pSwapToastByContent, TransactionId *pFreezeXid,\n-\t\t\t\tMultiXactId *pCutoffMulti)\n+copy_table_data(Relation NewHeap, Relation OldHeap, Relation OldIndex,\n+\t\t\t\tSnapshot snapshot, LogicalDecodingContext *decoding_ctx,\n+\t\t\t\tbool verbose, bool *pSwapToastByContent,\n+\t\t\t\tTransactionId *pFreezeXid, MultiXactId *pCutoffMulti)\n {\n \tOid\t\tOIDOldHeap = RelationGetRelid(OldHeap);\n \tOid\t\tOIDOldIndex = OldIndex ? RelationGetRelid(OldIndex) : InvalidOid;\n@@ -876,6 +1320,7 @@ copy_table_data(Relation NewHeap, Relation OldHeap, Relation OldIndex, bool verb\n \tint\t\t\televel = verbose ? INFO : DEBUG2;\n \tPGRUsage\tru0;\n \tchar\t *nspname;\n+\tbool\t\tconcurrent = snapshot != NULL;\n \n \tpg_rusage_init(&ru0);\n \n@@ -902,8 +1347,12 @@ copy_table_data(Relation NewHeap, Relation OldHeap, Relation OldIndex, bool verb\n \t *\n \t * We don't need to open the toast relation here, just lock it. The lock\n \t * will be held till end of transaction.\n+\t *\n+\t * In the CONCURRENT case, the lock does not help because we need to\n+\t * release it temporarily at some point. Instead, we expect VACUUM /\n+\t * CLUSTER to skip tables which are present in ClusteredRelsHash.\n \t */\n-\tif (OldHeap->rd_rel->reltoastrelid)\n+\tif (OldHeap->rd_rel->reltoastrelid && !concurrent)\n \t\tLockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);\n \n \t/*\n@@ -979,7 +1428,45 @@ copy_table_data(Relation NewHeap, Relation OldHeap, Relation OldIndex, bool verb\n \t * provided, else plain seqscan.\n \t */\n \tif (OldIndex != NULL && OldIndex->rd_rel->relam == BTREE_AM_OID)\n+\t{\n+\t\tResourceOwner\toldowner = CurrentResourceOwner;\n+\n+\t\t/*\n+\t\t * In the CONCURRENT case, do the planning in a subtrensaction so that\n+\t\t * we don't leave any additional locks behind us that we cannot\n+\t\t * release easily.\n+\t\t */\n+\t\tif (concurrent)\n+\t\t{\n+\t\t\tAssert(CheckRelationLockedByMe(OldHeap, LOCK_CLUSTER_CONCURRENT,\n+\t\t\t\t\t\t\t\t\t\t false));\n+\t\t\tAssert(CheckRelationLockedByMe(OldIndex, LOCK_CLUSTER_CONCURRENT,\n+\t\t\t\t\t\t\t\t\t\t false));\n+\t\t\tBeginInternalSubTransaction(\"plan_cluster_use_sort\");\n+\t\t}\n+\n \t\tuse_sort = plan_cluster_use_sort(OIDOldHeap, OIDOldIndex);\n+\n+\t\tif (concurrent)\n+\t\t{\n+\t\t\tPgBackendProgress\tprogress;\n+\n+\t\t\t/*\n+\t\t\t * Command progress reporting gets terminated at subtransaction\n+\t\t\t * end. Save the status so it can be eventually restored.\n+\t\t\t */\n+\t\t\tmemcpy(&progress, &MyBEEntry->st_progress,\n+\t\t\t\t sizeof(PgBackendProgress));\n+\n+\t\t\t/* Release the locks by aborting the subtransaction. */\n+\t\t\tRollbackAndReleaseCurrentSubTransaction();\n+\n+\t\t\t/* Restore the progress reporting status. */\n+\t\t\tpgstat_progress_restore_state(&progress);\n+\n+\t\t\tCurrentResourceOwner = oldowner;\n+\t\t}\n+\t}\n \telse\n \t\tuse_sort = false;\n \n@@ -1008,7 +1495,9 @@ copy_table_data(Relation NewHeap, Relation OldHeap, Relation OldIndex, bool verb\n \t * values (e.g. because the AM doesn't use freezing).\n \t */\n \ttable_relation_copy_for_cluster(OldHeap, NewHeap, OldIndex, use_sort,\n-\t\t\t\t\t\t\t\t\tcutoffs.OldestXmin, &cutoffs.FreezeLimit,\n+\t\t\t\t\t\t\t\t\tcutoffs.OldestXmin, snapshot,\n+\t\t\t\t\t\t\t\t\tdecoding_ctx,\n+\t\t\t\t\t\t\t\t\t&cutoffs.FreezeLimit,\n \t\t\t\t\t\t\t\t\t&cutoffs.MultiXactCutoff,\n \t\t\t\t\t\t\t\t\t&num_tuples, &tups_vacuumed,\n \t\t\t\t\t\t\t\t\t&tups_recently_dead);\n@@ -1017,7 +1506,11 @@ copy_table_data(Relation NewHeap, Relation OldHeap, Relation OldIndex, bool verb\n \t*pFreezeXid = cutoffs.FreezeLimit;\n \t*pCutoffMulti = cutoffs.MultiXactCutoff;\n \n-\t/* Reset rd_toastoid just to be tidy --- it shouldn't be looked at again */\n+\t/*\n+\t * Reset rd_toastoid just to be tidy --- it shouldn't be looked at\n+\t * again. In the CONCURRENT case, we need to set it again before applying\n+\t * the concurrent changes.\n+\t */\n \tNewHeap->rd_toastoid = InvalidOid;\n \n \tnum_pages = RelationGetNumberOfBlocks(NewHeap);\n@@ -1468,14 +1961,13 @@ finish_heap_swap(Oid OIDOldHeap, Oid OIDNewHeap,\n \t\t\t\t bool swap_toast_by_content,\n \t\t\t\t bool check_constraints,\n \t\t\t\t bool is_internal,\n+\t\t\t\t bool reindex,\n \t\t\t\t TransactionId frozenXid,\n \t\t\t\t MultiXactId cutoffMulti,\n \t\t\t\t char newrelpersistence)\n {\n \tObjectAddress object;\n \tOid\t\t\tmapped_tables[4];\n-\tint\t\t\treindex_flags;\n-\tReindexParams reindex_params = {0};\n \tint\t\t\ti;\n \n \t/* Report that we are now swapping relation files */\n@@ -1501,39 +1993,46 @@ finish_heap_swap(Oid OIDOldHeap, Oid OIDNewHeap,\n \tif (is_system_catalog)\n \t\tCacheInvalidateCatalog(OIDOldHeap);\n \n-\t/*\n-\t * Rebuild each index on the relation (but not the toast table, which is\n-\t * all-new at this point). It is important to do this before the DROP\n-\t * step because if we are processing a system catalog that will be used\n-\t * during DROP, we want to have its indexes available. There is no\n-\t * advantage to the other order anyway because this is all transactional,\n-\t * so no chance to reclaim disk space before commit. We do not need a\n-\t * final CommandCounterIncrement() because reindex_relation does it.\n-\t *\n-\t * Note: because index_build is called via reindex_relation, it will never\n-\t * set indcheckxmin true for the indexes. This is OK even though in some\n-\t * sense we are building new indexes rather than rebuilding existing ones,\n-\t * because the new heap won't contain any HOT chains at all, let alone\n-\t * broken ones, so it can't be necessary to set indcheckxmin.\n-\t */\n-\treindex_flags = REINDEX_REL_SUPPRESS_INDEX_USE;\n-\tif (check_constraints)\n-\t\treindex_flags |= REINDEX_REL_CHECK_CONSTRAINTS;\n+\tif (reindex)\n+\t{\n+\t\tint\t\t\treindex_flags;\n+\t\tReindexParams reindex_params = {0};\n \n-\t/*\n-\t * Ensure that the indexes have the same persistence as the parent\n-\t * relation.\n-\t */\n-\tif (newrelpersistence == RELPERSISTENCE_UNLOGGED)\n-\t\treindex_flags |= REINDEX_REL_FORCE_INDEXES_UNLOGGED;\n-\telse if (newrelpersistence == RELPERSISTENCE_PERMANENT)\n-\t\treindex_flags |= REINDEX_REL_FORCE_INDEXES_PERMANENT;\n+\t\t/*\n+\t\t * Rebuild each index on the relation (but not the toast table, which\n+\t\t * is all-new at this point). It is important to do this before the\n+\t\t * DROP step because if we are processing a system catalog that will\n+\t\t * be used during DROP, we want to have its indexes available. There\n+\t\t * is no advantage to the other order anyway because this is all\n+\t\t * transactional, so no chance to reclaim disk space before commit.\n+\t\t * We do not need a final CommandCounterIncrement() because\n+\t\t * reindex_relation does it.\n+\t\t *\n+\t\t * Note: because index_build is called via reindex_relation, it will never\n+\t\t * set indcheckxmin true for the indexes. This is OK even though in some\n+\t\t * sense we are building new indexes rather than rebuilding existing ones,\n+\t\t * because the new heap won't contain any HOT chains at all, let alone\n+\t\t * broken ones, so it can't be necessary to set indcheckxmin.\n+\t\t */\n+\t\treindex_flags = REINDEX_REL_SUPPRESS_INDEX_USE;\n+\t\tif (check_constraints)\n+\t\t\treindex_flags |= REINDEX_REL_CHECK_CONSTRAINTS;\n \n-\t/* Report that we are now reindexing relations */\n-\tpgstat_progress_update_param(PROGRESS_CLUSTER_PHASE,\n-\t\t\t\t\t\t\t\t PROGRESS_CLUSTER_PHASE_REBUILD_INDEX);\n+\t\t/*\n+\t\t * Ensure that the indexes have the same persistence as the parent\n+\t\t * relation.\n+\t\t */\n+\t\tif (newrelpersistence == RELPERSISTENCE_UNLOGGED)\n+\t\t\treindex_flags |= REINDEX_REL_FORCE_INDEXES_UNLOGGED;\n+\t\telse if (newrelpersistence == RELPERSISTENCE_PERMANENT)\n+\t\t\treindex_flags |= REINDEX_REL_FORCE_INDEXES_PERMANENT;\n \n-\treindex_relation(NULL, OIDOldHeap, reindex_flags, &reindex_params);\n+\t\t/* Report that we are now reindexing relations */\n+\t\tpgstat_progress_update_param(PROGRESS_CLUSTER_PHASE,\n+\t\t\t\t\t\t\t\t\t PROGRESS_CLUSTER_PHASE_REBUILD_INDEX);\n+\n+\t\treindex_relation(NULL, OIDOldHeap, reindex_flags, &reindex_params);\n+\t}\n \n \t/* Report that we are now doing clean up */\n \tpgstat_progress_update_param(PROGRESS_CLUSTER_PHASE,\n@@ -1773,3 +2272,1938 @@ cluster_is_permitted_for_relation(Oid relid, Oid userid)\n \t\t\t\t\tget_rel_name(relid))));\n \treturn false;\n }\n+\n+#define REPL_PLUGIN_NAME\t\"pgoutput_cluster\"\n+\n+/*\n+ * Each relation being processed by CLUSTER CONCURRENTLY must be in the\n+ * clusteredRels hashtable.\n+ */\n+typedef struct ClusteredRel\n+{\n+\tOid\t\trelid;\n+\tOid\t\tdbid;\n+} ClusteredRel;\n+\n+static HTAB *ClusteredRelsHash = NULL;\n+\n+/* Maximum number of entries in the hashtable. */\n+static int maxClusteredRels = 0;\n+\n+Size\n+ClusterShmemSize(void)\n+{\n+\t/*\n+\t * A replication slot is needed for the processing, so use this GUC to\n+\t * allocate memory for the hashtable. Reserve also space for TOAST\n+\t * relations.\n+\t */\n+\tmaxClusteredRels = max_replication_slots * 2;\n+\n+\treturn hash_estimate_size(maxClusteredRels, sizeof(ClusteredRel));\n+}\n+\n+void\n+ClusterShmemInit(void)\n+{\n+\tHASHCTL\t\tinfo;\n+\n+\tinfo.keysize = sizeof(ClusteredRel);\n+\tinfo.entrysize = info.keysize;\n+\n+\tClusteredRelsHash = ShmemInitHash(\"Clustered Relations\",\n+\t\t\t\t\t\t\t\t\t maxClusteredRels,\n+\t\t\t\t\t\t\t\t\t maxClusteredRels,\n+\t\t\t\t\t\t\t\t\t &info,\n+\t\t\t\t\t\t\t\t\t HASH_ELEM | HASH_BLOBS);\n+}\n+\n+/*\n+ * Perform a preliminary check whether CLUSTER / VACUUM FULL CONCURRENTLY is\n+ * possible. Note that here we only check things that should not change if we\n+ * release the relation lock temporarily. The information that can change due\n+ * to unlocking is checked in get_catalog_state().\n+ */\n+static void\n+check_concurrent_cluster_requirements(Relation rel, bool isTopLevel,\n+\t\t\t\t\t\t\t\t\t bool isCluster)\n+{\n+\tconst char\t*stmt;\n+\n+\tif (isCluster)\n+\t\tstmt = \"CLUSTER (CONCURRENTLY)\";\n+\telse\n+\t\tstmt = \"VACUUM (FULL, CONCURRENTLY)\";\n+\n+\t/*\n+\t * Make sure we have no XID assigned, otherwise call of\n+\t * setup_logical_decoding() can cause a deadlock.\n+\t */\n+\tPreventInTransactionBlock(isTopLevel, stmt);\n+\n+\tCheckSlotPermissions();\n+\n+\t/*\n+\t * Use an existing function to check if we can use logical\n+\t * decoding. However note that RecoveryInProgress() should already have\n+\t * caused error, as it does for the non-concurrent VACUUM FULL / CLUSTER.\n+\t */\n+\tCheckLogicalDecodingRequirements();\n+\n+\t/* See ClusterShmemSize() */\n+\tif (max_replication_slots < 2)\n+\t\tereport(ERROR,\n+\t\t\t\terrcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n+\t\t\t\t(errmsg(\"%s requires \\\"max_replication_slots\\\" to be at least 2\",\n+\t\t\t\t\t\tstmt)));\n+}\n+\n+/*\n+ * Call this function before CLUSTER CONCURRENTLY starts to setup logical\n+ * decoding. It makes sure that other users of the table put enough\n+ * information into WAL.\n+ *\n+ * The point is that on various places we expect that the table we're\n+ * processing is treated like a system catalog. For example, we need to be\n+ * able to scan it using a \"historic snapshot\" anytime during the processing\n+ * (as opposed to scanning only at the start point of the decoding, logical\n+ * replication does during initial table synchronization), in order to apply\n+ * concurrent UPDATE / DELETE commands.\n+ *\n+ * Since we need to close and reopen the relation here, the 'rel_p' and\n+ * 'index_p' arguments are in/out.\n+ *\n+ * 'enter_p' receives a bool value telling whether relation OID was entered\n+ * into the hashtable or not.\n+ */\n+static void\n+begin_concurrent_cluster(Relation *rel_p, Relation *index_p,\n+\t\t\t\t\t\t bool *entered_p)\n+{\n+\tRelation\trel = *rel_p;\n+\tOid\t\trelid, toastrelid;\n+\tClusteredRel\tkey, *entry;\n+\tbool\tfound;\n+\tRelReopenInfo\trri[2];\n+\tint\t\tnrel;\n+\tstatic bool before_shmem_exit_callback_setup = false;\n+\n+\trelid = RelationGetRelid(rel);\n+\n+\t/*\n+\t * Make sure that we do not leave an entry in ClusteredRelsHash if exiting\n+\t * due to FATAL.\n+\t */\n+\tif (!before_shmem_exit_callback_setup)\n+\t{\n+\t\tbefore_shmem_exit(cluster_before_shmem_exit_callback, 0);\n+\t\tbefore_shmem_exit_callback_setup = true;\n+\t}\n+\n+\tmemset(&key, 0, sizeof(key));\n+\tkey.relid = relid;\n+\tkey.dbid = MyDatabaseId;\n+\n+\t*entered_p = false;\n+\tLWLockAcquire(ClusteredRelsLock, LW_EXCLUSIVE);\n+\tentry = (ClusteredRel *)\n+\t\thash_search(ClusteredRelsHash, &key, HASH_ENTER_NULL, &found);\n+\tif (found)\n+\t{\n+\t\t/*\n+\t\t * Since CLUSTER CONCURRENTLY takes ShareRowExclusiveLock, a conflict\n+\t\t * should occur much earlier. However that lock may be released\n+\t\t * temporarily, see below. Anyway, we should complain whatever the\n+\t\t * reason of the conflict might be.\n+\t\t */\n+\t\tereport(ERROR,\n+\t\t\t\t(errmsg(CLUSTER_IN_PROGRESS_MESSAGE,\n+\t\t\t\t\t\tRelationGetRelationName(rel))));\n+\t}\n+\tif (entry == NULL)\n+\t\tereport(ERROR,\n+\t\t\t\t(errmsg(\"too many requests for CLUSTER CONCURRENTLY at a time\")),\n+\t\t\t\t(errhint(\"consider increasing the \\\"max_replication_slots\\\" configuration parameter\")));\n+\n+\t/*\n+\t * Even if the insertion of TOAST relid should fail below, the caller has\n+\t * to do cleanup.\n+\t */\n+\t*entered_p = true;\n+\n+\t/*\n+\t * Enable the callback to remove the entry in case of exit. We should not\n+\t * do this earlier, otherwise an attempt to insert already existing entry\n+\t * could make us remove that entry (inserted by another backend) during\n+\t * ERROR handling.\n+\t */\n+\tAssert(!OidIsValid(clustered_rel));\n+\tclustered_rel = relid;\n+\n+\t/*\n+\t * TOAST relation is not accessed using historic snapshot, but we enter it\n+\t * here to protect it from being VACUUMed by another backend. (Lock does\n+\t * not help in the CONCURRENT case because cannot hold it continuously\n+\t * till the end of the transaction.) See the comments on locking TOAST\n+\t * relation in copy_table_data().\n+\t */\n+\ttoastrelid = rel->rd_rel->reltoastrelid;\n+\tif (OidIsValid(toastrelid))\n+\t{\n+\t\tkey.relid = toastrelid;\n+\t\tentry = (ClusteredRel *)\n+\t\t\thash_search(ClusteredRelsHash, &key, HASH_ENTER_NULL, &found);\n+\t\tif (found)\n+\t\t\t/*\n+\t\t\t * If we could enter the main fork the TOAST should succeed\n+\t\t\t * too. Nevertheless, check.\n+\t\t\t */\n+\t\t\tereport(ERROR,\n+\t\t\t\t\t(errmsg(\"TOAST relation of \\\"%s\\\" is already being processed by CLUSTER CONCURRENTLY\",\n+\t\t\t\t\t\t\tRelationGetRelationName(rel))));\n+\t\tif (entry == NULL)\n+\t\t\tereport(ERROR,\n+\t\t\t\t\t(errmsg(\"too many requests for CLUSTER CONCURRENT at a time\")),\n+\t\t\t\t\t(errhint(\"consider increasing the \\\"max_replication_slots\\\" configuration parameter\")));\n+\n+\t\tAssert(!OidIsValid(clustered_rel_toast));\n+\t\tclustered_rel_toast = toastrelid;\n+\t}\n+\tLWLockRelease(ClusteredRelsLock);\n+\n+\t/*\n+\t * Make sure that other backends are aware of the new hash entry.\n+\t *\n+\t * Besides sending the invalidation message, we need to force re-opening\n+\t * of the relation, which includes the actual invalidation (and thus\n+\t * checking of our hashtable on the next access).\n+\t */\n+\tCacheInvalidateRelcacheImmediate(rel);\n+\t/*\n+\t * Since the hashtable only needs to be checked by write transactions,\n+\t * lock the relation in a mode that conflicts with any DML command. (The\n+\t * reading transactions are supposed to close the relation before opening\n+\t * it with higher lock.) Once we have the relation (and its index) locked,\n+\t * we unlock it immediately and then re-lock using the original mode.\n+\t */\n+\tnrel = 0;\n+\tinit_rel_reopen_info(&rri[nrel++], rel_p, InvalidOid,\n+\t\t\t\t\t\t LOCK_CLUSTER_CONCURRENT, ShareLock);\n+\tif (index_p)\n+\t{\n+\t\t/*\n+\t\t * Another transaction might want to open both the relation and the\n+\t\t * index. If it already has the relation lock and is waiting for the\n+\t\t * index lock, we should release the index lock, otherwise our request\n+\t\t * for ShareLock on the relation can end up in a deadlock.\n+\t\t */\n+\t\tinit_rel_reopen_info(&rri[nrel++], index_p, InvalidOid,\n+\t\t\t\t\t\t\t LOCK_CLUSTER_CONCURRENT, ShareLock);\n+\t}\n+\tunlock_and_close_relations(rri, nrel);\n+\t/*\n+\t * XXX It's not strictly necessary to lock the index here, but it's\n+\t * probably not worth teaching the \"reopen API\" about this special case.\n+\t */\n+\treopen_relations(rri, nrel);\n+\n+\t/* Switch back to the original lock. */\n+\tnrel = 0;\n+\tinit_rel_reopen_info(&rri[nrel++], rel_p, InvalidOid,\n+\t\t\t\t\t\t ShareLock, LOCK_CLUSTER_CONCURRENT);\n+\tif (index_p)\n+\t\tinit_rel_reopen_info(&rri[nrel++], index_p, InvalidOid,\n+\t\t\t\t\t\t\t ShareLock, LOCK_CLUSTER_CONCURRENT);\n+\tunlock_and_close_relations(rri, nrel);\n+\treopen_relations(rri, nrel);\n+}\n+\n+/*\n+ * Call this when done with CLUSTER CONCURRENTLY.\n+ *\n+ * 'error' tells whether the function is being called in order to handle\n+ * error.\n+ */\n+static void\n+end_concurrent_cluster(Oid relid, bool error)\n+{\n+\tClusteredRel\tkey, *entry, *entry_toast = NULL;\n+\n+\t/* Remove the relation from the hash. */\n+\tmemset(&key, 0, sizeof(key));\n+\tkey.relid = relid;\n+\tkey.dbid = MyDatabaseId;\n+\tLWLockAcquire(ClusteredRelsLock, LW_EXCLUSIVE);\n+\tentry = hash_search(ClusteredRelsHash, &key, HASH_REMOVE, NULL);\n+\n+\t/* Disable end_concurrent_cluster_on_exit_callback(). */\n+\tif (OidIsValid(clustered_rel))\n+\t\tclustered_rel = InvalidOid;\n+\n+\t/* Remove the TOAST relation if there is one. */\n+\tif (OidIsValid(clustered_rel_toast))\n+\t{\n+\t\tkey.relid = clustered_rel_toast;\n+\t\tentry_toast = hash_search(ClusteredRelsHash, &key, HASH_REMOVE,\n+\t\t\t\t\t\t\t\t NULL);\n+\n+\t\tclustered_rel_toast = InvalidOid;\n+\t}\n+\telse\n+\t\tkey.relid = InvalidOid;\n+\tLWLockRelease(ClusteredRelsLock);\n+\n+\t/*\n+\t * On normal completion (!error), we should not really fail to remove the\n+\t * entry. But if it did for any reason, make sure the transaction is\n+\t * aborted: if other transactions, while changing the contents of the\n+\t * relation, didn't know that CLUSTER CONCURRENTLY was in progress, they\n+\t * could have missed to WAL enough information, and thus we could have\n+\t * produced an inconsistent table contents.\n+\t *\n+\t * On the other hand, if we are already handling an error, there's no\n+\t * reason to worry about inconsistent contents of the new storage because\n+\t * the transaction is going to be rolled back anyway. Furthermore, by\n+\t * raising ERROR here we'd shadow the original error.\n+\t */\n+\tif (!error)\n+\t{\n+\t\tchar\t*relname;\n+\n+\t\tif (entry == NULL)\n+\t\t{\n+\t\t\trelname = get_rel_name(relid);\n+\t\t\tif (!relname)\n+\t\t\t\tereport(ERROR,\n+\t\t\t\t\t\t(errmsg(\"cache lookup failed for relation %u\",\n+\t\t\t\t\t\t\t\trelid)));\n+\n+\t\t\tereport(ERROR,\n+\t\t\t\t\t(errmsg(\"relation \\\"%s\\\" not found among clustered relations\",\n+\t\t\t\t\t\t\trelname)));\n+\t\t}\n+\n+\t\t/*\n+\t\t * Missing TOAST relation indicates that it could have been VACUUMed\n+\t\t * or CLUSTERed by another backend while we did not hold a lock on it.\n+\t\t */\n+\t\tif (entry_toast == NULL && OidIsValid(key.relid))\n+\t\t{\n+\t\t\trelname = get_rel_name(key.relid);\n+\t\t\tif (!relname)\n+\t\t\t\tereport(ERROR,\n+\t\t\t\t\t\t(errmsg(\"cache lookup failed for relation %u\",\n+\t\t\t\t\t\t\t\tkey.relid)));\n+\n+\t\t\tereport(ERROR,\n+\t\t\t\t\t(errmsg(\"relation \\\"%s\\\" not found among clustered relations\",\n+\t\t\t\t\t\t\trelname)));\n+\t\t}\n+\t}\n+\n+\t/*\n+\t * Note: unlike begin_concurrent_cluster(), here we do not lock/unlock the\n+\t * relation: 1) On normal completion, the caller is already holding\n+\t * AccessExclusiveLock (till the end of the transaction), 2) on ERROR /\n+\t * FATAL, we try to do the cleanup asap, but the worst case is that other\n+\t * backends will write unnecessary information to WAL until they close the\n+\t * relation.\n+\t */\n+}\n+\n+/*\n+ * A wrapper to call end_concurrent_cluster() as a before_shmem_exit callback.\n+ */\n+static void\n+cluster_before_shmem_exit_callback(int code, Datum arg)\n+{\n+\tif (OidIsValid(clustered_rel) || OidIsValid(clustered_rel_toast))\n+\t\tend_concurrent_cluster(clustered_rel, true);\n+}\n+\n+/*\n+ * Check if relation is currently being processed by CLUSTER CONCURRENTLY.\n+ */\n+bool\n+is_concurrent_cluster_in_progress(Oid relid)\n+{\n+\tClusteredRel\tkey, *entry;\n+\n+\tmemset(&key, 0, sizeof(key));\n+\tkey.relid = relid;\n+\tkey.dbid = MyDatabaseId;\n+\n+\tLWLockAcquire(ClusteredRelsLock, LW_SHARED);\n+\tentry = (ClusteredRel *)\n+\t\thash_search(ClusteredRelsHash, &key, HASH_FIND, NULL);\n+\tLWLockRelease(ClusteredRelsLock);\n+\n+\treturn entry != NULL;\n+}\n+\n+/*\n+ * Check if VACUUM FULL / CLUSTER CONCURRENTLY is already running for given\n+ * relation, and if so, raise ERROR. The problem is that cluster_rel() needs\n+ * to release its lock on the relation temporarily at some point, so our lock\n+ * alone does not help. Commands that might break what cluster_rel() is doing\n+ * should call this function first.\n+ *\n+ * Return without checking if lockmode allows for race conditions which would\n+ * make the result meaningless. In that case, cluster_rel() itself should\n+ * throw ERROR if the relation was changed by us in an incompatible\n+ * way. However, if it managed to do most of its work by then, a lot of CPU\n+ * time might be wasted.\n+ */\n+void\n+check_for_concurrent_cluster(Oid relid, LOCKMODE lockmode)\n+{\n+\t/*\n+\t * If the caller does not have a lock that conflicts with\n+\t * LOCK_CLUSTER_CONCURRENT, the check makes little sense because the\n+\t * VACUUM FULL / CLUSTER CONCURRENTLY can start anytime after the check.\n+\t */\n+\tif (lockmode < LOCK_CLUSTER_CONCURRENT)\n+\t\treturn;\n+\n+\tif (is_concurrent_cluster_in_progress(relid))\n+\t\tereport(ERROR,\n+\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n+\t\t\t\t errmsg(CLUSTER_IN_PROGRESS_MESSAGE,\n+\t\t\t\t\t\tget_rel_name(relid))));\n+\n+}\n+\n+/*\n+ * Check if relation is eligible for CLUSTER CONCURRENTLY and retrieve the\n+ * catalog state to be passed later to check_catalog_changes.\n+ *\n+ * Caller is supposed to hold (at least) LOCK_CLUSTER_CONCURRENT on the\n+ * relation.\n+ */\n+static CatalogState *\n+get_catalog_state(Relation rel)\n+{\n+\tCatalogState\t*result = palloc_object(CatalogState);\n+\tList\t*ind_oids;\n+\tListCell\t*lc;\n+\tint\t\tninds, i;\n+\tOid\t\treltoastrelid = rel->rd_rel->reltoastrelid;\n+\tchar\trelpersistence = rel->rd_rel->relpersistence;\n+\tchar\treplident = rel->rd_rel->relreplident;\n+\tOid\t\tident_idx = RelationGetReplicaIndex(rel);\n+\tTupleDesc\ttd_src = RelationGetDescr(rel);\n+\n+\t/*\n+\t * While gathering the catalog information, check if there is a reason not\n+\t * to proceed.\n+\t */\n+\tcheck_relation_is_clusterable_concurrently(rel, ERROR,\n+\t\t\t\t\t\t\t\t\t\t\t \"CLUSTER (CONCURRENTLY)\");\n+\n+\t/*\n+\t * TOAST should not really change, but be careful. If it did, we would be\n+\t * unable to remove the new one from ClusteredRelsHash.\n+\t */\n+\tif (OidIsValid(clustered_rel_toast) &&\n+\t\tclustered_rel_toast != reltoastrelid)\n+\t\tereport(ERROR,\n+\t\t\t\t(errmsg(\"TOAST relation changed by another transaction\")));\n+\n+\t/* No index should be dropped while we are checking it. */\n+\tAssert(CheckRelationLockedByMe(rel, ShareUpdateExclusiveLock, true));\n+\n+\tind_oids = RelationGetIndexList(rel);\n+\tresult->ninds = ninds = list_length(ind_oids);\n+\tresult->ind_oids = palloc_array(Oid, ninds);\n+\tresult->ind_tupdescs = palloc_array(TupleDesc, ninds);\n+\ti = 0;\n+\tforeach(lc, ind_oids)\n+\t{\n+\t\tOid\tind_oid = lfirst_oid(lc);\n+\t\tRelation\tindex;\n+\t\tTupleDesc\ttd_src, td_dst;\n+\n+\t\t/*\n+\t\t * Weaker lock should be o.k. for the index, but this one should break\n+\t\t * anything either.\n+\t\t */\n+\t\tindex = index_open(ind_oid, ShareUpdateExclusiveLock);\n+\n+\t\tresult->ind_oids[i] = RelationGetRelid(index);\n+\t\ttd_src = RelationGetDescr(index);\n+\t\ttd_dst = palloc(TupleDescSize(td_src));\n+\t\tTupleDescCopy(td_dst, td_src);\n+\t\tresult->ind_tupdescs[i] = td_dst;\n+\t\ti++;\n+\n+\t\tindex_close(index, ShareUpdateExclusiveLock);\n+\t}\n+\n+\t/* Fill-in the relation info. */\n+\tresult->tupdesc = palloc(TupleDescSize(td_src));\n+\tTupleDescCopy(result->tupdesc, td_src);\n+\tresult->reltoastrelid = reltoastrelid;\n+\tresult->relpersistence = relpersistence;\n+\tresult->replident = replident;\n+\tresult->replidindex = ident_idx;\n+\n+\treturn\tresult;\n+}\n+\n+static void\n+free_catalog_state(CatalogState *state)\n+{\n+\t/* We are only interested in indexes. */\n+\tif (state->ninds == 0)\n+\t\treturn;\n+\n+\tfor (int i = 0; i < state->ninds; i++)\n+\t\tFreeTupleDesc(state->ind_tupdescs[i]);\n+\n+\tFreeTupleDesc(state->tupdesc);\n+\tpfree(state->ind_oids);\n+\tpfree(state->ind_tupdescs);\n+\tpfree(state);\n+}\n+\n+/*\n+ * Raise ERROR if 'rel' changed in a way that does not allow further\n+ * processing of CLUSTER CONCURRENTLY.\n+ *\n+ * Besides the relation's tuple descriptor, it's important to check indexes:\n+ * concurrent change of index definition (can it happen in other way than\n+ * dropping and re-creating the index, accidentally with the same OID?) can be\n+ * a problem because we may already have the new index built. If an index was\n+ * created or dropped concurrently, we'd fail to swap the index storage. In\n+ * any case, we prefer to check the indexes early to get an explicit error\n+ * message about the mismatch. Furthermore, the earlier we detect the change,\n+ * the fewer CPU cycles we waste.\n+ *\n+ * Note that we do not check constraints because the transaction which changed\n+ * them must have ensured that the existing tuples satisfy the new\n+ * constraints. If any DML commands were necessary for that, we will simply\n+ * decode them from WAL and apply them to the new storage.\n+ *\n+ * Caller is supposed to hold (at least) ShareUpdateExclusiveLock on the\n+ * relation.\n+ */\n+static void\n+check_catalog_changes(Relation rel, CatalogState *cat_state)\n+{\n+\tList\t*ind_oids;\n+\tListCell\t*lc;\n+\tLOCKMODE\tlmode;\n+\tOid\t\tident_idx;\n+\tTupleDesc\ttd, td_cp;\n+\n+\t/* First, check the relation info. */\n+\n+\t/* TOAST is not easy to change, but check. */\n+\tif (rel->rd_rel->reltoastrelid != cat_state->reltoastrelid)\n+\t\tereport(ERROR,\n+\t\t\t\terrmsg(\"TOAST relation of relation \\\"%s\\\" changed by another transaction\",\n+\t\t\t\t\t RelationGetRelationName(rel)));\n+\n+\tif (rel->rd_rel->relpersistence != cat_state->relpersistence)\n+\t\tereport(ERROR,\n+\t\t\t\terrmsg(\"persistence of relation \\\"%s\\\" changed by another transaction\",\n+\t\t\t\t\t RelationGetRelationName(rel)));\n+\n+\tif (cat_state->replident != rel->rd_rel->relreplident)\n+\t\tereport(ERROR,\n+\t\t\t\terrmsg(\"replica identity of relation \\\"%s\\\" changed by another transaction\",\n+\t\t\t\t\t RelationGetRelationName(rel)));\n+\n+\tident_idx = RelationGetReplicaIndex(rel);\n+\tif (ident_idx == InvalidOid && rel->rd_pkindex != InvalidOid)\n+\t\tident_idx = rel->rd_pkindex;\n+\tif (cat_state->replidindex != ident_idx)\n+\t\tereport(ERROR,\n+\t\t\t\terrmsg(\"identity index of relation \\\"%s\\\" changed by another transaction\",\n+\t\t\t\t\t RelationGetRelationName(rel)));\n+\n+\t/*\n+\t * As cat_state contains a copy (which has the constraint info cleared),\n+\t * create a temporary copy for the comparison.\n+\t */\n+\ttd = RelationGetDescr(rel);\n+\ttd_cp = palloc(TupleDescSize(td));\n+\tTupleDescCopy(td_cp, td);\n+\tif (!equalTupleDescs(cat_state->tupdesc, td_cp))\n+\t\tereport(ERROR,\n+\t\t\t\terrmsg(\"definition of relation \\\"%s\\\" changed by another transaction\",\n+\t\t\t\t\t RelationGetRelationName(rel)));\n+\tFreeTupleDesc(td_cp);\n+\n+\t/* Now we are only interested in indexes. */\n+\tif (cat_state->ninds == 0)\n+\t\treturn;\n+\n+\t/* No index should be dropped while we are checking the relation. */\n+\tlmode = ShareUpdateExclusiveLock;\n+\tAssert(CheckRelationLockedByMe(rel, lmode, true));\n+\n+\tind_oids = RelationGetIndexList(rel);\n+\tif (list_length(ind_oids) != cat_state->ninds)\n+\t\tgoto failed_index;\n+\n+\tforeach(lc, ind_oids)\n+\t{\n+\t\tOid\tind_oid = lfirst_oid(lc);\n+\t\tint\t\ti;\n+\t\tTupleDesc\ttupdesc;\n+\t\tRelation\tindex;\n+\n+\t\t/* Find the index in cat_state. */\n+\t\tfor (i = 0; i < cat_state->ninds; i++)\n+\t\t{\n+\t\t\tif (cat_state->ind_oids[i] == ind_oid)\n+\t\t\t\tbreak;\n+\t\t}\n+\t\t/*\n+\t\t * OID not found, i.e. the index was replaced by another one. XXX\n+\t\t * Should we yet try to find if an index having the desired tuple\n+\t\t * descriptor exists? Or should we always look for the tuple\n+\t\t * descriptor and not use OIDs at all?\n+\t\t */\n+\t\tif (i == cat_state->ninds)\n+\t\t\tgoto failed_index;\n+\n+\t\t/* Check the tuple descriptor. */\n+\t\tindex = try_index_open(ind_oid, lmode);\n+\t\tif (index == NULL)\n+\t\t\tgoto failed_index;\n+\t\ttupdesc = RelationGetDescr(index);\n+\t\tif (!equalTupleDescs(cat_state->ind_tupdescs[i], tupdesc))\n+\t\t\tgoto failed_index;\n+\t\tindex_close(index, lmode);\n+\t}\n+\n+\treturn;\n+\n+failed_index:\n+\tereport(ERROR,\n+\t\t\t(errmsg(\"index(es) of relation \\\"%s\\\" changed by another transaction\",\n+\t\t\t\t\tRelationGetRelationName(rel))));\n+}\n+\n+/*\n+ * This function is much like pg_create_logical_replication_slot() except that\n+ * the new slot is neither released (if anyone else could read changes from\n+ * our slot, we could miss changes other backends do while we copy the\n+ * existing data into temporary table), nor persisted (it's easier to handle\n+ * crash by restarting all the work from scratch).\n+ *\n+ * XXX Even though CreateInitDecodingContext() does not set state to\n+ * RS_PERSISTENT, it does write the slot to disk. We rely on\n+ * RestoreSlotFromDisk() to delete ephemeral slots during startup. (Both ERROR\n+ * and FATAL should lead to cleanup even before the cluster goes down.)\n+ */\n+static LogicalDecodingContext *\n+setup_logical_decoding(Oid relid, const char *slotname, TupleDesc tupdesc)\n+{\n+\tLogicalDecodingContext *ctx;\n+\tClusterDecodingState *dstate;\n+\n+\t/* RS_TEMPORARY so that the slot gets cleaned up on ERROR. */\n+\tReplicationSlotCreate(slotname, true, RS_TEMPORARY, false, false, false);\n+\n+\t/*\n+\t * Neither prepare_write nor do_write callback nor update_progress is\n+\t * useful for us.\n+\t *\n+\t * Regarding the value of need_full_snapshot, we pass false because the\n+\t * table we are processing is present in ClusteredRelsHash and therefore,\n+\t * regarding logical decoding, treated like a catalog.\n+\t */\n+\tctx = CreateInitDecodingContext(REPL_PLUGIN_NAME,\n+\t\t\t\t\t\t\t\t\tNIL,\n+\t\t\t\t\t\t\t\t\tfalse,\n+\t\t\t\t\t\t\t\t\tInvalidXLogRecPtr,\n+\t\t\t\t\t\t\t\t\tXL_ROUTINE(.page_read = read_local_xlog_page,\n+\t\t\t\t\t\t\t\t\t\t\t .segment_open = wal_segment_open,\n+\t\t\t\t\t\t\t\t\t\t\t .segment_close = wal_segment_close),\n+\t\t\t\t\t\t\t\t\tNULL, NULL, NULL);\n+\n+\t/*\n+\t * We don't have control on setting fast_forward, so at least check it.\n+\t */\n+\tAssert(!ctx->fast_forward);\n+\n+\tDecodingContextFindStartpoint(ctx);\n+\n+\t/* Some WAL records should have been read. */\n+\tAssert(ctx->reader->EndRecPtr != InvalidXLogRecPtr);\n+\n+\tXLByteToSeg(ctx->reader->EndRecPtr, cluster_current_segment,\n+\t\t\t\twal_segment_size);\n+\n+\t/*\n+\t * Setup structures to store decoded changes.\n+\t */\n+\tdstate = palloc0(sizeof(ClusterDecodingState));\n+\tdstate->relid = relid;\n+\tdstate->tstore = tuplestore_begin_heap(false, false,\n+\t\t\t\t\t\t\t\t\t\t maintenance_work_mem);\n+\tdstate->tupdesc = tupdesc;\n+\n+\t/* Initialize the descriptor to store the changes ... */\n+\tdstate->tupdesc_change = CreateTemplateTupleDesc(1);\n+\n+\tTupleDescInitEntry(dstate->tupdesc_change, 1, NULL, BYTEAOID, -1, 0);\n+\t/* ... as well as the corresponding slot. */\n+\tdstate->tsslot = MakeSingleTupleTableSlot(dstate->tupdesc_change,\n+\t\t\t\t\t\t\t\t\t\t\t &TTSOpsMinimalTuple);\n+\n+\tdstate->resowner = ResourceOwnerCreate(CurrentResourceOwner,\n+\t\t\t\t\t\t\t\t\t\t \"logical decoding\");\n+\n+\tctx->output_writer_private = dstate;\n+\treturn ctx;\n+}\n+\n+/*\n+ * Retrieve tuple from a change structure. As for the change, no alignment is\n+ * assumed.\n+ */\n+static HeapTuple\n+get_changed_tuple(ConcurrentChange *change)\n+{\n+\tHeapTupleData tup_data;\n+\tHeapTuple\tresult;\n+\tchar\t *src;\n+\n+\t/*\n+\t * Ensure alignment before accessing the fields. (This is why we can't use\n+\t * heap_copytuple() instead of this function.)\n+\t */\n+\tmemcpy(&tup_data, &change->tup_data, sizeof(HeapTupleData));\n+\n+\tresult = (HeapTuple) palloc(HEAPTUPLESIZE + tup_data.t_len);\n+\tmemcpy(result, &tup_data, sizeof(HeapTupleData));\n+\tresult->t_data = (HeapTupleHeader) ((char *) result + HEAPTUPLESIZE);\n+\tsrc = (char *) change + sizeof(ConcurrentChange);\n+\tmemcpy(result->t_data, src, result->t_len);\n+\n+\treturn result;\n+}\n+\n+/*\n+ * Decode logical changes from the WAL sequence up to end_of_wal.\n+ */\n+void\n+cluster_decode_concurrent_changes(LogicalDecodingContext *ctx,\n+\t\t\t\t\t\t\t\t XLogRecPtr end_of_wal)\n+{\n+\tClusterDecodingState *dstate;\n+\tResourceOwner resowner_old;\n+\tPgBackendProgress\tprogress;\n+\n+\t/*\n+\t * Invalidate the \"present\" cache before moving to \"(recent) history\".\n+\t */\n+\tInvalidateSystemCaches();\n+\n+\tdstate = (ClusterDecodingState *) ctx->output_writer_private;\n+\tresowner_old = CurrentResourceOwner;\n+\tCurrentResourceOwner = dstate->resowner;\n+\n+\t/*\n+\t * reorderbuffer.c uses internal subtransaction, whose abort ends the\n+\t * command progress reporting. Save the status here so we can restore when\n+\t * done with the decoding.\n+\t */\n+\tmemcpy(&progress, &MyBEEntry->st_progress, sizeof(PgBackendProgress));\n+\n+\tPG_TRY();\n+\t{\n+\t\twhile (ctx->reader->EndRecPtr < end_of_wal)\n+\t\t{\n+\t\t\tXLogRecord *record;\n+\t\t\tXLogSegNo\tsegno_new;\n+\t\t\tchar\t *errm = NULL;\n+\t\t\tXLogRecPtr\tend_lsn;\n+\n+\t\t\trecord = XLogReadRecord(ctx->reader, &errm);\n+\t\t\tif (errm)\n+\t\t\t\telog(ERROR, \"%s\", errm);\n+\n+\t\t\tif (record != NULL)\n+\t\t\t\tLogicalDecodingProcessRecord(ctx, ctx->reader);\n+\n+\t\t\t/*\n+\t\t\t * If WAL segment boundary has been crossed, inform the decoding\n+\t\t\t * system that the catalog_xmin can advance. (We can confirm more\n+\t\t\t * often, but a filling a single WAL segment should not take much\n+\t\t\t * time.)\n+\t\t\t */\n+\t\t\tend_lsn = ctx->reader->EndRecPtr;\n+\t\t\tXLByteToSeg(end_lsn, segno_new, wal_segment_size);\n+\t\t\tif (segno_new != cluster_current_segment)\n+\t\t\t{\n+\t\t\t\tLogicalConfirmReceivedLocation(end_lsn);\n+\t\t\t\telog(DEBUG1, \"cluster: confirmed receive location %X/%X\",\n+\t\t\t\t\t (uint32) (end_lsn >> 32), (uint32) end_lsn);\n+\t\t\t\tcluster_current_segment = segno_new;\n+\t\t\t}\n+\n+\t\t\tCHECK_FOR_INTERRUPTS();\n+\t\t}\n+\t\tInvalidateSystemCaches();\n+\t\tCurrentResourceOwner = resowner_old;\n+\t}\n+\tPG_CATCH();\n+\t{\n+\t\tInvalidateSystemCaches();\n+\t\tCurrentResourceOwner = resowner_old;\n+\t\tPG_RE_THROW();\n+\t}\n+\tPG_END_TRY();\n+\n+\t/* Restore the progress reporting status. */\n+\tpgstat_progress_restore_state(&progress);\n+}\n+\n+/*\n+ * Apply changes that happened during the initial load.\n+ *\n+ * Scan key is passed by caller, so it does not have to be constructed\n+ * multiple times. Key entries have all fields initialized, except for\n+ * sk_argument.\n+ */\n+static void\n+apply_concurrent_changes(ClusterDecodingState *dstate, Relation rel,\n+\t\t\t\t\t\t ScanKey key, int nkeys, IndexInsertState *iistate)\n+{\n+\tTupleTableSlot *index_slot, *ident_slot;\n+\tHeapTuple\ttup_old = NULL;\n+\n+\tif (dstate->nchanges == 0)\n+\t\treturn;\n+\n+\t/* TupleTableSlot is needed to pass the tuple to ExecInsertIndexTuples(). */\n+\tindex_slot = MakeSingleTupleTableSlot(dstate->tupdesc, &TTSOpsHeapTuple);\n+\tiistate->econtext->ecxt_scantuple = index_slot;\n+\n+\t/* A slot to fetch tuples from identity index. */\n+\tident_slot = table_slot_create(rel, NULL);\n+\n+\twhile (tuplestore_gettupleslot(dstate->tstore, true, false,\n+\t\t\t\t\t\t\t\t dstate->tsslot))\n+\t{\n+\t\tbool\t\tshouldFree;\n+\t\tHeapTuple\ttup_change,\n+\t\t\t\t\ttup,\n+\t\t\t\t\ttup_exist;\n+\t\tchar\t *change_raw;\n+\t\tConcurrentChange *change;\n+\t\tSnapshot\tsnapshot;\n+\t\tbool\t\tisnull[1];\n+\t\tDatum\t\tvalues[1];\n+\n+\t\tCHECK_FOR_INTERRUPTS();\n+\n+\t\t/* Get the change from the single-column tuple. */\n+\t\ttup_change = ExecFetchSlotHeapTuple(dstate->tsslot, false, &shouldFree);\n+\t\theap_deform_tuple(tup_change, dstate->tupdesc_change, values, isnull);\n+\t\tAssert(!isnull[0]);\n+\n+\t\t/* This is bytea, but char* is easier to work with. */\n+\t\tchange_raw = (char *) DatumGetByteaP(values[0]);\n+\n+\t\tchange = (ConcurrentChange *) VARDATA(change_raw);\n+\n+\t\t/* TRUNCATE change contains no tuple, so process it separately. */\n+\t\tif (change->kind == CHANGE_TRUNCATE)\n+\t\t{\n+\t\t\t/*\n+\t\t\t * All the things that ExecuteTruncateGuts() does (such as firing\n+\t\t\t * triggers or handling the DROP_CASCADE behavior) should have\n+\t\t\t * taken place on the source relation. Thus we only do the actual\n+\t\t\t * truncation of the new relation (and its indexes).\n+\t\t\t */\n+\t\t\theap_truncate_one_rel(rel);\n+\n+\t\t\tpfree(tup_change);\n+\t\t\tcontinue;\n+\t\t}\n+\n+\t\t/*\n+\t\t * Extract the tuple from the change. The tuple is copied here because\n+\t\t * it might be assigned to 'tup_old', in which case it needs to\n+\t\t * survive into the next iteration.\n+\t\t */\n+\t\ttup = get_changed_tuple(change);\n+\n+\t\tif (change->kind == CHANGE_UPDATE_OLD)\n+\t\t{\n+\t\t\tAssert(tup_old == NULL);\n+\t\t\ttup_old = tup;\n+\t\t}\n+\t\telse if (change->kind == CHANGE_INSERT)\n+\t\t{\n+\t\t\tAssert(tup_old == NULL);\n+\n+\t\t\tapply_concurrent_insert(rel, change, tup, iistate, index_slot);\n+\n+\t\t\tpfree(tup);\n+\t\t}\n+\t\telse if (change->kind == CHANGE_UPDATE_NEW ||\n+\t\t\t\t change->kind == CHANGE_DELETE)\n+\t\t{\n+\t\t\tIndexScanDesc\tind_scan = NULL;\n+\t\t\tHeapTuple\ttup_key;\n+\n+\t\t\tif (change->kind == CHANGE_UPDATE_NEW)\n+\t\t\t{\n+\t\t\t\ttup_key = tup_old != NULL ? tup_old : tup;\n+\t\t\t}\n+\t\t\telse\n+\t\t\t{\n+\t\t\t\tAssert(tup_old == NULL);\n+\t\t\t\ttup_key = tup;\n+\t\t\t}\n+\n+\t\t\t/*\n+\t\t\t * Find the tuple to be updated or deleted.\n+\t\t\t *\n+\t\t\t * As the table being CLUSTERed concurrently is considered an\n+\t\t\t * \"user catalog\", new CID is WAL-logged and decoded. And since we\n+\t\t\t * use the same XID that the original DMLs did, the snapshot used\n+\t\t\t * for the logical decoding (by now converted to a non-historic\n+\t\t\t * MVCC snapshot) should see the tuples inserted previously into\n+\t\t\t * the new heap and/or updated there.\n+\t\t\t */\n+\t\t\tsnapshot = change->snapshot;\n+\n+\t\t\t/*\n+\t\t\t * Set what should be considered current transaction (and\n+\t\t\t * subtransactions) during visibility check.\n+\t\t\t *\n+\t\t\t * Note that this snapshot was created from a historic snapshot\n+\t\t\t * using SnapBuildMVCCFromHistoric(), which does not touch\n+\t\t\t * 'subxip'. Thus, unlike in a regular MVCC snapshot, the array\n+\t\t\t * does not contain (sub)transactions other than the one whose\n+\t\t\t * data changes we are applying.\n+\t\t\t */\n+\t\t\tSetClusterCurrentXids(snapshot->subxip, snapshot->subxcnt);\n+\n+\t\t\ttup_exist = find_target_tuple(rel, key, nkeys, tup_key, snapshot,\n+\t\t\t\t\t\t\t\t\t\t iistate, ident_slot, &ind_scan);\n+\t\t\tif (tup_exist == NULL)\n+\t\t\t\telog(ERROR, \"Failed to find target tuple\");\n+\n+\t\t\tif (change->kind == CHANGE_UPDATE_NEW)\n+\t\t\t\tapply_concurrent_update(rel, tup, tup_exist, change, iistate,\n+\t\t\t\t\t\t\t\t\t\tindex_slot);\n+\t\t\telse\n+\t\t\t\tapply_concurrent_delete(rel, tup_exist, change);\n+\n+\t\t\tResetClusterCurrentXids();\n+\n+\t\t\tif (tup_old != NULL)\n+\t\t\t{\n+\t\t\t\tpfree(tup_old);\n+\t\t\t\ttup_old = NULL;\n+\t\t\t}\n+\n+\t\t\tpfree(tup);\n+\t\t\tindex_endscan(ind_scan);\n+\t\t}\n+\t\telse\n+\t\t\telog(ERROR, \"Unrecognized kind of change: %d\", change->kind);\n+\n+\t\t/* Free the snapshot if this is the last change that needed it. */\n+\t\tAssert(change->snapshot->active_count > 0);\n+\t\tchange->snapshot->active_count--;\n+\t\tif (change->snapshot->active_count == 0)\n+\t\t{\n+\t\t\tif (change->snapshot == dstate->snapshot)\n+\t\t\t\tdstate->snapshot = NULL;\n+\t\t\tFreeSnapshot(change->snapshot);\n+\t\t}\n+\n+\t\t/* TTSOpsMinimalTuple has .get_heap_tuple==NULL. */\n+\t\tAssert(shouldFree);\n+\t\tpfree(tup_change);\n+\t}\n+\n+\ttuplestore_clear(dstate->tstore);\n+\tdstate->nchanges = 0;\n+\n+\t/* Cleanup. */\n+\tExecDropSingleTupleTableSlot(index_slot);\n+\tExecDropSingleTupleTableSlot(ident_slot);\n+}\n+\n+static void\n+apply_concurrent_insert(Relation rel, ConcurrentChange *change, HeapTuple tup,\n+\t\t\t\t\t\tIndexInsertState *iistate, TupleTableSlot *index_slot)\n+{\n+\tSnapshot\tsnapshot = change->snapshot;\n+\tList\t *recheck;\n+\n+\t/*\n+\t * For INSERT, the visibility information is not important, but we use the\n+\t * snapshot to get CID. Index functions might need the whole snapshot\n+\t * anyway.\n+\t */\n+\tSetClusterCurrentXids(snapshot->subxip, snapshot->subxcnt);\n+\n+\t/*\n+\t * Write the tuple into the new heap.\n+\t *\n+\t * The snapshot is the one we used to decode the insert (though converted\n+\t * to \"non-historic\" MVCC snapshot), i.e. the snapshot's curcid is the\n+\t * tuple CID incremented by one (due to the \"new CID\" WAL record that got\n+\t * written along with the INSERT record). Thus if we want to use the\n+\t * original CID, we need to subtract 1 from curcid.\n+\t */\n+\tAssert(snapshot->curcid != InvalidCommandId &&\n+\t\t snapshot->curcid > FirstCommandId);\n+\n+\theap_insert(rel, tup, change->xid, snapshot->curcid - 1,\n+\t\t\t\tHEAP_INSERT_NO_LOGICAL, NULL);\n+\n+\t/*\n+\t * Update indexes.\n+\t *\n+\t * In case functions in the index need the active snapshot and caller\n+\t * hasn't set one.\n+\t */\n+\tPushActiveSnapshot(snapshot);\n+\tExecStoreHeapTuple(tup, index_slot, false);\n+\trecheck = ExecInsertIndexTuples(iistate->rri,\n+\t\t\t\t\t\t\t\t\tindex_slot,\n+\t\t\t\t\t\t\t\t\tiistate->estate,\n+\t\t\t\t\t\t\t\t\tfalse,\t/* update */\n+\t\t\t\t\t\t\t\t\tfalse,\t/* noDupErr */\n+\t\t\t\t\t\t\t\t\tNULL,\t/* specConflict */\n+\t\t\t\t\t\t\t\t\tNIL, /* arbiterIndexes */\n+\t\t\t\t\t\t\t\t\tfalse\t/* onlySummarizing */\n+\t\t);\n+\tPopActiveSnapshot();\n+\tResetClusterCurrentXids();\n+\n+\t/*\n+\t * If recheck is required, it must have been preformed on the source\n+\t * relation by now. (All the logical changes we process here are already\n+\t * committed.)\n+\t */\n+\tlist_free(recheck);\n+\n+\tpgstat_progress_incr_param(PROGRESS_CLUSTER_HEAP_TUPLES_INSERTED, 1);\n+}\n+\n+static void\n+apply_concurrent_update(Relation rel, HeapTuple tup, HeapTuple tup_target,\n+\t\t\t\t\t\tConcurrentChange *change, IndexInsertState *iistate,\n+\t\t\t\t\t\tTupleTableSlot *index_slot)\n+{\n+\tList\t *recheck;\n+\tLockTupleMode\tlockmode;\n+\tTU_UpdateIndexes\tupdate_indexes;\n+\tItemPointerData\t\ttid_old_new_heap;\n+\tTM_Result\tres;\n+\tSnapshot snapshot\t= change->snapshot;\n+\tTM_FailureData tmfd;\n+\n+\t/* Location of the existing tuple in the new heap. */\n+\tItemPointerCopy(&tup_target->t_self, &tid_old_new_heap);\n+\n+\t/*\n+\t * Write the new tuple into the new heap. ('tup' gets the TID assigned\n+\t * here.)\n+\t *\n+\t * Regarding CID, see the comment in apply_concurrent_insert().\n+\t */\n+\tAssert(snapshot->curcid != InvalidCommandId &&\n+\t\t snapshot->curcid > FirstCommandId);\n+\n+\tres = heap_update(rel, &tid_old_new_heap, tup,\n+\t\t\t\t\t change->xid, snapshot->curcid - 1,\n+\t\t\t\t\t InvalidSnapshot,\n+\t\t\t\t\t false, /* no wait - only we are doing changes */\n+\t\t\t\t\t &tmfd, &lockmode, &update_indexes,\n+\t\t\t\t\t /* wal_logical */\n+\t\t\t\t\t false);\n+\tif (res != TM_Ok)\n+\t\tereport(ERROR, (errmsg(\"failed to apply concurrent UPDATE\")));\n+\n+\tExecStoreHeapTuple(tup, index_slot, false);\n+\n+\tif (update_indexes != TU_None)\n+\t{\n+\t\tPushActiveSnapshot(snapshot);\n+\t\trecheck = ExecInsertIndexTuples(iistate->rri,\n+\t\t\t\t\t\t\t\t\t\tindex_slot,\n+\t\t\t\t\t\t\t\t\t\tiistate->estate,\n+\t\t\t\t\t\t\t\t\t\ttrue,\t/* update */\n+\t\t\t\t\t\t\t\t\t\tfalse,\t/* noDupErr */\n+\t\t\t\t\t\t\t\t\t\tNULL,\t/* specConflict */\n+\t\t\t\t\t\t\t\t\t\tNIL, /* arbiterIndexes */\n+\t\t\t\t\t\t\t\t\t\t/* onlySummarizing */\n+\t\t\t\t\t\t\t\t\t\tupdate_indexes == TU_Summarizing);\n+\t\tPopActiveSnapshot();\n+\t\tlist_free(recheck);\n+\t}\n+\n+\tpgstat_progress_incr_param(PROGRESS_CLUSTER_HEAP_TUPLES_UPDATED, 1);\n+}\n+\n+static void\n+apply_concurrent_delete(Relation rel, HeapTuple tup_target,\n+\t\t\t\t\t\tConcurrentChange *change)\n+{\n+\tItemPointerData\t\ttid_old_new_heap;\n+\tTM_Result\tres;\n+\tTM_FailureData tmfd;\n+\tSnapshot\tsnapshot = change->snapshot;\n+\n+\t/* Regarding CID, see the comment in apply_concurrent_insert(). */\n+\tAssert(snapshot->curcid != InvalidCommandId &&\n+\t\t snapshot->curcid > FirstCommandId);\n+\n+\t/* Location of the existing tuple in the new heap. */\n+\tItemPointerCopy(&tup_target->t_self, &tid_old_new_heap);\n+\n+\tres = heap_delete(rel, &tid_old_new_heap, change->xid,\n+\t\t\t\t\t snapshot->curcid - 1, InvalidSnapshot, false,\n+\t\t\t\t\t &tmfd, false,\n+\t\t\t\t\t /* wal_logical */\n+\t\t\t\t\t false);\n+\n+\tif (res != TM_Ok)\n+\t\tereport(ERROR, (errmsg(\"failed to apply concurrent DELETE\")));\n+\n+\tpgstat_progress_incr_param(PROGRESS_CLUSTER_HEAP_TUPLES_DELETED, 1);\n+}\n+\n+/*\n+ * Find the tuple to be updated or deleted.\n+ *\n+ * 'key' is a pre-initialized scan key, into which the function will put the\n+ * key values.\n+ *\n+ * 'tup_key' is a tuple containing the key values for the scan.\n+ *\n+ * On exit,'*scan_p' contains the scan descriptor used. The caller must close\n+ * it when he no longer needs the tuple returned.\n+ */\n+static HeapTuple\n+find_target_tuple(Relation rel, ScanKey key, int nkeys, HeapTuple tup_key,\n+\t\t\t\t Snapshot snapshot, IndexInsertState *iistate,\n+\t\t\t\t TupleTableSlot *ident_slot, IndexScanDesc *scan_p)\n+{\n+\tIndexScanDesc scan;\n+\tForm_pg_index ident_form;\n+\tint2vector *ident_indkey;\n+\tHeapTuple\tresult = NULL;\n+\n+\tscan = index_beginscan(rel, iistate->ident_index, snapshot,\n+\t\t\t\t\t\t nkeys, 0);\n+\t*scan_p = scan;\n+\tindex_rescan(scan, key, nkeys, NULL, 0);\n+\n+\t/* Info needed to retrieve key values from heap tuple. */\n+\tident_form = iistate->ident_index->rd_index;\n+\tident_indkey = &ident_form->indkey;\n+\n+\t/* Use the incoming tuple to finalize the scan key. */\n+\tfor (int i = 0; i < scan->numberOfKeys; i++)\n+\t{\n+\t\tScanKey\t\tentry;\n+\t\tbool\t\tisnull;\n+\t\tint16\t\tattno_heap;\n+\n+\t\tentry = &scan->keyData[i];\n+\t\tattno_heap = ident_indkey->values[i];\n+\t\tentry->sk_argument = heap_getattr(tup_key,\n+\t\t\t\t\t\t\t\t\t\t attno_heap,\n+\t\t\t\t\t\t\t\t\t\t rel->rd_att,\n+\t\t\t\t\t\t\t\t\t\t &isnull);\n+\t\tAssert(!isnull);\n+\t}\n+\tif (index_getnext_slot(scan, ForwardScanDirection, ident_slot))\n+\t{\n+\t\tbool\t\tshouldFree;\n+\n+\t\tresult = ExecFetchSlotHeapTuple(ident_slot, false, &shouldFree);\n+\t\t/* TTSOpsBufferHeapTuple has .get_heap_tuple != NULL. */\n+\t\tAssert(!shouldFree);\n+\t}\n+\n+\treturn result;\n+}\n+\n+/*\n+ * Decode and apply concurrent changes.\n+ *\n+ * Pass rel_src iff its reltoastrelid is needed.\n+ */\n+static void\n+process_concurrent_changes(LogicalDecodingContext *ctx, XLogRecPtr end_of_wal,\n+\t\t\t\t\t\t Relation rel_dst, Relation rel_src, ScanKey ident_key,\n+\t\t\t\t\t\t int ident_key_nentries, IndexInsertState *iistate)\n+{\n+\tClusterDecodingState *dstate;\n+\n+\tpgstat_progress_update_param(PROGRESS_CLUSTER_PHASE,\n+\t\t\t\t\t\t\t\t PROGRESS_CLUSTER_PHASE_CATCH_UP);\n+\n+\tdstate = (ClusterDecodingState *) ctx->output_writer_private;\n+\n+\tcluster_decode_concurrent_changes(ctx, end_of_wal);\n+\n+\tif (dstate->nchanges == 0)\n+\t\treturn;\n+\n+\tPG_TRY();\n+\t{\n+\t\t/*\n+\t\t * Make sure that TOAST values can eventually be accessed via the old\n+\t\t * relation - see comment in copy_table_data().\n+\t\t */\n+\t\tif (rel_src)\n+\t\t\trel_dst->rd_toastoid = rel_src->rd_rel->reltoastrelid;\n+\n+\t\tapply_concurrent_changes(dstate, rel_dst, ident_key,\n+\t\t\t\t\t\t\t\t ident_key_nentries, iistate);\n+\t}\n+\tPG_FINALLY();\n+\t{\n+\t\tResetClusterCurrentXids();\n+\n+\t\tif (rel_src)\n+\t\t\trel_dst->rd_toastoid = InvalidOid;\n+\t}\n+\tPG_END_TRY();\n+}\n+\n+static IndexInsertState *\n+get_index_insert_state(Relation relation, Oid ident_index_id)\n+{\n+\tEState\t *estate;\n+\tint\t\t\ti;\n+\tIndexInsertState *result;\n+\n+\tresult = (IndexInsertState *) palloc0(sizeof(IndexInsertState));\n+\testate = CreateExecutorState();\n+\tresult->econtext = GetPerTupleExprContext(estate);\n+\n+\tresult->rri = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));\n+\tInitResultRelInfo(result->rri, relation, 0, 0, 0);\n+\tExecOpenIndices(result->rri, false);\n+\n+\t/*\n+\t * Find the relcache entry of the identity index so that we spend no extra\n+\t * effort to open / close it.\n+\t */\n+\tfor (i = 0; i < result->rri->ri_NumIndices; i++)\n+\t{\n+\t\tRelation\tind_rel;\n+\n+\t\tind_rel = result->rri->ri_IndexRelationDescs[i];\n+\t\tif (ind_rel->rd_id == ident_index_id)\n+\t\t\tresult->ident_index = ind_rel;\n+\t}\n+\tif (result->ident_index == NULL)\n+\t\telog(ERROR, \"Failed to open identity index\");\n+\n+\t/* Only initialize fields needed by ExecInsertIndexTuples(). */\n+\tresult->estate = estate;\n+\n+\treturn result;\n+}\n+\n+/*\n+ * Build scan key to process logical changes.\n+ */\n+static ScanKey\n+build_identity_key(Oid ident_idx_oid, Relation rel_src, int *nentries)\n+{\n+\tRelation\tident_idx_rel;\n+\tForm_pg_index ident_idx;\n+\tint\t\t\tn,\n+\t\t\t\ti;\n+\tScanKey\t\tresult;\n+\n+\tAssert(OidIsValid(ident_idx_oid));\n+\tident_idx_rel = index_open(ident_idx_oid, AccessShareLock);\n+\tident_idx = ident_idx_rel->rd_index;\n+\tn = ident_idx->indnatts;\n+\tresult = (ScanKey) palloc(sizeof(ScanKeyData) * n);\n+\tfor (i = 0; i < n; i++)\n+\t{\n+\t\tScanKey\t\tentry;\n+\t\tint16\t\trelattno;\n+\t\tForm_pg_attribute att;\n+\t\tOid\t\t\topfamily,\n+\t\t\t\t\topcintype,\n+\t\t\t\t\topno,\n+\t\t\t\t\topcode;\n+\n+\t\tentry = &result[i];\n+\t\trelattno = ident_idx->indkey.values[i];\n+\t\tif (relattno >= 1)\n+\t\t{\n+\t\t\tTupleDesc\tdesc;\n+\n+\t\t\tdesc = rel_src->rd_att;\n+\t\t\tatt = TupleDescAttr(desc, relattno - 1);\n+\t\t}\n+\t\telse\n+\t\t\telog(ERROR, \"Unexpected attribute number %d in index\", relattno);\n+\n+\t\topfamily = ident_idx_rel->rd_opfamily[i];\n+\t\topcintype = ident_idx_rel->rd_opcintype[i];\n+\t\topno = get_opfamily_member(opfamily, opcintype, opcintype,\n+\t\t\t\t\t\t\t\t BTEqualStrategyNumber);\n+\n+\t\tif (!OidIsValid(opno))\n+\t\t\telog(ERROR, \"Failed to find = operator for type %u\", opcintype);\n+\n+\t\topcode = get_opcode(opno);\n+\t\tif (!OidIsValid(opcode))\n+\t\t\telog(ERROR, \"Failed to find = operator for operator %u\", opno);\n+\n+\t\t/* Initialize everything but argument. */\n+\t\tScanKeyInit(entry,\n+\t\t\t\t\ti + 1,\n+\t\t\t\t\tBTEqualStrategyNumber, opcode,\n+\t\t\t\t\t(Datum) NULL);\n+\t\tentry->sk_collation = att->attcollation;\n+\t}\n+\tindex_close(ident_idx_rel, AccessShareLock);\n+\n+\t*nentries = n;\n+\treturn result;\n+}\n+\n+static void\n+free_index_insert_state(IndexInsertState *iistate)\n+{\n+\tExecCloseIndices(iistate->rri);\n+\tFreeExecutorState(iistate->estate);\n+\tpfree(iistate->rri);\n+\tpfree(iistate);\n+}\n+\n+static void\n+cleanup_logical_decoding(LogicalDecodingContext *ctx)\n+{\n+\tClusterDecodingState *dstate;\n+\n+\tdstate = (ClusterDecodingState *) ctx->output_writer_private;\n+\n+\tExecDropSingleTupleTableSlot(dstate->tsslot);\n+\tFreeTupleDesc(dstate->tupdesc_change);\n+\tFreeTupleDesc(dstate->tupdesc);\n+\ttuplestore_end(dstate->tstore);\n+\n+\tFreeDecodingContext(ctx);\n+}\n+\n+/*\n+ * The final steps of rebuild_relation() for concurrent processing.\n+ *\n+ * On entry, NewHeap is locked in AccessExclusiveLock mode. OldHeap and its\n+ * clustering index (if one is passed) are still locked in a mode that allows\n+ * concurrent data changes. On exit, both tables and their indexes are closed,\n+ * but locked in AccessExclusiveLock mode.\n+ */\n+static void\n+rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,\n+\t\t\t\t\t\t\t\t Relation cl_index,\n+\t\t\t\t\t\t\t\t CatalogState\t*cat_state,\n+\t\t\t\t\t\t\t\t LogicalDecodingContext *ctx,\n+\t\t\t\t\t\t\t\t bool swap_toast_by_content,\n+\t\t\t\t\t\t\t\t TransactionId frozenXid,\n+\t\t\t\t\t\t\t\t MultiXactId cutoffMulti)\n+{\n+\tLOCKMODE\tlmode_old;\n+\tList\t*ind_oids_new;\n+\tOid\t\told_table_oid = RelationGetRelid(OldHeap);\n+\tOid\t\tnew_table_oid = RelationGetRelid(NewHeap);\n+\tList\t*ind_oids_old = RelationGetIndexList(OldHeap);\n+\tListCell\t*lc, *lc2;\n+\tchar\t\trelpersistence;\n+\tbool\t\tis_system_catalog;\n+\tOid\t\tident_idx_old, ident_idx_new;\n+\tIndexInsertState *iistate;\n+\tScanKey\t\tident_key;\n+\tint\t\tident_key_nentries;\n+\tXLogRecPtr\twal_insert_ptr, end_of_wal;\n+\tchar\t\tdummy_rec_data = '\\0';\n+\tRelReopenInfo\t*rri = NULL;\n+\tint\t\tnrel;\n+\tRelation\t*ind_refs_all, *ind_refs_p;\n+\n+\t/* Like in cluster_rel(). */\n+\tlmode_old = LOCK_CLUSTER_CONCURRENT;\n+\tAssert(CheckRelationLockedByMe(OldHeap, lmode_old, false));\n+\tAssert(cl_index == NULL ||\n+\t\t CheckRelationLockedByMe(cl_index, lmode_old, false));\n+\t/* This is expected from the caller. */\n+\tAssert(CheckRelationLockedByMe(NewHeap, AccessExclusiveLock, false));\n+\n+\tident_idx_old = RelationGetReplicaIndex(OldHeap);\n+\n+\t/*\n+\t * Unlike the exclusive case, we build new indexes for the new relation\n+\t * rather than swapping the storage and reindexing the old relation. The\n+\t * point is that the index build can take some time, so we do it before we\n+\t * get AccessExclusiveLock on the old heap and therefore we cannot swap\n+\t * the heap storage yet.\n+\t *\n+\t * index_create() will lock the new indexes using AccessExclusiveLock\n+\t * creation - no need to change that.\n+\t */\n+\tind_oids_new = build_new_indexes(NewHeap, OldHeap, ind_oids_old);\n+\n+\t/*\n+\t * Processing shouldn't start w/o valid identity index.\n+\t */\n+\tAssert(OidIsValid(ident_idx_old));\n+\n+\t/* Find \"identity index\" on the new relation. */\n+\tident_idx_new = InvalidOid;\n+\tforboth(lc, ind_oids_old, lc2, ind_oids_new)\n+\t{\n+\t\tOid\tind_old = lfirst_oid(lc);\n+\t\tOid\tind_new = lfirst_oid(lc2);\n+\n+\t\tif (ident_idx_old == ind_old)\n+\t\t{\n+\t\t\tident_idx_new = ind_new;\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\tif (!OidIsValid(ident_idx_new))\n+\t\t/*\n+\t\t * Should not happen, given our lock on the old relation.\n+\t\t */\n+\t\tereport(ERROR,\n+\t\t\t\t(errmsg(\"Identity index missing on the new relation\")));\n+\n+\t/* Executor state to update indexes. */\n+\tiistate = get_index_insert_state(NewHeap, ident_idx_new);\n+\n+\t/*\n+\t * Build scan key that we'll use to look for rows to be updated / deleted\n+\t * during logical decoding.\n+\t */\n+\tident_key = build_identity_key(ident_idx_new, OldHeap, &ident_key_nentries);\n+\n+\t/*\n+\t * Flush all WAL records inserted so far (possibly except for the last\n+\t * incomplete page, see GetInsertRecPtr), to minimize the amount of data\n+\t * we need to flush while holding exclusive lock on the source table.\n+\t */\n+\twal_insert_ptr = GetInsertRecPtr();\n+\tXLogFlush(wal_insert_ptr);\n+\tend_of_wal = GetFlushRecPtr(NULL);\n+\n+\t/*\n+\t * Apply concurrent changes first time, to minimize the time we need to\n+\t * hold AccessExclusiveLock. (Quite some amount of WAL could have been\n+\t * written during the data copying and index creation.)\n+\t */\n+\tprocess_concurrent_changes(ctx, end_of_wal, NewHeap,\n+\t\t\t\t\t\t\t swap_toast_by_content ? OldHeap : NULL,\n+\t\t\t\t\t\t\t ident_key, ident_key_nentries, iistate);\n+\n+\t/*\n+\t * Release the locks that allowed concurrent data changes, in order to\n+\t * acquire the AccessExclusiveLock.\n+\t */\n+\tnrel = 0;\n+\t/*\n+\t * We unlock the old relation (and its clustering index), but then we will\n+\t * lock the relation and *all* its indexes because we want to swap their\n+\t * storage.\n+\t *\n+\t * (NewHeap is already locked, as well as its indexes.)\n+\t */\n+\trri = palloc_array(RelReopenInfo, 1 + list_length(ind_oids_old));\n+\tinit_rel_reopen_info(&rri[nrel++], &OldHeap, InvalidOid,\n+\t\t\t\t\t\t LOCK_CLUSTER_CONCURRENT, AccessExclusiveLock);\n+\t/* References to the re-opened indexes will be stored in this array. */\n+\tind_refs_all = palloc_array(Relation, list_length(ind_oids_old));\n+\tind_refs_p = ind_refs_all;\n+\t/* The clustering index is a special case. */\n+\tif (cl_index)\n+\t{\n+\t\t*ind_refs_p = cl_index;\n+\t\tinit_rel_reopen_info(&rri[nrel], ind_refs_p, InvalidOid,\n+\t\t\t\t\t\t\t LOCK_CLUSTER_CONCURRENT, AccessExclusiveLock);\n+\t\tnrel++;\n+\t\tind_refs_p++;\n+\t}\n+\t/*\n+\t * Initialize also the entries for the other indexes (currently unlocked)\n+\t * because we will have to lock them.\n+\t */\n+\tforeach(lc, ind_oids_old)\n+\t{\n+\t\tOid\t\tind_oid;\n+\n+\t\tind_oid = lfirst_oid(lc);\n+\t\t/* Clustering index is already in the array, or there is none. */\n+\t\tif (cl_index && RelationGetRelid(cl_index) == ind_oid)\n+\t\t\tcontinue;\n+\n+\t\tAssert(nrel < (1 + list_length(ind_oids_old)));\n+\n+\t\t*ind_refs_p = NULL;\n+\t\tinit_rel_reopen_info(&rri[nrel],\n+\t\t\t\t\t\t\t /*\n+\t\t\t\t\t\t\t * In this special case we do not have the\n+\t\t\t\t\t\t\t * relcache reference, use OID instead.\n+\t\t\t\t\t\t\t */\n+\t\t\t\t\t\t\t ind_refs_p,\n+\t\t\t\t\t\t\t ind_oid,\n+\t\t\t\t\t\t\t NoLock, /* Nothing to unlock. */\n+\t\t\t\t\t\t\t AccessExclusiveLock);\n+\n+\t\tnrel++;\n+\t\tind_refs_p++;\n+\t}\n+\t/* Perform the actual unlocking and re-locking. */\n+\tunlock_and_close_relations(rri, nrel);\n+\treopen_relations(rri, nrel);\n+\n+\t/*\n+\t * In addition, lock the OldHeap's TOAST relation that we skipped for the\n+\t * CONCURRENTLY option in copy_table_data(). This lock will be needed to\n+\t * swap the relation files.\n+\t */\n+\tif (OidIsValid(OldHeap->rd_rel->reltoastrelid))\n+\t\tLockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);\n+\n+\t/*\n+\t * Check if the new indexes match the old ones, i.e. no changes occurred\n+\t * while OldHeap was unlocked.\n+\t *\n+\t * XXX It's probably not necessary to check the relation tuple descriptor\n+\t * here because the logical decoding was already active when we released\n+\t * the lock, and thus the corresponding data changes won't be lost.\n+\t * However processing of those changes might take a lot of time.\n+\t */\n+\tcheck_catalog_changes(OldHeap, cat_state);\n+\n+\t/*\n+\t * Tuples and pages of the old heap will be gone, but the heap will stay.\n+\t */\n+\tTransferPredicateLocksToHeapRelation(OldHeap);\n+\t/* The same for indexes. */\n+\tfor (int i = 0; i < (nrel - 1); i++)\n+\t{\n+\t\tRelation\tindex = ind_refs_all[i];\n+\n+\t\tTransferPredicateLocksToHeapRelation(index);\n+\n+\t\t/*\n+\t\t * References to indexes on the old relation are not needed anymore,\n+\t\t * however locks stay till the end of the transaction.\n+\t\t */\n+\t\tindex_close(index, NoLock);\n+\t}\n+\tpfree(ind_refs_all);\n+\n+\t/*\n+\t * Flush anything we see in WAL, to make sure that all changes committed\n+\t * while we were waiting for the exclusive lock are available for\n+\t * decoding. This should not be necessary if all backends had\n+\t * synchronous_commit set, but we can't rely on this setting.\n+\t *\n+\t * Unfortunately, GetInsertRecPtr() may lag behind the actual insert\n+\t * position, and GetLastImportantRecPtr() points at the start of the last\n+\t * record rather than at the end. Thus the simplest way to determine the\n+\t * insert position is to insert a dummy record and use its LSN.\n+\t *\n+\t * XXX Consider using GetLastImportantRecPtr() and adding the size of the\n+\t * last record (plus the total size of all the page headers the record\n+\t * spans)?\n+\t */\n+\tXLogBeginInsert();\n+\tXLogRegisterData(&dummy_rec_data, 1);\n+\twal_insert_ptr = XLogInsert(RM_XLOG_ID, XLOG_NOOP);\n+\tXLogFlush(wal_insert_ptr);\n+\tend_of_wal = GetFlushRecPtr(NULL);\n+\n+\t/* Apply the concurrent changes again. */\n+\tprocess_concurrent_changes(ctx, end_of_wal, NewHeap,\n+\t\t\t\t\t\t\t swap_toast_by_content ? OldHeap : NULL,\n+\t\t\t\t\t\t\t ident_key, ident_key_nentries, iistate);\n+\n+\t/* Remember info about rel before closing OldHeap */\n+\trelpersistence = OldHeap->rd_rel->relpersistence;\n+\tis_system_catalog = IsSystemRelation(OldHeap);\n+\n+\tpgstat_progress_update_param(PROGRESS_CLUSTER_PHASE,\n+\t\t\t\t\t\t\t\t PROGRESS_CLUSTER_PHASE_SWAP_REL_FILES);\n+\n+\tforboth(lc, ind_oids_old, lc2, ind_oids_new)\n+\t{\n+\t\tOid\tind_old = lfirst_oid(lc);\n+\t\tOid\tind_new = lfirst_oid(lc2);\n+\t\tOid\t\t\tmapped_tables[4];\n+\n+\t\t/* Zero out possible results from swapped_relation_files */\n+\t\tmemset(mapped_tables, 0, sizeof(mapped_tables));\n+\n+\t\tswap_relation_files(ind_old, ind_new,\n+\t\t\t\t\t\t\t(old_table_oid == RelationRelationId),\n+\t\t\t\t\t\t\tswap_toast_by_content,\n+\t\t\t\t\t\t\ttrue,\n+\t\t\t\t\t\t\tInvalidTransactionId,\n+\t\t\t\t\t\t\tInvalidMultiXactId,\n+\t\t\t\t\t\t\tmapped_tables);\n+\n+#ifdef USE_ASSERT_CHECKING\n+\t\t/*\n+\t\t * Concurrent processing is not supported for system relations, so\n+\t\t * there should be no mapped tables.\n+\t\t */\n+\t\tfor (int i = 0; i < 4; i++)\n+\t\t\tAssert(mapped_tables[i] == 0);\n+#endif\n+\t}\n+\n+\t/* The new indexes must be visible for deletion. */\n+\tCommandCounterIncrement();\n+\n+\t/* Close the old heap but keep lock until transaction commit. */\n+\ttable_close(OldHeap, NoLock);\n+\t/* Close the new heap. (We didn't have to open its indexes). */\n+\ttable_close(NewHeap, NoLock);\n+\n+\t/* Cleanup what we don't need anymore. (And close the identity index.) */\n+\tpfree(ident_key);\n+\tfree_index_insert_state(iistate);\n+\n+\t/*\n+\t * Swap the relations and their TOAST relations and TOAST indexes. This\n+\t * also drops the new relation and its indexes.\n+\t *\n+\t * (System catalogs are currently not supported.)\n+\t */\n+\tAssert(!is_system_catalog);\n+\tfinish_heap_swap(old_table_oid, new_table_oid,\n+\t\t\t\t\t is_system_catalog,\n+\t\t\t\t\t swap_toast_by_content,\n+\t\t\t\t\t false, true, false,\n+\t\t\t\t\t frozenXid, cutoffMulti,\n+\t\t\t\t\t relpersistence);\n+\n+\tpfree(rri);\n+}\n+\n+/*\n+ * Build indexes on NewHeap according to those on OldHeap.\n+ *\n+ * OldIndexes is the list of index OIDs on OldHeap.\n+ *\n+ * A list of OIDs of the corresponding indexes created on NewHeap is\n+ * returned. The order of items does match, so we can use these arrays to swap\n+ * index storage.\n+ */\n+static List *\n+build_new_indexes(Relation NewHeap, Relation OldHeap, List *OldIndexes)\n+{\n+\tStringInfo\tind_name;\n+\tListCell\t*lc;\n+\tList\t *result = NIL;\n+\n+\tpgstat_progress_update_param(PROGRESS_CLUSTER_PHASE,\n+\t\t\t\t\t\t\t\t PROGRESS_CLUSTER_PHASE_REBUILD_INDEX);\n+\n+\tind_name = makeStringInfo();\n+\n+\tforeach(lc, OldIndexes)\n+\t{\n+\t\tOid\t\t\tind_oid,\n+\t\t\t\t\tind_oid_new,\n+\t\t\t\t\ttbsp_oid;\n+\t\tRelation\tind;\n+\t\tIndexInfo *ind_info;\n+\t\tint\t\t\ti,\n+\t\t\t\t\theap_col_id;\n+\t\tList\t *colnames;\n+\t\tint16\t\tindnatts;\n+\t\tOid\t\t *collations,\n+\t\t\t\t *opclasses;\n+\t\tHeapTuple\ttup;\n+\t\tbool\t\tisnull;\n+\t\tDatum\t\td;\n+\t\toidvector *oidvec;\n+\t\tint2vector *int2vec;\n+\t\tsize_t\t\toid_arr_size;\n+\t\tsize_t\t\tint2_arr_size;\n+\t\tint16\t *indoptions;\n+\t\ttext\t *reloptions = NULL;\n+\t\tbits16\t\tflags;\n+\t\tDatum\t\t*opclassOptions;\n+\t\tNullableDatum *stattargets;\n+\n+\t\tind_oid = lfirst_oid(lc);\n+\t\tind = index_open(ind_oid, AccessShareLock);\n+\t\tind_info = BuildIndexInfo(ind);\n+\n+\t\ttbsp_oid = ind->rd_rel->reltablespace;\n+\t\t/*\n+\t\t * Index name really doesn't matter, we'll eventually use only their\n+\t\t * storage. Just make them unique within the table.\n+\t\t */\n+\t\tresetStringInfo(ind_name);\n+\t\tappendStringInfo(ind_name, \"ind_%d\",\n+\t\t\t\t\t\t list_cell_number(OldIndexes, lc));\n+\n+\t\tflags = 0;\n+\t\tif (ind->rd_index->indisprimary)\n+\t\t\tflags |= INDEX_CREATE_IS_PRIMARY;\n+\n+\t\tcolnames = NIL;\n+\t\tindnatts = ind->rd_index->indnatts;\n+\t\toid_arr_size = sizeof(Oid) * indnatts;\n+\t\tint2_arr_size = sizeof(int16) * indnatts;\n+\n+\t\tcollations = (Oid *) palloc(oid_arr_size);\n+\t\tfor (i = 0; i < indnatts; i++)\n+\t\t{\n+\t\t\tchar\t *colname;\n+\n+\t\t\theap_col_id = ind->rd_index->indkey.values[i];\n+\t\t\tif (heap_col_id > 0)\n+\t\t\t{\n+\t\t\t\tForm_pg_attribute att;\n+\n+\t\t\t\t/* Normal attribute. */\n+\t\t\t\tatt = TupleDescAttr(OldHeap->rd_att, heap_col_id - 1);\n+\t\t\t\tcolname = pstrdup(NameStr(att->attname));\n+\t\t\t\tcollations[i] = att->attcollation;\n+\t\t\t}\n+\t\t\telse if (heap_col_id == 0)\n+\t\t\t{\n+\t\t\t\tHeapTuple\ttuple;\n+\t\t\t\tForm_pg_attribute att;\n+\n+\t\t\t\t/*\n+\t\t\t\t * Expression column is not present in relcache. What we need\n+\t\t\t\t * here is an attribute of the *index* relation.\n+\t\t\t\t */\n+\t\t\t\ttuple = SearchSysCache2(ATTNUM,\n+\t\t\t\t\t\t\t\t\t\tObjectIdGetDatum(ind_oid),\n+\t\t\t\t\t\t\t\t\t\tInt16GetDatum(i + 1));\n+\t\t\t\tif (!HeapTupleIsValid(tuple))\n+\t\t\t\t\telog(ERROR,\n+\t\t\t\t\t\t \"cache lookup failed for attribute %d of relation %u\",\n+\t\t\t\t\t\t i + 1, ind_oid);\n+\t\t\t\tatt = (Form_pg_attribute) GETSTRUCT(tuple);\n+\t\t\t\tcolname = pstrdup(NameStr(att->attname));\n+\t\t\t\tcollations[i] = att->attcollation;\n+\t\t\t\tReleaseSysCache(tuple);\n+\t\t\t}\n+\t\t\telse\n+\t\t\t\telog(ERROR, \"Unexpected column number: %d\",\n+\t\t\t\t\t heap_col_id);\n+\n+\t\t\tcolnames = lappend(colnames, colname);\n+\t\t}\n+\n+\t\t/*\n+\t\t * Special effort needed for variable length attributes of\n+\t\t * Form_pg_index.\n+\t\t */\n+\t\ttup = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(ind_oid));\n+\t\tif (!HeapTupleIsValid(tup))\n+\t\t\telog(ERROR, \"cache lookup failed for index %u\", ind_oid);\n+\t\td = SysCacheGetAttr(INDEXRELID, tup, Anum_pg_index_indclass, &isnull);\n+\t\tAssert(!isnull);\n+\t\toidvec = (oidvector *) DatumGetPointer(d);\n+\t\topclasses = (Oid *) palloc(oid_arr_size);\n+\t\tmemcpy(opclasses, oidvec->values, oid_arr_size);\n+\n+\t\td = SysCacheGetAttr(INDEXRELID, tup, Anum_pg_index_indoption,\n+\t\t\t\t\t\t\t&isnull);\n+\t\tAssert(!isnull);\n+\t\tint2vec = (int2vector *) DatumGetPointer(d);\n+\t\tindoptions = (int16 *) palloc(int2_arr_size);\n+\t\tmemcpy(indoptions, int2vec->values, int2_arr_size);\n+\t\tReleaseSysCache(tup);\n+\n+\t\ttup = SearchSysCache1(RELOID, ObjectIdGetDatum(ind_oid));\n+\t\tif (!HeapTupleIsValid(tup))\n+\t\t\telog(ERROR, \"cache lookup failed for index relation %u\", ind_oid);\n+\t\td = SysCacheGetAttr(RELOID, tup, Anum_pg_class_reloptions, &isnull);\n+\t\treloptions = !isnull ? DatumGetTextPCopy(d) : NULL;\n+\t\tReleaseSysCache(tup);\n+\n+\t\topclassOptions = palloc0(sizeof(Datum) * ind_info->ii_NumIndexAttrs);\n+\t\tfor (i = 0; i < ind_info->ii_NumIndexAttrs; i++)\n+\t\t\topclassOptions[i] = get_attoptions(ind_oid, i + 1);\n+\n+\t\tstattargets = get_index_stattargets(ind_oid, ind_info);\n+\n+\t\t/*\n+\t\t * Neither parentIndexRelid nor parentConstraintId needs to be passed\n+\t\t * since the new catalog entries (pg_constraint, pg_inherits) would\n+\t\t * eventually be dropped. Therefore there's no need to record valid\n+\t\t * dependency on parents.\n+\t\t */\n+\t\tind_oid_new = index_create(NewHeap,\n+\t\t\t\t\t\t\t\t ind_name->data,\n+\t\t\t\t\t\t\t\t InvalidOid,\n+\t\t\t\t\t\t\t\t InvalidOid,\t/* parentIndexRelid */\n+\t\t\t\t\t\t\t\t InvalidOid,\t/* parentConstraintId */\n+\t\t\t\t\t\t\t\t InvalidOid,\n+\t\t\t\t\t\t\t\t ind_info,\n+\t\t\t\t\t\t\t\t colnames,\n+\t\t\t\t\t\t\t\t ind->rd_rel->relam,\n+\t\t\t\t\t\t\t\t tbsp_oid,\n+\t\t\t\t\t\t\t\t collations,\n+\t\t\t\t\t\t\t\t opclasses,\n+\t\t\t\t\t\t\t\t opclassOptions,\n+\t\t\t\t\t\t\t\t indoptions,\n+\t\t\t\t\t\t\t\t stattargets,\n+\t\t\t\t\t\t\t\t PointerGetDatum(reloptions),\n+\t\t\t\t\t\t\t\t flags,\t/* flags */\n+\t\t\t\t\t\t\t\t 0,\t/* constr_flags */\n+\t\t\t\t\t\t\t\t false,\t/* allow_system_table_mods */\n+\t\t\t\t\t\t\t\t false,\t/* is_internal */\n+\t\t\t\t\t\t\t\t NULL /* constraintId */\n+\t\t\t);\n+\t\tresult = lappend_oid(result, ind_oid_new);\n+\n+\t\tindex_close(ind, AccessShareLock);\n+\t\tlist_free_deep(colnames);\n+\t\tpfree(collations);\n+\t\tpfree(opclasses);\n+\t\tpfree(indoptions);\n+\t\tif (reloptions)\n+\t\t\tpfree(reloptions);\n+\t}\n+\n+\treturn result;\n+}\n+\n+static void\n+init_rel_reopen_info(RelReopenInfo *rri, Relation *rel_p, Oid relid,\n+\t\t\t\t\t LOCKMODE lockmode_orig, LOCKMODE lockmode_new)\n+{\n+\trri->rel_p = rel_p;\n+\trri->relid = relid;\n+\trri->lockmode_orig = lockmode_orig;\n+\trri->lockmode_new = lockmode_new;\n+}\n+\n+/*\n+ * Unlock and close relations specified by items of the 'rels' array. 'nrels'\n+ * is the number of items.\n+ *\n+ * Information needed to (re)open the relations (or to issue meaningful ERROR)\n+ * is added to the array items.\n+ */\n+static void\n+unlock_and_close_relations(RelReopenInfo *rels, int nrel)\n+{\n+\tint\t\ti;\n+\tRelReopenInfo\t*rri;\n+\n+\t/*\n+\t * First, retrieve the information that we will need for re-opening.\n+\t *\n+\t * We could close (and unlock) each relation as soon as we have gathered\n+\t * the related information, but then we would have to be careful not to\n+\t * unlock the table until we have the info on all its indexes. (Once we\n+\t * unlock the table, any index can be dropped, and thus we can fail to get\n+\t * the name we want to report if re-opening fails.) It seem simpler to\n+\t * separate the work into two iterations.\n+\t */\n+\tfor (i = 0; i < nrel; i++)\n+\t{\n+\t\tRelation\trel;\n+\n+\t\trri = &rels[i];\n+\t\trel = *rri->rel_p;\n+\n+\t\tif (rel)\n+\t\t{\n+\t\t\tAssert(CheckRelationLockedByMe(rel, rri->lockmode_orig, false));\n+\t\t\tAssert(!OidIsValid(rri->relid));\n+\n+\t\t\trri->relid = RelationGetRelid(rel);\n+\t\t\trri->relkind = rel->rd_rel->relkind;\n+\t\t\trri->relname = pstrdup(RelationGetRelationName(rel));\n+\t\t}\n+\t\telse\n+\t\t{\n+\t\t\tAssert(OidIsValid(rri->relid));\n+\n+\t\t\trri->relname = get_rel_name(rri->relid);\n+\t\t\trri->relkind = get_rel_relkind(rri->relid);\n+\t\t}\n+\t}\n+\n+\t/* Second, close the relations. */\n+\tfor (i = 0; i < nrel; i++)\n+\t{\n+\t\tRelation\trel;\n+\n+\t\trri = &rels[i];\n+\t\trel = *rri->rel_p;\n+\n+\t\t/* Close the relation if the caller passed one. */\n+\t\tif (rel)\n+\t\t{\n+\t\t\tif (rri->relkind == RELKIND_RELATION)\n+\t\t\t\ttable_close(rel, rri->lockmode_orig);\n+\t\t\telse\n+\t\t\t{\n+\t\t\t\tAssert(rri->relkind == RELKIND_INDEX);\n+\n+\t\t\t\tindex_close(rel, rri->lockmode_orig);\n+\t\t\t}\n+\t\t}\n+\t}\n+}\n+\n+/*\n+ * Re-open the relations closed previously by unlock_and_close_relations().\n+ */\n+static void\n+reopen_relations(RelReopenInfo *rels, int nrel)\n+{\n+\tfor (int i = 0; i < nrel; i++)\n+\t{\n+\t\tRelReopenInfo\t*rri = &rels[i];\n+\t\tRelation\trel;\n+\n+\t\tif (rri->relkind == RELKIND_RELATION)\n+\t\t{\n+\t\t\trel = try_table_open(rri->relid, rri->lockmode_new);\n+\t\t}\n+\t\telse\n+\t\t{\n+\t\t\tAssert(rri->relkind == RELKIND_INDEX);\n+\n+\t\t\trel = try_index_open(rri->relid, rri->lockmode_new);\n+\t\t}\n+\n+\t\tif (rel == NULL)\n+\t\t{\n+\t\t\tconst char\t*kind_str;\n+\n+\t\t\tkind_str = (rri->relkind == RELKIND_RELATION) ? \"table\" : \"index\";\n+\t\t\tereport(ERROR,\n+\t\t\t\t\t(errmsg(\"could not open \\%s \\\"%s\\\"\", kind_str,\n+\t\t\t\t\t\t\trri->relname),\n+\t\t\t\t\t errhint(\"the %s could have been dropped by another transaction\",\n+\t\t\t\t\t\t\t kind_str)));\n+\t\t}\n+\t\t*rri->rel_p = rel;\n+\n+\t\tpfree(rri->relname);\n+\t}\n+}\ndiff --git a/src/backend/commands/matview.c b/src/backend/commands/matview.c\nindex 488ca950d9..af1945e1ed 100644\n--- a/src/backend/commands/matview.c\n+++ b/src/backend/commands/matview.c\n@@ -873,7 +873,7 @@ refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner,\n static void\n refresh_by_heap_swap(Oid matviewOid, Oid OIDNewHeap, char relpersistence)\n {\n-\tfinish_heap_swap(matviewOid, OIDNewHeap, false, false, true, true,\n+\tfinish_heap_swap(matviewOid, OIDNewHeap, false, false, true, true, true,\n \t\t\t\t\t RecentXmin, ReadNextMultiXactId(), relpersistence);\n }\n \ndiff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c\nindex 5d6151dad1..13f32ede92 100644\n--- a/src/backend/commands/tablecmds.c\n+++ b/src/backend/commands/tablecmds.c\n@@ -4395,6 +4395,16 @@ AlterTableInternal(Oid relid, List *cmds, bool recurse)\n \n \trel = relation_open(relid, lockmode);\n \n+\t/*\n+\t * If lockmode allows, check if VACUUM FULL / CLUSTER CONCURRENTLY is in\n+\t * progress. If lockmode is too weak, cluster_rel() should detect\n+\t * incompatible DDLs executed by us.\n+\t *\n+\t * XXX We might skip the changes for DDLs which do not change the tuple\n+\t * descriptor.\n+\t */\n+\tcheck_for_concurrent_cluster(relid, lockmode);\n+\n \tEventTriggerAlterTableRelid(relid);\n \n \tATController(NULL, rel, cmds, recurse, lockmode, NULL);\n@@ -5861,6 +5871,7 @@ ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode,\n \t\t\tfinish_heap_swap(tab->relid, OIDNewHeap,\n \t\t\t\t\t\t\t false, false, true,\n \t\t\t\t\t\t\t !OidIsValid(tab->newTableSpace),\n+\t\t\t\t\t\t\t true,\n \t\t\t\t\t\t\t RecentXmin,\n \t\t\t\t\t\t\t ReadNextMultiXactId(),\n \t\t\t\t\t\t\t persistence);\ndiff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c\nindex 0bd000acc5..529c46c186 100644\n--- a/src/backend/commands/vacuum.c\n+++ b/src/backend/commands/vacuum.c\n@@ -112,7 +112,8 @@ static void vac_truncate_clog(TransactionId frozenXID,\n \t\t\t\t\t\t\t TransactionId lastSaneFrozenXid,\n \t\t\t\t\t\t\t MultiXactId lastSaneMinMulti);\n static bool vacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params,\n-\t\t\t\t\t BufferAccessStrategy bstrategy);\n+\t\t\t\t\t BufferAccessStrategy bstrategy, bool isTopLevel,\n+\t\t\t\t\t bool whole_database);\n static double compute_parallel_delay(void);\n static VacOptValue get_vacoptval_from_boolean(DefElem *def);\n static bool vac_tid_reaped(ItemPointer itemptr, void *state);\n@@ -153,6 +154,7 @@ ExecVacuum(ParseState *pstate, VacuumStmt *vacstmt, bool isTopLevel)\n \tbool\t\tanalyze = false;\n \tbool\t\tfreeze = false;\n \tbool\t\tfull = false;\n+\tbool\t\tconcurrent = false;\n \tbool\t\tdisable_page_skipping = false;\n \tbool\t\tprocess_main = true;\n \tbool\t\tprocess_toast = true;\n@@ -226,6 +228,8 @@ ExecVacuum(ParseState *pstate, VacuumStmt *vacstmt, bool isTopLevel)\n \t\t\tfreeze = defGetBoolean(opt);\n \t\telse if (strcmp(opt->defname, \"full\") == 0)\n \t\t\tfull = defGetBoolean(opt);\n+\t\telse if (strcmp(opt->defname, \"concurrently\") == 0)\n+\t\t\tconcurrent = defGetBoolean(opt);\n \t\telse if (strcmp(opt->defname, \"disable_page_skipping\") == 0)\n \t\t\tdisable_page_skipping = defGetBoolean(opt);\n \t\telse if (strcmp(opt->defname, \"index_cleanup\") == 0)\n@@ -300,7 +304,7 @@ ExecVacuum(ParseState *pstate, VacuumStmt *vacstmt, bool isTopLevel)\n \t\t(skip_locked ? VACOPT_SKIP_LOCKED : 0) |\n \t\t(analyze ? VACOPT_ANALYZE : 0) |\n \t\t(freeze ? VACOPT_FREEZE : 0) |\n-\t\t(full ? VACOPT_FULL : 0) |\n+\t\t(full ? (concurrent ? VACOPT_FULL_CONCURRENT : VACOPT_FULL_EXCLUSIVE) : 0) |\n \t\t(disable_page_skipping ? VACOPT_DISABLE_PAGE_SKIPPING : 0) |\n \t\t(process_main ? VACOPT_PROCESS_MAIN : 0) |\n \t\t(process_toast ? VACOPT_PROCESS_TOAST : 0) |\n@@ -380,6 +384,12 @@ ExecVacuum(ParseState *pstate, VacuumStmt *vacstmt, bool isTopLevel)\n \t\t\t\t\t errmsg(\"ONLY_DATABASE_STATS cannot be specified with other VACUUM options\")));\n \t}\n \n+\t/* This problem cannot be identified from the options. */\n+\tif (concurrent && !full)\n+\t\tereport(ERROR,\n+\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n+\t\t\t\t errmsg(\"CONCURRENTLY can only be specified with VACUUM FULL\")));\n+\n \t/*\n \t * All freeze ages are zero if the FREEZE option is given; otherwise pass\n \t * them as -1 which means to use the default values.\n@@ -483,6 +493,7 @@ vacuum(List *relations, VacuumParams *params, BufferAccessStrategy bstrategy,\n \tconst char *stmttype;\n \tvolatile bool in_outer_xact,\n \t\t\t\tuse_own_xacts;\n+\tbool\t\twhole_database = false;\n \n \tAssert(params != NULL);\n \n@@ -543,7 +554,15 @@ vacuum(List *relations, VacuumParams *params, BufferAccessStrategy bstrategy,\n \t\trelations = newrels;\n \t}\n \telse\n+\t{\n \t\trelations = get_all_vacuum_rels(vac_context, params->options);\n+\t\t/*\n+\t\t * If all tables should be processed, the CONCURRENTLY option implies\n+\t\t * that we should skip system relations rather than raising ERRORs.\n+\t\t */\n+\t\tif (params->options & VACOPT_FULL_CONCURRENT)\n+\t\t\twhole_database = true;\n+\t}\n \n \t/*\n \t * Decide whether we need to start/commit our own transactions.\n@@ -619,7 +638,8 @@ vacuum(List *relations, VacuumParams *params, BufferAccessStrategy bstrategy,\n \n \t\t\tif (params->options & VACOPT_VACUUM)\n \t\t\t{\n-\t\t\t\tif (!vacuum_rel(vrel->oid, vrel->relation, params, bstrategy))\n+\t\t\t\tif (!vacuum_rel(vrel->oid, vrel->relation, params, bstrategy,\n+\t\t\t\t\t\t\t\tisTopLevel, whole_database))\n \t\t\t\t\tcontinue;\n \t\t\t}\n \n@@ -1932,10 +1952,14 @@ vac_truncate_clog(TransactionId frozenXID,\n /*\n *\tvacuum_rel() -- vacuum one heap relation\n *\n- *\t\trelid identifies the relation to vacuum. If relation is supplied,\n- *\t\tuse the name therein for reporting any failure to open/lock the rel;\n- *\t\tdo not use it once we've successfully opened the rel, since it might\n- *\t\tbe stale.\n+ *\t\trelid identifies the relation to vacuum. If relation is supplied, use\n+ *\t\tthe name therein for reporting any failure to open/lock the rel; do\n+ *\t\tnot use it once we've successfully opened the rel, since it might be\n+ *\t\tstale.\n+ *\n+ *\t\tIf whole_database is true, we are processing all the relations of the\n+ *\t\tcurrent database. In that case we might need to silently skip\n+ *\t\trelations which could otherwise cause ERROR.\n *\n *\t\tReturns true if it's okay to proceed with a requested ANALYZE\n *\t\toperation on this table.\n@@ -1950,7 +1974,8 @@ vac_truncate_clog(TransactionId frozenXID,\n */\n static bool\n vacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params,\n-\t\t BufferAccessStrategy bstrategy)\n+\t\t BufferAccessStrategy bstrategy, bool isTopLevel,\n+\t\t bool whole_database)\n {\n \tLOCKMODE\tlmode;\n \tRelation\trel;\n@@ -2013,10 +2038,11 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params,\n \n \t/*\n \t * Determine the type of lock we want --- hard exclusive lock for a FULL\n-\t * vacuum, but just ShareUpdateExclusiveLock for concurrent vacuum. Either\n-\t * way, we can be sure that no other backend is vacuuming the same table.\n+\t * exclusive vacuum, but a weaker lock (ShareUpdateExclusiveLock) for\n+\t * concurrent vacuum. Either way, we can be sure that no other backend is\n+\t * vacuuming the same table.\n \t */\n-\tlmode = (params->options & VACOPT_FULL) ?\n+\tlmode = (params->options & VACOPT_FULL_EXCLUSIVE) ?\n \t\tAccessExclusiveLock : ShareUpdateExclusiveLock;\n \n \t/* open the relation and get the appropriate lock on it */\n@@ -2031,6 +2057,39 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params,\n \t\treturn false;\n \t}\n \n+\t/*\n+\t * Leave if the CONCURRENTLY option was passed, but the relation is not\n+\t * suitable for that. Note that we only skip such relations if the user\n+\t * wants to vacuum the whole database. In contrast, if he specified\n+\t * inappropriate relation(s) explicitly, the command will end up with\n+\t * ERROR.\n+\t */\n+\tif (whole_database && (params->options & VACOPT_FULL_CONCURRENT) &&\n+\t\t!check_relation_is_clusterable_concurrently(rel, DEBUG1,\n+\t\t\t\t\t\t\t\t\t\t\t\t\t\"VACUUM (FULL, CONCURRENTLY)\"))\n+\t{\n+\t\trelation_close(rel, lmode);\n+\t\tPopActiveSnapshot();\n+\t\tCommitTransactionCommand();\n+\t\treturn false;\n+\t}\n+\n+\t/*\n+\t * Skip the relation if VACUUM FULL / CLUSTER CONCURRENTLY is in progress\n+\t * as it will drop the current storage of the relation.\n+\t *\n+\t * This check should not take place until we have a lock that prevents\n+\t * another backend from starting VACUUM FULL / CLUSTER CONCURRENTLY later.\n+\t */\n+\tAssert(lmode >= LOCK_CLUSTER_CONCURRENT);\n+\tif (is_concurrent_cluster_in_progress(relid))\n+\t{\n+\t\trelation_close(rel, lmode);\n+\t\tPopActiveSnapshot();\n+\t\tCommitTransactionCommand();\n+\t\treturn false;\n+\t}\n+\n \t/*\n \t * When recursing to a TOAST table, check privileges on the parent. NB:\n \t * This is only safe to do because we hold a session lock on the main\n@@ -2104,19 +2163,6 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params,\n \t\treturn true;\n \t}\n \n-\t/*\n-\t * Get a session-level lock too. This will protect our access to the\n-\t * relation across multiple transactions, so that we can vacuum the\n-\t * relation's TOAST table (if any) secure in the knowledge that no one is\n-\t * deleting the parent relation.\n-\t *\n-\t * NOTE: this cannot block, even if someone else is waiting for access,\n-\t * because the lock manager knows that both lock requests are from the\n-\t * same process.\n-\t */\n-\tlockrelid = rel->rd_lockInfo.lockRelId;\n-\tLockRelationIdForSession(&lockrelid, lmode);\n-\n \t/*\n \t * Set index_cleanup option based on index_cleanup reloption if it wasn't\n \t * specified in VACUUM command, or when running in an autovacuum worker\n@@ -2169,6 +2215,30 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params,\n \telse\n \t\ttoast_relid = InvalidOid;\n \n+\t/*\n+\t * Get a session-level lock too. This will protect our access to the\n+\t * relation across multiple transactions, so that we can vacuum the\n+\t * relation's TOAST table (if any) secure in the knowledge that no one is\n+\t * deleting the parent relation.\n+\t *\n+\t * NOTE: this cannot block, even if someone else is waiting for access,\n+\t * because the lock manager knows that both lock requests are from the\n+\t * same process.\n+\t */\n+\tif (OidIsValid(toast_relid))\n+\t{\n+\t\t/*\n+\t\t * You might worry that, in the VACUUM (FULL, CONCURRENTLY) case,\n+\t\t * cluster_rel() needs to release all the locks on the relation at\n+\t\t * some point, but this session lock makes it impossible. In fact,\n+\t\t * cluster_rel() will will eventually be called for the TOAST relation\n+\t\t * and raise ERROR because, in the concurrent mode, it cannot process\n+\t\t * TOAST relation alone anyway.\n+\t\t */\n+\t\tlockrelid = rel->rd_lockInfo.lockRelId;\n+\t\tLockRelationIdForSession(&lockrelid, lmode);\n+\t}\n+\n \t/*\n \t * Switch to the table owner's userid, so that any index functions are run\n \t * as that user. Also lock down security-restricted operations and\n@@ -2196,11 +2266,22 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params,\n \t\t{\n \t\t\tClusterParams cluster_params = {0};\n \n+\t\t\t/*\n+\t\t\t * Invalid toast_relid means that there is no session lock on the\n+\t\t\t * relation. Such a lock would be a problem because it would\n+\t\t\t * prevent cluster_rel() from releasing all locks when it tries to\n+\t\t\t * get AccessExclusiveLock.\n+\t\t\t */\n+\t\t\tAssert(!OidIsValid(toast_relid));\n+\n \t\t\tif ((params->options & VACOPT_VERBOSE) != 0)\n \t\t\t\tcluster_params.options |= CLUOPT_VERBOSE;\n \n+\t\t\tif ((params->options & VACOPT_FULL_CONCURRENT) != 0)\n+\t\t\t\tcluster_params.options |= CLUOPT_CONCURRENT;\n+\n \t\t\t/* VACUUM FULL is now a variant of CLUSTER; see cluster.c */\n-\t\t\tcluster_rel(rel, InvalidOid, &cluster_params);\n+\t\t\tcluster_rel(rel, InvalidOid, &cluster_params, isTopLevel);\n \n \t\t\t/*\n \t\t\t * cluster_rel() should have closed the relation, lock is kept\n@@ -2249,13 +2330,15 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params,\n \t\ttoast_vacuum_params.options |= VACOPT_PROCESS_MAIN;\n \t\ttoast_vacuum_params.toast_parent = relid;\n \n-\t\tvacuum_rel(toast_relid, NULL, &toast_vacuum_params, bstrategy);\n+\t\tvacuum_rel(toast_relid, NULL, &toast_vacuum_params, bstrategy,\n+\t\t\t\t isTopLevel, whole_database);\n \t}\n \n \t/*\n \t * Now release the session-level lock on the main table.\n \t */\n-\tUnlockRelationIdForSession(&lockrelid, lmode);\n+\tif (OidIsValid(toast_relid))\n+\t\tUnlockRelationIdForSession(&lockrelid, lmode);\n \n \t/* Report that we really did it. */\n \treturn true;\ndiff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c\nindex d687ceee33..066d96dea2 100644\n--- a/src/backend/replication/logical/decode.c\n+++ b/src/backend/replication/logical/decode.c\n@@ -467,6 +467,57 @@ heap_decode(LogicalDecodingContext *ctx, XLogRecordBuffer *buf)\n \tTransactionId xid = XLogRecGetXid(buf->record);\n \tSnapBuild *builder = ctx->snapshot_builder;\n \n+\t/*\n+\t * If the change is not intended for logical decoding, do not even\n+\t * establish transaction for it. This is particularly important if the\n+\t * record was generated by CLUSTER CONCURRENTLY because this command uses\n+\t * the original XID when doing changes in the new storage. The decoding\n+\t * subsystem probably does not expect to see the same transaction multiple\n+\t * times.\n+\t */\n+\tswitch (info)\n+\t{\n+\t\tcase XLOG_HEAP_INSERT:\n+\t\t{\n+\t\t\txl_heap_insert\t*rec;\n+\n+\t\t\trec = (xl_heap_insert *) XLogRecGetData(buf->record);\n+\t\t\t/*\n+\t\t\t * (This does happen when raw_heap_insert marks the TOAST record\n+\t\t\t * as HEAP_INSERT_NO_LOGICAL).\n+\t\t\t */\n+\t\t\tif ((rec->flags & XLH_INSERT_CONTAINS_NEW_TUPLE) == 0)\n+\t\t\t\treturn;\n+\n+\t\t\tbreak;\n+\t\t}\n+\n+\t\tcase XLOG_HEAP_HOT_UPDATE:\n+\t\tcase XLOG_HEAP_UPDATE:\n+\t\t{\n+\t\t\txl_heap_update\t*rec;\n+\n+\t\t\trec = (xl_heap_update *) XLogRecGetData(buf->record);\n+\t\t\tif ((rec->flags &\n+\t\t\t\t (XLH_UPDATE_CONTAINS_NEW_TUPLE |\n+\t\t\t\t XLH_UPDATE_CONTAINS_OLD_TUPLE |\n+\t\t\t\t XLH_UPDATE_CONTAINS_OLD_KEY)) == 0)\n+\t\t\t\treturn;\n+\n+\t\t\tbreak;\n+\t\t}\n+\n+\t\tcase XLOG_HEAP_DELETE:\n+\t\t{\n+\t\t\txl_heap_delete\t*rec;\n+\n+\t\t\trec = (xl_heap_delete *) XLogRecGetData(buf->record);\n+\t\t\tif (rec->flags & XLH_DELETE_NO_LOGICAL)\n+\t\t\t\treturn;\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\n \tReorderBufferProcessXid(ctx->reorder, xid, buf->origptr);\n \n \t/*\n@@ -903,13 +954,6 @@ DecodeInsert(LogicalDecodingContext *ctx, XLogRecordBuffer *buf)\n \n \txlrec = (xl_heap_insert *) XLogRecGetData(r);\n \n-\t/*\n-\t * Ignore insert records without new tuples (this does happen when\n-\t * raw_heap_insert marks the TOAST record as HEAP_INSERT_NO_LOGICAL).\n-\t */\n-\tif (!(xlrec->flags & XLH_INSERT_CONTAINS_NEW_TUPLE))\n-\t\treturn;\n-\n \t/* only interested in our database */\n \tXLogRecGetBlockTag(r, 0, &target_locator, NULL, NULL);\n \tif (target_locator.dbOid != ctx->slot->data.database)\ndiff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c\nindex e37e22f441..ed15a0b175 100644\n--- a/src/backend/replication/logical/snapbuild.c\n+++ b/src/backend/replication/logical/snapbuild.c\n@@ -286,7 +286,7 @@ static bool ExportInProgress = false;\n static void SnapBuildPurgeOlderTxn(SnapBuild *builder);\n \n /* snapshot building/manipulation/distribution functions */\n-static Snapshot SnapBuildBuildSnapshot(SnapBuild *builder);\n+static Snapshot SnapBuildBuildSnapshot(SnapBuild *builder, XLogRecPtr lsn);\n \n static void SnapBuildFreeSnapshot(Snapshot snap);\n \n@@ -481,12 +481,17 @@ SnapBuildSnapDecRefcount(Snapshot snap)\n * Build a new snapshot, based on currently committed catalog-modifying\n * transactions.\n *\n+ * 'lsn' is the location of the commit record (of a catalog-changing\n+ * transaction) that triggered creation of the snapshot. Pass\n+ * InvalidXLogRecPtr for the transaction base snapshot or if it the user of\n+ * the snapshot should not need the LSN.\n+ *\n * In-progress transactions with catalog access are *not* allowed to modify\n * these snapshots; they have to copy them and fill in appropriate ->curcid\n * and ->subxip/subxcnt values.\n */\n static Snapshot\n-SnapBuildBuildSnapshot(SnapBuild *builder)\n+SnapBuildBuildSnapshot(SnapBuild *builder, XLogRecPtr lsn)\n {\n \tSnapshot\tsnapshot;\n \tSize\t\tssize;\n@@ -554,6 +559,7 @@ SnapBuildBuildSnapshot(SnapBuild *builder)\n \tsnapshot->active_count = 0;\n \tsnapshot->regd_count = 0;\n \tsnapshot->snapXactCompletionCount = 0;\n+\tsnapshot->lsn = lsn;\n \n \treturn snapshot;\n }\n@@ -569,10 +575,7 @@ Snapshot\n SnapBuildInitialSnapshot(SnapBuild *builder)\n {\n \tSnapshot\tsnap;\n-\tTransactionId xid;\n \tTransactionId safeXid;\n-\tTransactionId *newxip;\n-\tint\t\t\tnewxcnt = 0;\n \n \tAssert(XactIsoLevel == XACT_REPEATABLE_READ);\n \tAssert(builder->building_full_snapshot);\n@@ -593,7 +596,7 @@ SnapBuildInitialSnapshot(SnapBuild *builder)\n \tif (TransactionIdIsValid(MyProc->xmin))\n \t\telog(ERROR, \"cannot build an initial slot snapshot when MyProc->xmin already is valid\");\n \n-\tsnap = SnapBuildBuildSnapshot(builder);\n+\tsnap = SnapBuildBuildSnapshot(builder, InvalidXLogRecPtr);\n \n \t/*\n \t * We know that snap->xmin is alive, enforced by the logical xmin\n@@ -614,6 +617,47 @@ SnapBuildInitialSnapshot(SnapBuild *builder)\n \n \tMyProc->xmin = snap->xmin;\n \n+\t/* Convert the historic snapshot to MVCC snapshot. */\n+\treturn SnapBuildMVCCFromHistoric(snap, true);\n+}\n+\n+/*\n+ * Build an MVCC snapshot for the initial data load performed by CLUSTER\n+ * CONCURRENTLY command.\n+ *\n+ * The snapshot will only be used to scan one particular relation, which is\n+ * treated like a catalog (therefore ->building_full_snapshot is not\n+ * important), and the caller should already have a replication slot setup (so\n+ * we do not set MyProc->xmin). XXX Do we yet need to add some restrictions?\n+ */\n+Snapshot\n+SnapBuildInitialSnapshotForCluster(SnapBuild *builder)\n+{\n+\tSnapshot\tsnap;\n+\n+\tAssert(builder->state == SNAPBUILD_CONSISTENT);\n+\n+\tsnap = SnapBuildBuildSnapshot(builder, InvalidXLogRecPtr);\n+\treturn SnapBuildMVCCFromHistoric(snap, false);\n+}\n+\n+/*\n+ * Turn a historic MVCC snapshot into an ordinary MVCC snapshot.\n+ *\n+ * Pass true for 'in_place' if you don't care about modifying the source\n+ * snapshot. If you need a new instance, and one that was allocated as a\n+ * single chunk of memory, pass false.\n+ */\n+Snapshot\n+SnapBuildMVCCFromHistoric(Snapshot snapshot, bool in_place)\n+{\n+\tTransactionId xid;\n+\tTransactionId *oldxip = snapshot->xip;\n+\tuint32\t\toldxcnt\t= snapshot->xcnt;\n+\tTransactionId *newxip;\n+\tint\t\t\tnewxcnt = 0;\n+\tSnapshot\tresult;\n+\n \t/* allocate in transaction context */\n \tnewxip = (TransactionId *)\n \t\tpalloc(sizeof(TransactionId) * GetMaxSnapshotXidCount());\n@@ -624,7 +668,7 @@ SnapBuildInitialSnapshot(SnapBuild *builder)\n \t * classical snapshot by marking all non-committed transactions as\n \t * in-progress. This can be expensive.\n \t */\n-\tfor (xid = snap->xmin; NormalTransactionIdPrecedes(xid, snap->xmax);)\n+\tfor (xid = snapshot->xmin; NormalTransactionIdPrecedes(xid, snapshot->xmax);)\n \t{\n \t\tvoid\t *test;\n \n@@ -632,7 +676,7 @@ SnapBuildInitialSnapshot(SnapBuild *builder)\n \t\t * Check whether transaction committed using the decoding snapshot\n \t\t * meaning of ->xip.\n \t\t */\n-\t\ttest = bsearch(&xid, snap->xip, snap->xcnt,\n+\t\ttest = bsearch(&xid, snapshot->xip, snapshot->xcnt,\n \t\t\t\t\t sizeof(TransactionId), xidComparator);\n \n \t\tif (test == NULL)\n@@ -649,11 +693,22 @@ SnapBuildInitialSnapshot(SnapBuild *builder)\n \t}\n \n \t/* adjust remaining snapshot fields as needed */\n-\tsnap->snapshot_type = SNAPSHOT_MVCC;\n-\tsnap->xcnt = newxcnt;\n-\tsnap->xip = newxip;\n+\tsnapshot->xcnt = newxcnt;\n+\tsnapshot->xip = newxip;\n+\n+\tif (in_place)\n+\t\tresult = snapshot;\n+\telse\n+\t{\n+\t\tresult = CopySnapshot(snapshot);\n+\n+\t\t/* Restore the original values so the source is intact. */\n+\t\tsnapshot->xip = oldxip;\n+\t\tsnapshot->xcnt = oldxcnt;\n+\t}\n+\tresult->snapshot_type = SNAPSHOT_MVCC;\n \n-\treturn snap;\n+\treturn result;\n }\n \n /*\n@@ -712,7 +767,7 @@ SnapBuildGetOrBuildSnapshot(SnapBuild *builder)\n \t/* only build a new snapshot if we don't have a prebuilt one */\n \tif (builder->snapshot == NULL)\n \t{\n-\t\tbuilder->snapshot = SnapBuildBuildSnapshot(builder);\n+\t\tbuilder->snapshot = SnapBuildBuildSnapshot(builder, InvalidXLogRecPtr);\n \t\t/* increase refcount for the snapshot builder */\n \t\tSnapBuildSnapIncRefcount(builder->snapshot);\n \t}\n@@ -792,7 +847,7 @@ SnapBuildProcessChange(SnapBuild *builder, TransactionId xid, XLogRecPtr lsn)\n \t\t/* only build a new snapshot if we don't have a prebuilt one */\n \t\tif (builder->snapshot == NULL)\n \t\t{\n-\t\t\tbuilder->snapshot = SnapBuildBuildSnapshot(builder);\n+\t\t\tbuilder->snapshot = SnapBuildBuildSnapshot(builder, lsn);\n \t\t\t/* increase refcount for the snapshot builder */\n \t\t\tSnapBuildSnapIncRefcount(builder->snapshot);\n \t\t}\n@@ -1161,7 +1216,7 @@ SnapBuildCommitTxn(SnapBuild *builder, XLogRecPtr lsn, TransactionId xid,\n \t\tif (builder->snapshot)\n \t\t\tSnapBuildSnapDecRefcount(builder->snapshot);\n \n-\t\tbuilder->snapshot = SnapBuildBuildSnapshot(builder);\n+\t\tbuilder->snapshot = SnapBuildBuildSnapshot(builder, lsn);\n \n \t\t/* we might need to execute invalidations, add snapshot */\n \t\tif (!ReorderBufferXidHasBaseSnapshot(builder->reorder, xid))\n@@ -1989,7 +2044,7 @@ SnapBuildRestore(SnapBuild *builder, XLogRecPtr lsn)\n \t{\n \t\tSnapBuildSnapDecRefcount(builder->snapshot);\n \t}\n-\tbuilder->snapshot = SnapBuildBuildSnapshot(builder);\n+\tbuilder->snapshot = SnapBuildBuildSnapshot(builder, InvalidXLogRecPtr);\n \tSnapBuildSnapIncRefcount(builder->snapshot);\n \n \tReorderBufferSetRestartPoint(builder->reorder, lsn);\ndiff --git a/src/backend/replication/pgoutput_cluster/Makefile b/src/backend/replication/pgoutput_cluster/Makefile\nnew file mode 100644\nindex 0000000000..31471bb546\n--- /dev/null\n+++ b/src/backend/replication/pgoutput_cluster/Makefile\n@@ -0,0 +1,32 @@\n+#-------------------------------------------------------------------------\n+#\n+# Makefile--\n+# Makefile for src/backend/replication/pgoutput_cluster\n+#\n+# IDENTIFICATION\n+# src/backend/replication/pgoutput_cluster\n+#\n+#-------------------------------------------------------------------------\n+\n+subdir = src/backend/replication/pgoutput_cluster\n+top_builddir = ../../../..\n+include $(top_builddir)/src/Makefile.global\n+\n+OBJS = \\\n+\t$(WIN32RES) \\\n+\tpgoutput_cluster.o\n+PGFILEDESC = \"pgoutput_cluster - logical replication output plugin for CLUSTER command\"\n+NAME = pgoutput_cluster\n+\n+all: all-shared-lib\n+\n+include $(top_srcdir)/src/Makefile.shlib\n+\n+install: all installdirs install-lib\n+\n+installdirs: installdirs-lib\n+\n+uninstall: uninstall-lib\n+\n+clean distclean: clean-lib\n+\trm -f $(OBJS)\ndiff --git a/src/backend/replication/pgoutput_cluster/meson.build b/src/backend/replication/pgoutput_cluster/meson.build\nnew file mode 100644\nindex 0000000000..0f033064f2\n--- /dev/null\n+++ b/src/backend/replication/pgoutput_cluster/meson.build\n@@ -0,0 +1,18 @@\n+# Copyright (c) 2022-2024, PostgreSQL Global Development Group\n+\n+pgoutput_cluster_sources = files(\n+ 'pgoutput_cluster.c',\n+)\n+\n+if host_system == 'windows'\n+ pgoutput_cluster_sources += rc_lib_gen.process(win32ver_rc, extra_args: [\n+ '--NAME', 'pgoutput_cluster',\n+ '--FILEDESC', 'pgoutput_cluster - logical replication output plugin for CLUSTER command',])\n+endif\n+\n+pgoutput_cluster = shared_module('pgoutput_cluster',\n+ pgoutput_cluster_sources,\n+ kwargs: pg_mod_args,\n+)\n+\n+backend_targets += pgoutput_cluster\ndiff --git a/src/backend/replication/pgoutput_cluster/pgoutput_cluster.c b/src/backend/replication/pgoutput_cluster/pgoutput_cluster.c\nnew file mode 100644\nindex 0000000000..9fe44017a8\n--- /dev/null\n+++ b/src/backend/replication/pgoutput_cluster/pgoutput_cluster.c\n@@ -0,0 +1,321 @@\n+/* TODO Move into src/backend/cluster/ (and rename?) */\n+/*-------------------------------------------------------------------------\n+ *\n+ * pgoutput_cluster.c\n+ *\t\tLogical Replication output plugin for CLUSTER command\n+ *\n+ * Copyright (c) 2012-2024, PostgreSQL Global Development Group\n+ *\n+ * IDENTIFICATION\n+ *\t\t src/backend/replication/pgoutput_cluster/pgoutput_cluster.c\n+ *\n+ *-------------------------------------------------------------------------\n+ */\n+#include \"postgres.h\"\n+\n+#include \"access/heaptoast.h\"\n+#include \"commands/cluster.h\"\n+#include \"replication/snapbuild.h\"\n+\n+PG_MODULE_MAGIC;\n+\n+static void plugin_startup(LogicalDecodingContext *ctx,\n+\t\t\t\t\t\t OutputPluginOptions *opt, bool is_init);\n+static void plugin_shutdown(LogicalDecodingContext *ctx);\n+static void plugin_begin_txn(LogicalDecodingContext *ctx,\n+\t\t\t\t\t\t\t ReorderBufferTXN *txn);\n+static void plugin_commit_txn(LogicalDecodingContext *ctx,\n+\t\t\t\t\t\t\t ReorderBufferTXN *txn, XLogRecPtr commit_lsn);\n+static void plugin_change(LogicalDecodingContext *ctx, ReorderBufferTXN *txn,\n+\t\t\t\t\t\t Relation rel, ReorderBufferChange *change);\n+static void plugin_truncate(struct LogicalDecodingContext *ctx,\n+\t\t\t\t\t\t\tReorderBufferTXN *txn, int nrelations,\n+\t\t\t\t\t\t\tRelation relations[],\n+\t\t\t\t\t\t\tReorderBufferChange *change);\n+static void store_change(LogicalDecodingContext *ctx,\n+\t\t\t\t\t\t ConcurrentChangeKind kind, HeapTuple tuple,\n+\t\t\t\t\t\t TransactionId xid);\n+\n+void\n+_PG_output_plugin_init(OutputPluginCallbacks *cb)\n+{\n+\tAssertVariableIsOfType(&_PG_output_plugin_init, LogicalOutputPluginInit);\n+\n+\tcb->startup_cb = plugin_startup;\n+\tcb->begin_cb = plugin_begin_txn;\n+\tcb->change_cb = plugin_change;\n+\tcb->truncate_cb = plugin_truncate;\n+\tcb->commit_cb = plugin_commit_txn;\n+\tcb->shutdown_cb = plugin_shutdown;\n+}\n+\n+\n+/* initialize this plugin */\n+static void\n+plugin_startup(LogicalDecodingContext *ctx, OutputPluginOptions *opt,\n+\t\t\t bool is_init)\n+{\n+\tctx->output_plugin_private = NULL;\n+\n+\t/* Probably unnecessary, as we don't use the SQL interface ... */\n+\topt->output_type = OUTPUT_PLUGIN_BINARY_OUTPUT;\n+\n+\tif (ctx->output_plugin_options != NIL)\n+\t{\n+\t\tereport(ERROR,\n+\t\t\t\t(errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n+\t\t\t\t errmsg(\"This plugin does not expect any options\")));\n+\t}\n+}\n+\n+static void\n+plugin_shutdown(LogicalDecodingContext *ctx)\n+{\n+}\n+\n+/*\n+ * As we don't release the slot during processing of particular table, there's\n+ * no room for SQL interface, even for debugging purposes. Therefore we need\n+ * neither OutputPluginPrepareWrite() nor OutputPluginWrite() in the plugin\n+ * callbacks. (Although we might want to write custom callbacks, this API\n+ * seems to be unnecessarily generic for our purposes.)\n+ */\n+\n+/* BEGIN callback */\n+static void\n+plugin_begin_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn)\n+{\n+}\n+\n+/* COMMIT callback */\n+static void\n+plugin_commit_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn,\n+\t\t\t\t XLogRecPtr commit_lsn)\n+{\n+}\n+\n+/*\n+ * Callback for individual changed tuples\n+ */\n+static void\n+plugin_change(LogicalDecodingContext *ctx, ReorderBufferTXN *txn,\n+\t\t\t Relation relation, ReorderBufferChange *change)\n+{\n+\tClusterDecodingState *dstate;\n+\tSnapshot\tsnapshot;\n+\n+\tdstate = (ClusterDecodingState *) ctx->output_writer_private;\n+\n+\t/* Only interested in one particular relation. */\n+\tif (relation->rd_id != dstate->relid)\n+\t\treturn;\n+\n+\t/*\n+\t * Catalog snapshot is fine because the table we are processing is\n+\t * temporarily considered a user catalog table.\n+\t */\n+\tsnapshot = GetCatalogSnapshot(InvalidOid);\n+\tAssert(snapshot->snapshot_type == SNAPSHOT_HISTORIC_MVCC);\n+\tAssert(!snapshot->suboverflowed);\n+\n+\t/*\n+\t * This should not happen, but if we don't have enough information to\n+\t * apply a new snapshot, the consequences would be bad. Thus prefer ERROR\n+\t * to Assert().\n+\t */\n+\tif (XLogRecPtrIsInvalid(snapshot->lsn))\n+\t\tereport(ERROR, (errmsg(\"snapshot has invalid LSN\")));\n+\n+\t/*\n+\t * reorderbuffer.c changes the catalog snapshot as soon as it sees a new\n+\t * CID or a commit record of a catalog-changing transaction.\n+\t */\n+\tif (dstate->snapshot == NULL || snapshot->lsn != dstate->snapshot_lsn ||\n+\t\tsnapshot->curcid != dstate->snapshot->curcid)\n+\t{\n+\t\t/* CID should not go backwards. */\n+\t\tAssert(dstate->snapshot == NULL ||\n+\t\t\t snapshot->curcid >= dstate->snapshot->curcid);\n+\n+\t\t/*\n+\t\t * XXX Is it a problem that the copy is created in\n+\t\t * TopTransactionContext?\n+\t\t */\n+\t\tdstate->snapshot = SnapBuildMVCCFromHistoric(snapshot, false);\n+\t\tdstate->snapshot_lsn = snapshot->lsn;\n+\t}\n+\n+\t/* Decode entry depending on its type */\n+\tswitch (change->action)\n+\t{\n+\t\tcase REORDER_BUFFER_CHANGE_INSERT:\n+\t\t\t{\n+\t\t\t\tHeapTuple\tnewtuple;\n+\n+\t\t\t\tnewtuple = change->data.tp.newtuple != NULL ?\n+\t\t\t\t\tchange->data.tp.newtuple : NULL;\n+\n+\t\t\t\t/*\n+\t\t\t\t * Identity checks in the main function should have made this\n+\t\t\t\t * impossible.\n+\t\t\t\t */\n+\t\t\t\tif (newtuple == NULL)\n+\t\t\t\t\telog(ERROR, \"Incomplete insert info.\");\n+\n+\t\t\t\tstore_change(ctx, CHANGE_INSERT, newtuple, change->txn->xid);\n+\t\t\t}\n+\t\t\tbreak;\n+\t\tcase REORDER_BUFFER_CHANGE_UPDATE:\n+\t\t\t{\n+\t\t\t\tHeapTuple\toldtuple,\n+\t\t\t\t\t\t\tnewtuple;\n+\n+\t\t\t\toldtuple = change->data.tp.oldtuple != NULL ?\n+\t\t\t\t\tchange->data.tp.oldtuple : NULL;\n+\t\t\t\tnewtuple = change->data.tp.newtuple != NULL ?\n+\t\t\t\t\tchange->data.tp.newtuple : NULL;\n+\n+\t\t\t\tif (newtuple == NULL)\n+\t\t\t\t\telog(ERROR, \"Incomplete update info.\");\n+\n+\t\t\t\tif (oldtuple != NULL)\n+\t\t\t\t\tstore_change(ctx, CHANGE_UPDATE_OLD, oldtuple,\n+\t\t\t\t\t\t\t\t change->txn->xid);\n+\n+\t\t\t\tstore_change(ctx, CHANGE_UPDATE_NEW, newtuple,\n+\t\t\t\t\t\t\t change->txn->xid);\n+\t\t\t}\n+\t\t\tbreak;\n+\t\tcase REORDER_BUFFER_CHANGE_DELETE:\n+\t\t\t{\n+\t\t\t\tHeapTuple\toldtuple;\n+\n+\t\t\t\toldtuple = change->data.tp.oldtuple ?\n+\t\t\t\t\tchange->data.tp.oldtuple : NULL;\n+\n+\t\t\t\tif (oldtuple == NULL)\n+\t\t\t\t\telog(ERROR, \"Incomplete delete info.\");\n+\n+\t\t\t\tstore_change(ctx, CHANGE_DELETE, oldtuple, change->txn->xid);\n+\t\t\t}\n+\t\t\tbreak;\n+\t\tdefault:\n+\t\t\t/* Should not come here */\n+\t\t\tAssert(false);\n+\t\t\tbreak;\n+\t}\n+}\n+\n+static void\n+plugin_truncate(struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn,\n+\t\t\t\tint nrelations, Relation relations[],\n+\t\t\t\tReorderBufferChange *change)\n+{\n+\tClusterDecodingState *dstate;\n+\tint\t\ti;\n+\tRelation\trelation = NULL;\n+\n+\tdstate = (ClusterDecodingState *) ctx->output_writer_private;\n+\n+\t/* Find the relation we are processing. */\n+\tfor (i = 0; i < nrelations; i++)\n+\t{\n+\t\trelation = relations[i];\n+\n+\t\tif (RelationGetRelid(relation) == dstate->relid)\n+\t\t\tbreak;\n+\t}\n+\n+\t/* Is this truncation of another relation? */\n+\tif (i == nrelations)\n+\t\treturn;\n+\n+\tstore_change(ctx, CHANGE_TRUNCATE, NULL, InvalidTransactionId);\n+}\n+\n+/* Store concurrent data change. */\n+static void\n+store_change(LogicalDecodingContext *ctx, ConcurrentChangeKind kind,\n+\t\t\t HeapTuple tuple, TransactionId xid)\n+{\n+\tClusterDecodingState *dstate;\n+\tchar\t *change_raw;\n+\tConcurrentChange *change;\n+\tbool\t\tflattened = false;\n+\tSize\t\tsize;\n+\tDatum\t\tvalues[1];\n+\tbool\t\tisnull[1];\n+\tchar\t *dst;\n+\n+\tdstate = (ClusterDecodingState *) ctx->output_writer_private;\n+\n+\tsize = MAXALIGN(VARHDRSZ) + sizeof(ConcurrentChange);\n+\n+\tif (tuple)\n+\t{\n+\t\t/*\n+\t\t * ReorderBufferCommit() stores the TOAST chunks in its private memory\n+\t\t * context and frees them after having called\n+\t\t * apply_change(). Therefore we need flat copy (including TOAST) that\n+\t\t * we eventually copy into the memory context which is available to\n+\t\t * decode_concurrent_changes().\n+\t\t */\n+\t\tif (HeapTupleHasExternal(tuple))\n+\t\t{\n+\t\t\t/*\n+\t\t\t * toast_flatten_tuple_to_datum() might be more convenient but we\n+\t\t\t * don't want the decompression it does.\n+\t\t\t */\n+\t\t\ttuple = toast_flatten_tuple(tuple, dstate->tupdesc);\n+\t\t\tflattened = true;\n+\t\t}\n+\n+\t\tsize += tuple->t_len;\n+\t}\n+\n+\t/* XXX Isn't there any function / macro to do this? */\n+\tif (size >= 0x3FFFFFFF)\n+\t\telog(ERROR, \"Change is too big.\");\n+\n+\t/* Construct the change. */\n+\tchange_raw = (char *) palloc0(size);\n+\tSET_VARSIZE(change_raw, size);\n+\tchange = (ConcurrentChange *) VARDATA(change_raw);\n+\tchange->kind = kind;\n+\n+\t/* No other information is needed for TRUNCATE. */\n+\tif (change->kind == CHANGE_TRUNCATE)\n+\t\tgoto store;\n+\n+\t/*\n+\t * Copy the tuple.\n+\t *\n+\t * CAUTION: change->tup_data.t_data must be fixed on retrieval!\n+\t */\n+\tmemcpy(&change->tup_data, tuple, sizeof(HeapTupleData));\n+\tdst = (char *) change + sizeof(ConcurrentChange);\n+\tmemcpy(dst, tuple->t_data, tuple->t_len);\n+\n+\t/* Initialize the other fields. */\n+\tchange->xid = xid;\n+\tchange->snapshot = dstate->snapshot;\n+\tdstate->snapshot->active_count++;\n+\n+\t/* The data has been copied. */\n+\tif (flattened)\n+\t\tpfree(tuple);\n+\n+store:\n+\t/* Store as tuple of 1 bytea column. */\n+\tvalues[0] = PointerGetDatum(change_raw);\n+\tisnull[0] = false;\n+\ttuplestore_putvalues(dstate->tstore, dstate->tupdesc_change,\n+\t\t\t\t\t\t values, isnull);\n+\n+\t/* Accounting. */\n+\tdstate->nchanges++;\n+\n+\t/* Cleanup. */\n+\tpfree(change_raw);\n+}\n+\ndiff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c\nindex 2100150f01..a84de0611a 100644\n--- a/src/backend/storage/ipc/ipci.c\n+++ b/src/backend/storage/ipc/ipci.c\n@@ -25,6 +25,7 @@\n #include \"access/xlogprefetcher.h\"\n #include \"access/xlogrecovery.h\"\n #include \"commands/async.h\"\n+#include \"commands/cluster.h\"\n #include \"miscadmin.h\"\n #include \"pgstat.h\"\n #include \"postmaster/autovacuum.h\"\n@@ -152,6 +153,7 @@ CalculateShmemSize(int *num_semaphores)\n \tsize = add_size(size, WaitEventCustomShmemSize());\n \tsize = add_size(size, InjectionPointShmemSize());\n \tsize = add_size(size, SlotSyncShmemSize());\n+\tsize = add_size(size, ClusterShmemSize());\n #ifdef EXEC_BACKEND\n \tsize = add_size(size, ShmemBackendArraySize());\n #endif\n@@ -357,6 +359,7 @@ CreateOrAttachShmemStructs(void)\n \tStatsShmemInit();\n \tWaitEventCustomShmemInit();\n \tInjectionPointShmemInit();\n+\tClusterShmemInit();\n }\n \n /*\ndiff --git a/src/backend/tcop/utility.c b/src/backend/tcop/utility.c\nindex fa66b8017e..a6dda9b520 100644\n--- a/src/backend/tcop/utility.c\n+++ b/src/backend/tcop/utility.c\n@@ -1299,6 +1299,17 @@ ProcessUtilitySlow(ParseState *pstate,\n \t\t\t\t\tlockmode = AlterTableGetLockLevel(atstmt->cmds);\n \t\t\t\t\trelid = AlterTableLookupRelation(atstmt, lockmode);\n \n+\t\t\t\t\t/*\n+\t\t\t\t\t * If lockmode allows, check if VACUUM FULL / CLUSTER\n+\t\t\t\t\t * CONCURRENT is in progress. If lockmode is too weak,\n+\t\t\t\t\t * cluster_rel() should detect incompatible DDLs executed\n+\t\t\t\t\t * by us.\n+\t\t\t\t\t *\n+\t\t\t\t\t * XXX We might skip the changes for DDLs which do not\n+\t\t\t\t\t * change the tuple descriptor.\n+\t\t\t\t\t */\n+\t\t\t\t\tcheck_for_concurrent_cluster(relid, lockmode);\n+\n \t\t\t\t\tif (OidIsValid(relid))\n \t\t\t\t\t{\n \t\t\t\t\t\tAlterTableUtilityContext atcontext;\ndiff --git a/src/backend/utils/activity/backend_progress.c b/src/backend/utils/activity/backend_progress.c\nindex e7c8bfba94..c52ec92a97 100644\n--- a/src/backend/utils/activity/backend_progress.c\n+++ b/src/backend/utils/activity/backend_progress.c\n@@ -163,3 +163,19 @@ pgstat_progress_end_command(void)\n \tbeentry->st_progress.command_target = InvalidOid;\n \tPGSTAT_END_WRITE_ACTIVITY(beentry);\n }\n+\n+void\n+pgstat_progress_restore_state(PgBackendProgress *backup)\n+{\n+\tvolatile PgBackendStatus *beentry = MyBEEntry;\n+\n+\tif (!beentry || !pgstat_track_activities)\n+\t\treturn;\n+\n+\tPGSTAT_BEGIN_WRITE_ACTIVITY(beentry);\n+\tbeentry->st_progress.command = backup->command;\n+\tbeentry->st_progress.command_target = backup->command_target;\n+\tmemcpy(MyBEEntry->st_progress.param, backup->param,\n+\t\t sizeof(beentry->st_progress.param));\n+\tPGSTAT_END_WRITE_ACTIVITY(beentry);\n+}\ndiff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt\nindex db37beeaae..8245be7846 100644\n--- a/src/backend/utils/activity/wait_event_names.txt\n+++ b/src/backend/utils/activity/wait_event_names.txt\n@@ -345,6 +345,7 @@ WALSummarizer\t\"Waiting to read or update WAL summarization state.\"\n DSMRegistry\t\"Waiting to read or update the dynamic shared memory registry.\"\n InjectionPoint\t\"Waiting to read or update information related to injection points.\"\n SerialControl\t\"Waiting to read or update shared <filename>pg_serial</filename> state.\"\n+ClusteredRels\t\"Waiting to read or update information on tables being clustered concurrently.\"\n \n #\n # END OF PREDEFINED LWLOCKS (DO NOT CHANGE THIS LINE)\ndiff --git a/src/backend/utils/cache/inval.c b/src/backend/utils/cache/inval.c\nindex 603aa4157b..5a2d5d6138 100644\n--- a/src/backend/utils/cache/inval.c\n+++ b/src/backend/utils/cache/inval.c\n@@ -1373,6 +1373,28 @@ CacheInvalidateRelcache(Relation relation)\n \tRegisterRelcacheInvalidation(databaseId, relationId);\n }\n \n+/*\n+ * CacheInvalidateRelcacheImmediate\n+ *\t\tSend invalidation message for the specified relation's relcache entry.\n+ *\n+ * Currently this is used in VACUUM FULL/CLUSTER CONCURRENTLY, to make sure\n+ * that other backends are aware that the command is being executed for the\n+ * relation.\n+ */\n+void\n+CacheInvalidateRelcacheImmediate(Relation relation)\n+{\n+\tSharedInvalidationMessage msg;\n+\n+\tmsg.rc.id = SHAREDINVALRELCACHE_ID;\n+\tmsg.rc.dbId = MyDatabaseId;\n+\tmsg.rc.relId = RelationGetRelid(relation);\n+\t/* check AddCatcacheInvalidationMessage() for an explanation */\n+\tVALGRIND_MAKE_MEM_DEFINED(&msg, sizeof(msg));\n+\n+\tSendSharedInvalidMessages(&msg, 1);\n+}\n+\n /*\n * CacheInvalidateRelcacheAll\n *\t\tRegister invalidation of the whole relcache at the end of command.\ndiff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c\nindex 66ed24e401..708d1ee27a 100644\n--- a/src/backend/utils/cache/relcache.c\n+++ b/src/backend/utils/cache/relcache.c\n@@ -64,6 +64,7 @@\n #include \"catalog/pg_type.h\"\n #include \"catalog/schemapg.h\"\n #include \"catalog/storage.h\"\n+#include \"commands/cluster.h\"\n #include \"commands/policy.h\"\n #include \"commands/publicationcmds.h\"\n #include \"commands/trigger.h\"\n@@ -1257,6 +1258,10 @@ retry:\n \t/* make sure relation is marked as having no open file yet */\n \trelation->rd_smgr = NULL;\n \n+\t/* Is CLUSTER CONCURRENTLY in progress? */\n+\trelation->rd_cluster_concurrent =\n+\t\tis_concurrent_cluster_in_progress(targetRelId);\n+\n \t/*\n \t * now we can free the memory allocated for pg_class_tuple\n \t */\ndiff --git a/src/backend/utils/time/snapmgr.c b/src/backend/utils/time/snapmgr.c\nindex 7d2b34d4f2..6be0fef84c 100644\n--- a/src/backend/utils/time/snapmgr.c\n+++ b/src/backend/utils/time/snapmgr.c\n@@ -155,9 +155,7 @@ typedef struct ExportedSnapshot\n static List *exportedSnapshots = NIL;\n \n /* Prototypes for local functions */\n-static Snapshot CopySnapshot(Snapshot snapshot);\n static void UnregisterSnapshotNoOwner(Snapshot snapshot);\n-static void FreeSnapshot(Snapshot snapshot);\n static void SnapshotResetXmin(void);\n \n /* ResourceOwner callbacks to track snapshot references */\n@@ -570,7 +568,7 @@ SetTransactionSnapshot(Snapshot sourcesnap, VirtualTransactionId *sourcevxid,\n * The copy is palloc'd in TopTransactionContext and has initial refcounts set\n * to 0. The returned snapshot has the copied flag set.\n */\n-static Snapshot\n+Snapshot\n CopySnapshot(Snapshot snapshot)\n {\n \tSnapshot\tnewsnap;\n@@ -626,7 +624,7 @@ CopySnapshot(Snapshot snapshot)\n * FreeSnapshot\n *\t\tFree the memory associated with a snapshot.\n */\n-static void\n+void\n FreeSnapshot(Snapshot snapshot)\n {\n \tAssert(snapshot->regd_count == 0);\ndiff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c\nindex d453e224d9..6cab6ed5ee 100644\n--- a/src/bin/psql/tab-complete.c\n+++ b/src/bin/psql/tab-complete.c\n@@ -2787,7 +2787,7 @@ psql_completion(const char *text, int start, int end)\n \t\t * one word, so the above test is correct.\n \t\t */\n \t\tif (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))\n-\t\t\tCOMPLETE_WITH(\"VERBOSE\");\n+\t\t\tCOMPLETE_WITH(\"VERBOSE\", \"CONCURRENTLY\");\n \t}\n \n /* COMMENT */\n@@ -4764,7 +4764,8 @@ psql_completion(const char *text, int start, int end)\n \t\t\t\t\t\t \"DISABLE_PAGE_SKIPPING\", \"SKIP_LOCKED\",\n \t\t\t\t\t\t \"INDEX_CLEANUP\", \"PROCESS_MAIN\", \"PROCESS_TOAST\",\n \t\t\t\t\t\t \"TRUNCATE\", \"PARALLEL\", \"SKIP_DATABASE_STATS\",\n-\t\t\t\t\t\t \"ONLY_DATABASE_STATS\", \"BUFFER_USAGE_LIMIT\");\n+\t\t\t\t\t\t \"ONLY_DATABASE_STATS\", \"BUFFER_USAGE_LIMIT\",\n+\t\t\t\t\t\t \"CONCURRENTLY\");\n \t\telse if (TailMatches(\"FULL|FREEZE|ANALYZE|VERBOSE|DISABLE_PAGE_SKIPPING|SKIP_LOCKED|PROCESS_MAIN|PROCESS_TOAST|TRUNCATE|SKIP_DATABASE_STATS|ONLY_DATABASE_STATS\"))\n \t\t\tCOMPLETE_WITH(\"ON\", \"OFF\");\n \t\telse if (TailMatches(\"INDEX_CLEANUP\"))\ndiff --git a/src/include/access/heapam.h b/src/include/access/heapam.h\nindex 9e9aec88a6..e87eb2f861 100644\n--- a/src/include/access/heapam.h\n+++ b/src/include/access/heapam.h\n@@ -316,21 +316,24 @@ extern BulkInsertState GetBulkInsertState(void);\n extern void FreeBulkInsertState(BulkInsertState);\n extern void ReleaseBulkInsertStatePin(BulkInsertState bistate);\n \n-extern void heap_insert(Relation relation, HeapTuple tup, CommandId cid,\n-\t\t\t\t\t\tint options, BulkInsertState bistate);\n+extern void heap_insert(Relation relation, HeapTuple tup, TransactionId xid,\n+\t\t\t\t\t\tCommandId cid, int options, BulkInsertState bistate);\n extern void heap_multi_insert(Relation relation, struct TupleTableSlot **slots,\n \t\t\t\t\t\t\t int ntuples, CommandId cid, int options,\n \t\t\t\t\t\t\t BulkInsertState bistate);\n extern TM_Result heap_delete(Relation relation, ItemPointer tid,\n-\t\t\t\t\t\t\t CommandId cid, Snapshot crosscheck, bool wait,\n-\t\t\t\t\t\t\t struct TM_FailureData *tmfd, bool changingPart);\n+\t\t\t\t\t\t\t TransactionId xid, CommandId cid,\n+\t\t\t\t\t\t\t Snapshot crosscheck, bool wait,\n+\t\t\t\t\t\t\t struct TM_FailureData *tmfd, bool changingPart,\n+\t\t\t\t\t\t\t bool wal_logical);\n extern void heap_finish_speculative(Relation relation, ItemPointer tid);\n extern void heap_abort_speculative(Relation relation, ItemPointer tid);\n extern TM_Result heap_update(Relation relation, ItemPointer otid,\n-\t\t\t\t\t\t\t HeapTuple newtup,\n+\t\t\t\t\t\t\t HeapTuple newtup, TransactionId xid,\n \t\t\t\t\t\t\t CommandId cid, Snapshot crosscheck, bool wait,\n \t\t\t\t\t\t\t struct TM_FailureData *tmfd, LockTupleMode *lockmode,\n-\t\t\t\t\t\t\t TU_UpdateIndexes *update_indexes);\n+\t\t\t\t\t\t\t TU_UpdateIndexes *update_indexes,\n+\t\t\t\t\t\t\t bool wal_logical);\n extern TM_Result heap_lock_tuple(Relation relation, HeapTuple tuple,\n \t\t\t\t\t\t\t\t CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,\n \t\t\t\t\t\t\t\t bool follow_updates,\n@@ -405,6 +408,10 @@ extern HTSV_Result HeapTupleSatisfiesVacuumHorizon(HeapTuple htup, Buffer buffer\n \t\t\t\t\t\t\t\t\t\t\t\t TransactionId *dead_after);\n extern void HeapTupleSetHintBits(HeapTupleHeader tuple, Buffer buffer,\n \t\t\t\t\t\t\t\t uint16 infomask, TransactionId xid);\n+extern bool HeapTupleMVCCInserted(HeapTuple htup, Snapshot snapshot,\n+\t\t\t\t\t\t\t\t Buffer buffer);\n+extern bool HeapTupleMVCCNotDeleted(HeapTuple htup, Snapshot snapshot,\n+\t\t\t\t\t\t\t\t\tBuffer buffer);\n extern bool HeapTupleHeaderIsOnlyLocked(HeapTupleHeader tuple);\n extern bool HeapTupleIsSurelyDead(HeapTuple htup,\n \t\t\t\t\t\t\t\t struct GlobalVisState *vistest);\ndiff --git a/src/include/access/heapam_xlog.h b/src/include/access/heapam_xlog.h\nindex 42736f37e7..1c5cb7c728 100644\n--- a/src/include/access/heapam_xlog.h\n+++ b/src/include/access/heapam_xlog.h\n@@ -103,6 +103,8 @@\n #define XLH_DELETE_CONTAINS_OLD_KEY\t\t\t\t(1<<2)\n #define XLH_DELETE_IS_SUPER\t\t\t\t\t\t(1<<3)\n #define XLH_DELETE_IS_PARTITION_MOVE\t\t\t(1<<4)\n+/* See heap_delete() */\n+#define XLH_DELETE_NO_LOGICAL\t\t\t\t\t(1<<5)\n \n /* convenience macro for checking whether any form of old tuple was logged */\n #define XLH_DELETE_CONTAINS_OLD\t\t\t\t\t\t\\\ndiff --git a/src/include/access/tableam.h b/src/include/access/tableam.h\nindex da661289c1..1380ba81fc 100644\n--- a/src/include/access/tableam.h\n+++ b/src/include/access/tableam.h\n@@ -21,6 +21,7 @@\n #include \"access/sdir.h\"\n #include \"access/xact.h\"\n #include \"executor/tuptable.h\"\n+#include \"replication/logical.h\"\n #include \"storage/read_stream.h\"\n #include \"utils/rel.h\"\n #include \"utils/snapshot.h\"\n@@ -630,6 +631,8 @@ typedef struct TableAmRoutine\n \t\t\t\t\t\t\t\t\t\t\t Relation OldIndex,\n \t\t\t\t\t\t\t\t\t\t\t bool use_sort,\n \t\t\t\t\t\t\t\t\t\t\t TransactionId OldestXmin,\n+\t\t\t\t\t\t\t\t\t\t\t Snapshot snapshot,\n+\t\t\t\t\t\t\t\t\t\t\t LogicalDecodingContext *decoding_ctx,\n \t\t\t\t\t\t\t\t\t\t\t TransactionId *xid_cutoff,\n \t\t\t\t\t\t\t\t\t\t\t MultiXactId *multi_cutoff,\n \t\t\t\t\t\t\t\t\t\t\t double *num_tuples,\n@@ -1667,6 +1670,10 @@ table_relation_copy_data(Relation rel, const RelFileLocator *newrlocator)\n * not needed for the relation's AM\n * - *xid_cutoff - ditto\n * - *multi_cutoff - ditto\n+ * - snapshot - if != NULL, ignore data changes done by transactions that this\n+ *\t (MVCC) snapshot considers still in-progress or in the future.\n+ * - decoding_ctx - logical decoding context, to capture concurrent data\n+ * changes.\n *\n * Output parameters:\n * - *xid_cutoff - rel's new relfrozenxid value, may be invalid\n@@ -1679,6 +1686,8 @@ table_relation_copy_for_cluster(Relation OldTable, Relation NewTable,\n \t\t\t\t\t\t\t\tRelation OldIndex,\n \t\t\t\t\t\t\t\tbool use_sort,\n \t\t\t\t\t\t\t\tTransactionId OldestXmin,\n+\t\t\t\t\t\t\t\tSnapshot snapshot,\n+\t\t\t\t\t\t\t\tLogicalDecodingContext *decoding_ctx,\n \t\t\t\t\t\t\t\tTransactionId *xid_cutoff,\n \t\t\t\t\t\t\t\tMultiXactId *multi_cutoff,\n \t\t\t\t\t\t\t\tdouble *num_tuples,\n@@ -1687,6 +1696,7 @@ table_relation_copy_for_cluster(Relation OldTable, Relation NewTable,\n {\n \tOldTable->rd_tableam->relation_copy_for_cluster(OldTable, NewTable, OldIndex,\n \t\t\t\t\t\t\t\t\t\t\t\t\tuse_sort, OldestXmin,\n+\t\t\t\t\t\t\t\t\t\t\t\t\tsnapshot, decoding_ctx,\n \t\t\t\t\t\t\t\t\t\t\t\t\txid_cutoff, multi_cutoff,\n \t\t\t\t\t\t\t\t\t\t\t\t\tnum_tuples, tups_vacuumed,\n \t\t\t\t\t\t\t\t\t\t\t\t\ttups_recently_dead);\ndiff --git a/src/include/access/xact.h b/src/include/access/xact.h\nindex 6d4439f052..e0016631f6 100644\n--- a/src/include/access/xact.h\n+++ b/src/include/access/xact.h\n@@ -476,6 +476,8 @@ extern Size EstimateTransactionStateSpace(void);\n extern void SerializeTransactionState(Size maxsize, char *start_address);\n extern void StartParallelWorkerTransaction(char *tstatespace);\n extern void EndParallelWorkerTransaction(void);\n+extern void SetClusterCurrentXids(TransactionId *xip, int xcnt);\n+extern void ResetClusterCurrentXids(void);\n extern bool IsTransactionBlock(void);\n extern bool IsTransactionOrTransactionBlock(void);\n extern char TransactionBlockStatusCode(void);\ndiff --git a/src/include/catalog/index.h b/src/include/catalog/index.h\nindex 7d434f8e65..77d522561b 100644\n--- a/src/include/catalog/index.h\n+++ b/src/include/catalog/index.h\n@@ -99,6 +99,9 @@ extern Oid\tindex_concurrently_create_copy(Relation heapRelation,\n \t\t\t\t\t\t\t\t\t\t Oid tablespaceOid,\n \t\t\t\t\t\t\t\t\t\t const char *newName);\n \n+extern NullableDatum *get_index_stattargets(Oid indexid,\n+\t\t\t\t\t\t\t\t\t\t\tIndexInfo *indInfo);\n+\n extern void index_concurrently_build(Oid heapRelationId,\n \t\t\t\t\t\t\t\t\t Oid indexRelationId);\n \ndiff --git a/src/include/commands/cluster.h b/src/include/commands/cluster.h\nindex 7492796ea2..f98b855f21 100644\n--- a/src/include/commands/cluster.h\n+++ b/src/include/commands/cluster.h\n@@ -13,10 +13,15 @@\n #ifndef CLUSTER_H\n #define CLUSTER_H\n \n+#include \"nodes/execnodes.h\"\n #include \"nodes/parsenodes.h\"\n #include \"parser/parse_node.h\"\n+#include \"replication/logical.h\"\n #include \"storage/lock.h\"\n+#include \"storage/relfilelocator.h\"\n #include \"utils/relcache.h\"\n+#include \"utils/resowner.h\"\n+#include \"utils/tuplestore.h\"\n \n \n /* flag bits for ClusterParams->options */\n@@ -24,6 +29,7 @@\n #define CLUOPT_RECHECK 0x02\t\t/* recheck relation state */\n #define CLUOPT_RECHECK_ISCLUSTERED 0x04 /* recheck relation state for\n \t\t\t\t\t\t\t\t\t\t * indisclustered */\n+#define CLUOPT_CONCURRENT 0x08\t/* allow concurrent data changes */\n \n /* options for CLUSTER */\n typedef struct ClusterParams\n@@ -31,12 +37,114 @@ typedef struct ClusterParams\n \tbits32\t\toptions;\t\t/* bitmask of CLUOPT_* */\n } ClusterParams;\n \n+/*\n+ * The following definitions are used for concurrent processing.\n+ */\n+\n+/*\n+ * Lock level for the concurrent variant of CLUSTER / VACUUM FULL.\n+ *\n+ * Like for lazy VACUUM, we choose the strongest lock that still allows\n+ * INSERT, UPDATE and DELETE.\n+ *\n+ * Note that the lock needs to be released temporarily a few times during the\n+ * processing. In such cases it should be checked after re-locking that the\n+ * relation / index hasn't changed in the system catalog while the lock was\n+ * not held.\n+ */\n+#define LOCK_CLUSTER_CONCURRENT\tShareUpdateExclusiveLock\n+\n+typedef enum\n+{\n+\tCHANGE_INSERT,\n+\tCHANGE_UPDATE_OLD,\n+\tCHANGE_UPDATE_NEW,\n+\tCHANGE_DELETE,\n+\tCHANGE_TRUNCATE\n+} ConcurrentChangeKind;\n+\n+typedef struct ConcurrentChange\n+{\n+\t/* See the enum above. */\n+\tConcurrentChangeKind kind;\n+\n+\t/* Transaction that changes the data. */\n+\tTransactionId\txid;\n+\n+\t/*\n+\t * Historic catalog snapshot that was used to decode this change.\n+\t */\n+\tSnapshot\tsnapshot;\n+\n+\t/*\n+\t * The actual tuple.\n+\t *\n+\t * The tuple data follows the ConcurrentChange structure. Before use make\n+\t * sure the tuple is correctly aligned (ConcurrentChange can be stored as\n+\t * bytea) and that tuple->t_data is fixed.\n+\t */\n+\tHeapTupleData tup_data;\n+} ConcurrentChange;\n+\n+/*\n+ * Logical decoding state.\n+ *\n+ * Here we store the data changes that we decode from WAL while the table\n+ * contents is being copied to a new storage. Also the necessary metadata\n+ * needed to apply these changes to the table is stored here.\n+ */\n+typedef struct ClusterDecodingState\n+{\n+\t/* The relation whose changes we're decoding. */\n+\tOid\t\t\trelid;\n+\n+\t/*\n+\t * Decoded changes are stored here. Although we try to avoid excessive\n+\t * batches, it can happen that the changes need to be stored to disk. The\n+\t * tuplestore does this transparently.\n+\t */\n+\tTuplestorestate *tstore;\n+\n+\t/* The current number of changes in tstore. */\n+\tdouble\t\tnchanges;\n+\n+\t/*\n+\t * Descriptor to store the ConcurrentChange structure serialized (bytea).\n+\t * We can't store the tuple directly because tuplestore only supports\n+\t * minimum tuple and we may need to transfer OID system column from the\n+\t * output plugin. Also we need to transfer the change kind, so it's better\n+\t * to put everything in the structure than to use 2 tuplestores \"in\n+\t * parallel\".\n+\t */\n+\tTupleDesc\ttupdesc_change;\n+\n+\t/* Tuple descriptor needed to update indexes. */\n+\tTupleDesc\ttupdesc;\n+\n+\t/* Slot to retrieve data from tstore. */\n+\tTupleTableSlot *tsslot;\n+\n+\t/*\n+\t * Historic catalog snapshot that was used to decode the most recent\n+\t * change.\n+\t */\n+\tSnapshot\tsnapshot;\n+\t/* LSN of the record */\n+\tXLogRecPtr\tsnapshot_lsn;\n+\n+\tResourceOwner resowner;\n+} ClusterDecodingState;\n+\n extern void cluster(ParseState *pstate, ClusterStmt *stmt, bool isTopLevel);\n-extern void cluster_rel(Relation OldHeap, Oid indexOid, ClusterParams *params);\n+extern void cluster_rel(Relation OldHeap, Oid indexOid,\tClusterParams *params,\n+\t\t\t\t\t\tbool isTopLevel);\n extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,\n \t\t\t\t\t\t\t\t\t LOCKMODE lockmode);\n extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);\n-\n+extern bool check_relation_is_clusterable_concurrently(Relation rel, int elevel,\n+\t\t\t\t\t\t\t\t\t\t\t\t\t const char *stmt);\n+extern void cluster_decode_concurrent_changes(LogicalDecodingContext *ctx,\n+\t\t\t\t\t\t\t\t\t\t\t XLogRecPtr end_of_wal);\n extern Oid\tmake_new_heap(Oid OIDOldHeap, Oid NewTableSpace, Oid NewAccessMethod,\n \t\t\t\t\t\t char relpersistence, LOCKMODE lockmode_old,\n \t\t\t\t\t\t LOCKMODE *lockmode_new_p);\n@@ -45,8 +153,13 @@ extern void finish_heap_swap(Oid OIDOldHeap, Oid OIDNewHeap,\n \t\t\t\t\t\t\t bool swap_toast_by_content,\n \t\t\t\t\t\t\t bool check_constraints,\n \t\t\t\t\t\t\t bool is_internal,\n+\t\t\t\t\t\t\t bool reindex,\n \t\t\t\t\t\t\t TransactionId frozenXid,\n \t\t\t\t\t\t\t MultiXactId cutoffMulti,\n \t\t\t\t\t\t\t char newrelpersistence);\n \n+extern Size ClusterShmemSize(void);\n+extern void ClusterShmemInit(void);\n+extern bool is_concurrent_cluster_in_progress(Oid relid);\n+extern void check_for_concurrent_cluster(Oid relid, LOCKMODE lockmode);\n #endif\t\t\t\t\t\t\t/* CLUSTER_H */\ndiff --git a/src/include/commands/progress.h b/src/include/commands/progress.h\nindex 5616d64523..03e3712ede 100644\n--- a/src/include/commands/progress.h\n+++ b/src/include/commands/progress.h\n@@ -59,19 +59,22 @@\n #define PROGRESS_CLUSTER_PHASE\t\t\t\t\t1\n #define PROGRESS_CLUSTER_INDEX_RELID\t\t\t2\n #define PROGRESS_CLUSTER_HEAP_TUPLES_SCANNED\t3\n-#define PROGRESS_CLUSTER_HEAP_TUPLES_WRITTEN\t4\n-#define PROGRESS_CLUSTER_TOTAL_HEAP_BLKS\t\t5\n-#define PROGRESS_CLUSTER_HEAP_BLKS_SCANNED\t\t6\n-#define PROGRESS_CLUSTER_INDEX_REBUILD_COUNT\t7\n+#define PROGRESS_CLUSTER_HEAP_TUPLES_INSERTED\t4\n+#define PROGRESS_CLUSTER_HEAP_TUPLES_UPDATED\t5\n+#define PROGRESS_CLUSTER_HEAP_TUPLES_DELETED\t6\n+#define PROGRESS_CLUSTER_TOTAL_HEAP_BLKS\t\t7\n+#define PROGRESS_CLUSTER_HEAP_BLKS_SCANNED\t\t8\n+#define PROGRESS_CLUSTER_INDEX_REBUILD_COUNT\t9\n \n /* Phases of cluster (as advertised via PROGRESS_CLUSTER_PHASE) */\n #define PROGRESS_CLUSTER_PHASE_SEQ_SCAN_HEAP\t1\n #define PROGRESS_CLUSTER_PHASE_INDEX_SCAN_HEAP\t2\n #define PROGRESS_CLUSTER_PHASE_SORT_TUPLES\t\t3\n #define PROGRESS_CLUSTER_PHASE_WRITE_NEW_HEAP\t4\n-#define PROGRESS_CLUSTER_PHASE_SWAP_REL_FILES\t5\n-#define PROGRESS_CLUSTER_PHASE_REBUILD_INDEX\t6\n-#define PROGRESS_CLUSTER_PHASE_FINAL_CLEANUP\t7\n+#define PROGRESS_CLUSTER_PHASE_CATCH_UP\t\t\t5\n+#define PROGRESS_CLUSTER_PHASE_SWAP_REL_FILES\t6\n+#define PROGRESS_CLUSTER_PHASE_REBUILD_INDEX\t7\n+#define PROGRESS_CLUSTER_PHASE_FINAL_CLEANUP\t8\n \n /* Commands of PROGRESS_CLUSTER */\n #define PROGRESS_CLUSTER_COMMAND_CLUSTER\t\t1\ndiff --git a/src/include/commands/vacuum.h b/src/include/commands/vacuum.h\nindex 759f9a87d3..2f693e0fc0 100644\n--- a/src/include/commands/vacuum.h\n+++ b/src/include/commands/vacuum.h\n@@ -181,13 +181,16 @@ typedef struct VacAttrStats\n #define VACOPT_ANALYZE 0x02\t\t/* do ANALYZE */\n #define VACOPT_VERBOSE 0x04\t\t/* output INFO instrumentation messages */\n #define VACOPT_FREEZE 0x08\t\t/* FREEZE option */\n-#define VACOPT_FULL 0x10\t\t/* FULL (non-concurrent) vacuum */\n-#define VACOPT_SKIP_LOCKED 0x20 /* skip if cannot get lock */\n-#define VACOPT_PROCESS_MAIN 0x40\t/* process main relation */\n-#define VACOPT_PROCESS_TOAST 0x80\t/* process the TOAST table, if any */\n-#define VACOPT_DISABLE_PAGE_SKIPPING 0x100\t/* don't skip any pages */\n-#define VACOPT_SKIP_DATABASE_STATS 0x200\t/* skip vac_update_datfrozenxid() */\n-#define VACOPT_ONLY_DATABASE_STATS 0x400\t/* only vac_update_datfrozenxid() */\n+#define VACOPT_FULL_EXCLUSIVE 0x10\t/* FULL (non-concurrent) vacuum */\n+#define VACOPT_FULL_CONCURRENT 0x20\t/* FULL (concurrent) vacuum */\n+#define VACOPT_SKIP_LOCKED 0x40 /* skip if cannot get lock */\n+#define VACOPT_PROCESS_MAIN 0x80\t/* process main relation */\n+#define VACOPT_PROCESS_TOAST 0x100\t/* process the TOAST table, if any */\n+#define VACOPT_DISABLE_PAGE_SKIPPING 0x200\t/* don't skip any pages */\n+#define VACOPT_SKIP_DATABASE_STATS 0x400\t/* skip vac_update_datfrozenxid() */\n+#define VACOPT_ONLY_DATABASE_STATS 0x800\t/* only vac_update_datfrozenxid() */\n+\n+#define VACOPT_FULL (VACOPT_FULL_EXCLUSIVE | VACOPT_FULL_CONCURRENT)\n \n /*\n * Values used by index_cleanup and truncate params.\ndiff --git a/src/include/replication/snapbuild.h b/src/include/replication/snapbuild.h\nindex a3360a1c5e..abbfb616ce 100644\n--- a/src/include/replication/snapbuild.h\n+++ b/src/include/replication/snapbuild.h\n@@ -68,6 +68,8 @@ extern void FreeSnapshotBuilder(SnapBuild *builder);\n extern void SnapBuildSnapDecRefcount(Snapshot snap);\n \n extern Snapshot SnapBuildInitialSnapshot(SnapBuild *builder);\n+extern Snapshot SnapBuildInitialSnapshotForCluster(SnapBuild *builder);\n+extern Snapshot SnapBuildMVCCFromHistoric(Snapshot snapshot, bool in_place);\n extern const char *SnapBuildExportSnapshot(SnapBuild *builder);\n extern void SnapBuildClearExportedSnapshot(void);\n extern void SnapBuildResetExportedSnapshotState(void);\ndiff --git a/src/include/storage/lockdefs.h b/src/include/storage/lockdefs.h\nindex 934ba84f6a..cac3d7f8c7 100644\n--- a/src/include/storage/lockdefs.h\n+++ b/src/include/storage/lockdefs.h\n@@ -36,7 +36,7 @@ typedef int LOCKMODE;\n #define AccessShareLock\t\t\t1\t/* SELECT */\n #define RowShareLock\t\t\t2\t/* SELECT FOR UPDATE/FOR SHARE */\n #define RowExclusiveLock\t\t3\t/* INSERT, UPDATE, DELETE */\n-#define ShareUpdateExclusiveLock 4\t/* VACUUM (non-FULL), ANALYZE, CREATE\n+#define ShareUpdateExclusiveLock 4\t/* VACUUM (non-exclusive), ANALYZE, CREATE\n \t\t\t\t\t\t\t\t\t * INDEX CONCURRENTLY */\n #define ShareLock\t\t\t\t5\t/* CREATE INDEX (WITHOUT CONCURRENTLY) */\n #define ShareRowExclusiveLock\t6\t/* like EXCLUSIVE MODE, but allows ROW\ndiff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h\nindex 6a2f64c54f..a5f59b6c12 100644\n--- a/src/include/storage/lwlocklist.h\n+++ b/src/include/storage/lwlocklist.h\n@@ -83,3 +83,4 @@ PG_LWLOCK(49, WALSummarizer)\n PG_LWLOCK(50, DSMRegistry)\n PG_LWLOCK(51, InjectionPoint)\n PG_LWLOCK(52, SerialControl)\n+PG_LWLOCK(53, ClusteredRels)\ndiff --git a/src/include/utils/backend_progress.h b/src/include/utils/backend_progress.h\nindex e09598eafc..5ab5df9d41 100644\n--- a/src/include/utils/backend_progress.h\n+++ b/src/include/utils/backend_progress.h\n@@ -35,7 +35,7 @@ typedef enum ProgressCommandType\n \n /*\n * Any command which wishes can advertise that it is running by setting\n- * command, command_target, and param[]. command_target should be the OID of\n+ * ommand, command_target, and param[]. command_target should be the OID of\n * the relation which the command targets (we assume there's just one, as this\n * is meant for utility commands), but the meaning of each element in the\n * param array is command-specific.\n@@ -55,6 +55,7 @@ extern void pgstat_progress_parallel_incr_param(int index, int64 incr);\n extern void pgstat_progress_update_multi_param(int nparam, const int *index,\n \t\t\t\t\t\t\t\t\t\t\t const int64 *val);\n extern void pgstat_progress_end_command(void);\n+extern void pgstat_progress_restore_state(PgBackendProgress *backup);\n \n \n #endif\t\t\t\t\t\t\t/* BACKEND_PROGRESS_H */\ndiff --git a/src/include/utils/inval.h b/src/include/utils/inval.h\nindex 24695facf2..4acf9d0ed9 100644\n--- a/src/include/utils/inval.h\n+++ b/src/include/utils/inval.h\n@@ -42,6 +42,8 @@ extern void CacheInvalidateCatalog(Oid catalogId);\n \n extern void CacheInvalidateRelcache(Relation relation);\n \n+extern void CacheInvalidateRelcacheImmediate(Relation relation);\n+\n extern void CacheInvalidateRelcacheAll(void);\n \n extern void CacheInvalidateRelcacheByTuple(HeapTuple classTuple);\ndiff --git a/src/include/utils/rel.h b/src/include/utils/rel.h\nindex 8700204953..adda46c985 100644\n--- a/src/include/utils/rel.h\n+++ b/src/include/utils/rel.h\n@@ -253,6 +253,9 @@ typedef struct RelationData\n \tbool\t\tpgstat_enabled; /* should relation stats be counted */\n \t/* use \"struct\" here to avoid needing to include pgstat.h: */\n \tstruct PgStat_TableStatus *pgstat_info; /* statistics collection area */\n+\n+\t/* Is CLUSTER CONCURRENTLY being performed on this relation? */\n+\tbool\trd_cluster_concurrent;\n } RelationData;\n \n \n@@ -684,7 +687,9 @@ RelationCloseSmgr(Relation relation)\n #define RelationIsAccessibleInLogicalDecoding(relation) \\\n \t(XLogLogicalInfoActive() && \\\n \t RelationNeedsWAL(relation) && \\\n-\t (IsCatalogRelation(relation) || RelationIsUsedAsCatalogTable(relation)))\n+\t (IsCatalogRelation(relation) || \\\n+\t RelationIsUsedAsCatalogTable(relation) || \\\n+\t (relation)->rd_cluster_concurrent))\n \n /*\n * RelationIsLogicallyLogged\ndiff --git a/src/include/utils/snapmgr.h b/src/include/utils/snapmgr.h\nindex 9398a84051..f58c9108fc 100644\n--- a/src/include/utils/snapmgr.h\n+++ b/src/include/utils/snapmgr.h\n@@ -68,6 +68,9 @@ extern Snapshot GetLatestSnapshot(void);\n extern void SnapshotSetCommandId(CommandId curcid);\n extern Snapshot GetOldestSnapshot(void);\n \n+extern Snapshot CopySnapshot(Snapshot snapshot);\n+extern void FreeSnapshot(Snapshot snapshot);\n+\n extern Snapshot GetCatalogSnapshot(Oid relid);\n extern Snapshot GetNonHistoricCatalogSnapshot(Oid relid);\n extern void InvalidateCatalogSnapshot(void);\ndiff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out\nindex 4c789279e5..22cb0702dc 100644\n--- a/src/test/regress/expected/rules.out\n+++ b/src/test/regress/expected/rules.out\n@@ -1958,17 +1958,20 @@ pg_stat_progress_cluster| SELECT s.pid,\n WHEN 2 THEN 'index scanning heap'::text\n WHEN 3 THEN 'sorting tuples'::text\n WHEN 4 THEN 'writing new heap'::text\n- WHEN 5 THEN 'swapping relation files'::text\n- WHEN 6 THEN 'rebuilding index'::text\n- WHEN 7 THEN 'performing final cleanup'::text\n+ WHEN 5 THEN 'catch-up'::text\n+ WHEN 6 THEN 'swapping relation files'::text\n+ WHEN 7 THEN 'rebuilding index'::text\n+ WHEN 8 THEN 'performing final cleanup'::text\n ELSE NULL::text\n END AS phase,\n (s.param3)::oid AS cluster_index_relid,\n s.param4 AS heap_tuples_scanned,\n- s.param5 AS heap_tuples_written,\n- s.param6 AS heap_blks_total,\n- s.param7 AS heap_blks_scanned,\n- s.param8 AS index_rebuild_count\n+ s.param5 AS heap_tuples_inserted,\n+ s.param6 AS heap_tuples_updated,\n+ s.param7 AS heap_tuples_deleted,\n+ s.param8 AS heap_blks_total,\n+ s.param9 AS heap_blks_scanned,\n+ s.param10 AS index_rebuild_count\n FROM (pg_stat_get_progress_info('CLUSTER'::text) s(pid, datid, relid, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, param11, param12, param13, param14, param15, param16, param17, param18, param19, param20)\n LEFT JOIN pg_database d ON ((s.datid = d.oid)));\n pg_stat_progress_copy| SELECT s.pid,\n-- \n2.45.2",
"msg_date": "Tue, 09 Jul 2024 17:55:58 +0200",
"msg_from": "Antonin Houska <ah@cybertec.at>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "Antonin Houska <ah@cybertec.at> wrote:\n\n> Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> \n> > > Is your plan to work on it soon or should I try to write a draft patch? (I\n> > > assume this is for PG >= 18.)\n> > \n> > I don't have plans for it, so if you have resources, please go for it.\n> \n> The first version is attached. The actual feature is in 0003. 0004 is probably\n> not necessary now, but I haven't realized until I coded it.\n\nThe mailing list archive indicates something is wrong with the 0003\nattachment. Sending it all again, as *.tar.\n\n-- \nAntonin Houska\nWeb: https://www.cybertec-postgresql.com",
"msg_date": "Tue, 09 Jul 2024 18:03:29 +0200",
"msg_from": "Antonin Houska <ah@cybertec.at>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "On 2024-Jul-09, Antonin Houska wrote:\n\n> Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> \n> > > Is your plan to work on it soon or should I try to write a draft patch? (I\n> > > assume this is for PG >= 18.)\n> > \n> > I don't have plans for it, so if you have resources, please go for it.\n> \n> The first version is attached. The actual feature is in 0003. 0004 is probably\n> not necessary now, but I haven't realized until I coded it.\n\nThank you, this is great. I'll be studying this during the next\ncommitfest.\n\n\nBTW I can apply 0003 from this email perfectly fine, but you're right\nthat the archives don't show the file name. I suspect the\n\"Content-Disposition: inline\" PLUS the Content-Type text/plain are what\ncause the problem -- for instance, [1] doesn't have a problem and they\ndo have inline content disposition, but the content-type is not\ntext/plain. In any case, I encourage you not to send patches as\ntarballs :-)\n\n[1] https://postgr.es/m/32781.1714378236@antos\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": "Tue, 9 Jul 2024 19:30:48 +0200",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n\n> On 2024-Jul-09, Antonin Houska wrote:\n> \n> > Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> > \n> > > > Is your plan to work on it soon or should I try to write a draft patch? (I\n> > > > assume this is for PG >= 18.)\n> > > \n> > > I don't have plans for it, so if you have resources, please go for it.\n> > \n> > The first version is attached. The actual feature is in 0003. 0004 is probably\n> > not necessary now, but I haven't realized until I coded it.\n> \n> Thank you, this is great. I'll be studying this during the next\n> commitfest.\n\nThanks. I'll register it in the CF application.\n\n\n> BTW I can apply 0003 from this email perfectly fine, but you're right\n> that the archives don't show the file name. I suspect the\n> \"Content-Disposition: inline\" PLUS the Content-Type text/plain are what\n> cause the problem -- for instance, [1] doesn't have a problem and they\n> do have inline content disposition, but the content-type is not\n> text/plain. In any case, I encourage you not to send patches as\n> tarballs :-)\n> \n> [1] https://postgr.es/m/32781.1714378236@antos\n\nYou're right, \"Content-Disposition\" is the problem. I forgot that \"attachment\"\nis better for patches and my email client (emacs+nmh) defaults to\n\"inline\". I'll pay attention next time.\n\n\n-- \nAntonin Houska\nWeb: https://www.cybertec-postgresql.com\n\n\n",
"msg_date": "Wed, 10 Jul 2024 08:56:27 +0200",
"msg_from": "Antonin Houska <ah@cybertec.at>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "Hi!\nI'm interested in the vacuum concurrently feature being inside the\ncore, so will try to review patch set and give valuable feedback. For\nnow, just a few little thoughts..\n\n\n> The first version is attached. The actual feature is in 0003. 0004 is probably\n> not necessary now, but I haven't realized until I coded it.\n\nThe logical replication vacuum approach is a really smart idea, I like\nit. As far as I understand, pg_squeeze works well in real production\ndatabases, which\ngives us hope that the vacuum concurrent feature in core will be good\ntoo... What is the size of the biggest relation successfully vacuumed\nvia pg_squeeze?\nLooks like in case of big relartion or high insertion load,\nreplication may lag and never catch up...\n\nHowever, in general, the 3rd patch is really big, very hard to\ncomprehend. Please consider splitting this into smaller (and\nreviewable) pieces.\nAlso, we obviously need more tests on this. Both tap-test and\nregression tests I suppose.\n\nOne more thing is about pg_squeeze background workers. They act in an\nautovacuum-like fashion, aren't they? Maybe we can support this kind\nof relation processing in core too?\n\n\n",
"msg_date": "Sun, 21 Jul 2024 20:13:11 +0500",
"msg_from": "Kirill Reshke <reshkekirill@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "Hi\n\nne 21. 7. 2024 v 17:13 odesílatel Kirill Reshke <reshkekirill@gmail.com>\nnapsal:\n\n> Hi!\n> I'm interested in the vacuum concurrently feature being inside the\n> core, so will try to review patch set and give valuable feedback. For\n> now, just a few little thoughts..\n>\n>\n>\n> One more thing is about pg_squeeze background workers. They act in an\n> autovacuum-like fashion, aren't they? Maybe we can support this kind\n> of relation processing in core too?\n>\n\nI don't think it is necessary when this feature will be an internal\nfeature.\n\nI agree so this feature is very important, I proposed it (and I very happy\nso Tonda implemented it), but I am not sure, if usage of this should be\nautomatized, and if it should be, then\n\na) probably autovacuum should do,\nb) we can move a discussion after vacuum full concurrently will be merged\nto upstream, please. Isn't very practical to have too many open targets.\n\nRegards\n\nPavel\n\nHine 21. 7. 2024 v 17:13 odesílatel Kirill Reshke <reshkekirill@gmail.com> napsal:Hi!\nI'm interested in the vacuum concurrently feature being inside the\ncore, so will try to review patch set and give valuable feedback. For\nnow, just a few little thoughts..\n\n\nOne more thing is about pg_squeeze background workers. They act in an\nautovacuum-like fashion, aren't they? Maybe we can support this kind\nof relation processing in core too?I don't think it is necessary when this feature will be an internal feature. I agree so this feature is very important, I proposed it (and I very happy so Tonda implemented it), but I am not sure, if usage of this should be automatized, and if it should be, then a) probably autovacuum should do,b) we can move a discussion after vacuum full concurrently will be merged to upstream, please. Isn't very practical to have too many open targets.RegardsPavel",
"msg_date": "Sun, 21 Jul 2024 17:23:24 +0200",
"msg_from": "Pavel Stehule <pavel.stehule@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "> Also, we obviously need more tests on this. Both tap-test and\n> regression tests I suppose.\n\nThe one simple test to this patch can be done this way:\n\n1) create test relation (call it vac_conc_r1 for example) and fill it\nwith dead tuples (insert + update or insert + delete)\n2) create injection point preventing concurrent vacuum from compiling.\n3) run concurrent vacuum (VACUUM FULL CONCURRENTLY) in separate thread\nor in some other async way.\n4) Insert new data in relation to vac_conc_r1.\n5) Release injection point, assert that vacuum completed successfully.\n6) check that all data is present in vac_conc_r1 (data from step 1 and\nfrom step 4).\n\nThis way we can catch some basic buggs, if some paths of VACUUM\nCONCURRENTLY will be touched in the future.\nThe problem with this test is: i don't know how to do anything async\nin current TAP tests (needed in step 3). Also, maybe test with async\ninteraction\nmay be too flappy (producing false negative flaps) to support.\nSequential test for this feature would be much better, but I can't\nthink of one.\n\nAlso, should we create a cf entry for this thread already?\n\n\n",
"msg_date": "Mon, 22 Jul 2024 13:23:03 +0500",
"msg_from": "Kirill Reshke <reshkekirill@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "On Mon, Jul 22, 2024 at 01:23:03PM +0500, Kirill Reshke wrote:\n> Also, should we create a cf entry for this thread already?\n\nI was wondering about this as well, but there is one for the upcoming\ncommitfest already:\n\nhttps://commitfest.postgresql.org/49/5117/\n\n\nMichael\n\n\n",
"msg_date": "Mon, 22 Jul 2024 11:53:58 +0200",
"msg_from": "Michael Banck <mbanck@gmx.net>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "Hi!\n\nOn Tue, 30 Jan 2024 at 15:31, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n\n> FWIW a newer, more modern and more trustworthy alternative to pg_repack\n> is pg_squeeze, which I discovered almost by random chance, and soon\n> discovered I liked it much more.\n\nCan you please clarify this a bit more? What is the exact reason for\npg_squeeze being more trustworthy than pg_repack?\nIs there something about the logical replication approach that makes\nit more bulletproof than the trigger-based repack approach?\n\nAlso, I was thinking about pg_repack vs pg_squeeze being used for the\nVACUUM FULL CONCURRENTLY feature, and I'm a bit suspicious about the\nlatter.\nIf I understand correctly, we essentially parse the whole WAL to\nobtain info about one particular relation changes. That may be a big\noverhead, whereas the trigger approach does\nnot suffer from this. So, there is the chance that VACUUM FULL\nCONCURRENTLY will never keep up with vacuumed relation changes. Am I\nright?\n\n\n",
"msg_date": "Thu, 25 Jul 2024 15:02:28 +0500",
"msg_from": "Kirill Reshke <reshkekirill@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "Kirill Reshke <reshkekirill@gmail.com> wrote:\n\n> Also, I was thinking about pg_repack vs pg_squeeze being used for the\n> VACUUM FULL CONCURRENTLY feature, and I'm a bit suspicious about the\n> latter.\n\n> If I understand correctly, we essentially parse the whole WAL to\n> obtain info about one particular relation changes. That may be a big\n> overhead,\n\npg_squeeze is an extension but the logical decoding is performed by the core,\nso there is no way to ensure that data changes of the \"other tables\" are not\ndecoded. However, it might be possible if we integrate the functionality into\nthe core. I'll consider doing so in the next version of [1].\n\n> whereas the trigger approach does not suffer from this. So, there is the\n> chance that VACUUM FULL CONCURRENTLY will never keep up with vacuumed\n> relation changes. Am I right?\n\nPerhaps it can happen, but note that trigger processing is also not free and\nthat in this case the cost is paid by the applications. So while VACUUM FULL\nCONCURRENTLY (based on logical decoding) might fail to catch-up, the trigger\nbased solution may slow down the applications that execute DML commands while\nthe table is being rewritten.\n\n[1] https://commitfest.postgresql.org/49/5117/\n\n-- \nAntonin Houska\nWeb: https://www.cybertec-postgresql.com\n\n\n",
"msg_date": "Wed, 31 Jul 2024 17:25:45 +0200",
"msg_from": "Antonin Houska <ah@cybertec.at>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "Kirill Reshke <reshkekirill@gmail.com> wrote:\n\n> What is the size of the biggest relation successfully vacuumed\n> via pg_squeeze?\n> Looks like in case of big relartion or high insertion load,\n> replication may lag and never catch up...\n\nUsers reports problems rather than successes, so I don't know. 400 GB was\nreported in [1] but it's possible that the table size for this test was\ndetermined based on available disk space.\n\nI think that the amount of data changes performed during the \"squeezing\"\nmatters more than the table size. In [2] one user reported \"thounsands of\nUPSERTs per second\", but the amount of data also depends on row size, which he\ndidn't mention.\n\npg_squeeze gives up if it fails to catch up a few times. The first version of\nmy patch does not check this, I'll add the corresponding code in the next\nversion.\n\n> However, in general, the 3rd patch is really big, very hard to\n> comprehend. Please consider splitting this into smaller (and\n> reviewable) pieces.\n\nI'll try to move some preparation steps into separate diffs, but not sure if\nthat will make the main diff much smaller. I prefer self-contained patches, as\nalso explained in [3].\n\n> Also, we obviously need more tests on this. Both tap-test and\n> regression tests I suppose.\n\nSure. The next version will use the injection points to test if \"concurrent\ndata changes\" are processed correctly.\n\n> One more thing is about pg_squeeze background workers. They act in an\n> autovacuum-like fashion, aren't they? Maybe we can support this kind\n> of relation processing in core too?\n\nMaybe later. Even just adding the CONCURRENTLY option to CLUSTER and VACUUM\nFULL requires quite some effort.\n\n\n[1] https://github.com/cybertec-postgresql/pg_squeeze/issues/51\n\n[2]\nhttps://github.com/cybertec-postgresql/pg_squeeze/issues/21#issuecomment-514495369\n\n[3] http://peter.eisentraut.org/blog/2024/05/14/when-to-split-patches-for-postgresql\n\n-- \nAntonin Houska\nWeb: https://www.cybertec-postgresql.com\n\n\n",
"msg_date": "Fri, 02 Aug 2024 08:09:26 +0200",
"msg_from": "Antonin Houska <ah@cybertec.at>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "On Fri, 2 Aug 2024 at 11:09, Antonin Houska <ah@cybertec.at> wrote:\n>\n> Kirill Reshke <reshkekirill@gmail.com> wrote:\n> > However, in general, the 3rd patch is really big, very hard to\n> > comprehend. Please consider splitting this into smaller (and\n> > reviewable) pieces.\n>\n> I'll try to move some preparation steps into separate diffs, but not sure if\n> that will make the main diff much smaller. I prefer self-contained patches, as\n> also explained in [3].\n\nThanks for sharing [3], it is a useful link.\n\nThere is actually one more case when ACCESS EXCLUSIVE is held: during\ntable rewrite (AT set TAM, AT set Tablespace and AT alter column type\nare some examples).\nThis can be done CONCURRENTLY too, using the same logical replication\napproach, or do I miss something?\nI'm not saying we must do it immediately, this should be a separate\nthread, but we can do some preparation work here.\n\nI can see that a bunch of functions which are currently placed in\ncluster.c can be moved to something like\nlogical_rewrite_heap.c. ConcurrentChange struct and\napply_concurrent_insert function is one example of such.\n\nSo, if this is the case, 0003 patch can be splitted in two:\nThe first one is general utility code for logical table rewrite\nThe second one with actual VACUUM CONCURRENTLY feature.\n\nWhat do you think?\n\n\n",
"msg_date": "Fri, 2 Aug 2024 12:28:54 +0500",
"msg_from": "Kirill Reshke <reshkekirill@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "Attached is version 2, the feature itself is now in 0004.\n\nUnlike version 1, it contains some regression tests (0006) and a new GUC to\ncontrol how long the AccessExclusiveLock may be held (0007).\n\nKirill Reshke <reshkekirill@gmail.com> wrote:\n\n> On Fri, 2 Aug 2024 at 11:09, Antonin Houska <ah@cybertec.at> wrote:\n> >\n> > Kirill Reshke <reshkekirill@gmail.com> wrote:\n> > > However, in general, the 3rd patch is really big, very hard to\n> > > comprehend. Please consider splitting this into smaller (and\n> > > reviewable) pieces.\n> >\n> > I'll try to move some preparation steps into separate diffs, but not sure if\n> > that will make the main diff much smaller. I prefer self-contained patches, as\n> > also explained in [3].\n> \n> Thanks for sharing [3], it is a useful link.\n> \n> There is actually one more case when ACCESS EXCLUSIVE is held: during\n> table rewrite (AT set TAM, AT set Tablespace and AT alter column type\n> are some examples).\n> This can be done CONCURRENTLY too, using the same logical replication\n> approach, or do I miss something?\n\nYes, the logical replication can potentially be used in other cases.\n\n> I'm not saying we must do it immediately, this should be a separate\n> thread, but we can do some preparation work here.\n> \n> I can see that a bunch of functions which are currently placed in\n> cluster.c can be moved to something like\n> logical_rewrite_heap.c. ConcurrentChange struct and\n> apply_concurrent_insert function is one example of such.\n> \n> So, if this is the case, 0003 patch can be splitted in two:\n> The first one is general utility code for logical table rewrite\n> The second one with actual VACUUM CONCURRENTLY feature.\n\n> What do you think?\n\nI can imagine moving the function process_concurrent_changes() and subroutines\nto a different file (e.g. rewriteheap.c), but moving it into a separate diff\nthat does not contain any call of the function makes little sense to me. Such\na diff would not add any useful functionality and could not be considered\nrefactoring either.\n\nSo far I at least moved some code to separate diffs: 0003 and 0005. I'll move\nmore if I find sensible opportunity in the future.\n\n-- \nAntonin Houska\nWeb: https://www.cybertec-postgresql.com",
"msg_date": "Tue, 27 Aug 2024 14:00:50 +0200",
"msg_from": "Antonin Houska <ah@cybertec.at>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "Hi,\n\nOn Tue, Aug 27, 2024 at 8:01 PM Antonin Houska <ah@cybertec.at> wrote:\n>\n> Attached is version 2, the feature itself is now in 0004.\n>\n> Unlike version 1, it contains some regression tests (0006) and a new GUC to\n> control how long the AccessExclusiveLock may be held (0007).\n>\n> Kirill Reshke <reshkekirill@gmail.com> wrote:\n>\n> > On Fri, 2 Aug 2024 at 11:09, Antonin Houska <ah@cybertec.at> wrote:\n> > >\n> > > Kirill Reshke <reshkekirill@gmail.com> wrote:\n> > > > However, in general, the 3rd patch is really big, very hard to\n> > > > comprehend. Please consider splitting this into smaller (and\n> > > > reviewable) pieces.\n> > >\n> > > I'll try to move some preparation steps into separate diffs, but not sure if\n> > > that will make the main diff much smaller. I prefer self-contained patches, as\n> > > also explained in [3].\n> >\n> > Thanks for sharing [3], it is a useful link.\n> >\n> > There is actually one more case when ACCESS EXCLUSIVE is held: during\n> > table rewrite (AT set TAM, AT set Tablespace and AT alter column type\n> > are some examples).\n> > This can be done CONCURRENTLY too, using the same logical replication\n> > approach, or do I miss something?\n>\n> Yes, the logical replication can potentially be used in other cases.\n>\n> > I'm not saying we must do it immediately, this should be a separate\n> > thread, but we can do some preparation work here.\n> >\n> > I can see that a bunch of functions which are currently placed in\n> > cluster.c can be moved to something like\n> > logical_rewrite_heap.c. ConcurrentChange struct and\n> > apply_concurrent_insert function is one example of such.\n> >\n> > So, if this is the case, 0003 patch can be splitted in two:\n> > The first one is general utility code for logical table rewrite\n> > The second one with actual VACUUM CONCURRENTLY feature.\n>\n> > What do you think?\n>\n> I can imagine moving the function process_concurrent_changes() and subroutines\n> to a different file (e.g. rewriteheap.c), but moving it into a separate diff\n> that does not contain any call of the function makes little sense to me. Such\n> a diff would not add any useful functionality and could not be considered\n> refactoring either.\n>\n> So far I at least moved some code to separate diffs: 0003 and 0005. I'll move\n> more if I find sensible opportunity in the future.\n>\n> --\n> Antonin Houska\n> Web: https://www.cybertec-postgresql.com\n>\n\nThanks for working on this, I think this is a very useful feature.\n\nThe patch doesn't compile in the debug build with errors:\n\n../postgres/src/backend/commands/cluster.c: In function ‘get_catalog_state’:\n../postgres/src/backend/commands/cluster.c:2771:33: error: declaration\nof ‘td_src’ shadows a previous local [-Werror=shadow=compatible-local]\n2771 | TupleDesc td_src, td_dst;\n| ^~~~~~\n../postgres/src/backend/commands/cluster.c:2741:25: note: shadowed\ndeclaration is here\n2741 | TupleDesc td_src = RelationGetDescr(rel);\n\nyou forgot the meson build for pgoutput_cluster\n\ndiff --git a/src/backend/meson.build b/src/backend/meson.build\nindex 78c5726814..0f9141a4ac 100644\n--- a/src/backend/meson.build\n+++ b/src/backend/meson.build\n@@ -194,5 +194,6 @@ pg_test_mod_args = pg_mod_args + {\n subdir('jit/llvm')\n subdir('replication/libpqwalreceiver')\n subdir('replication/pgoutput')\n+subdir('replication/pgoutput_cluster')\n\nI noticed that you use lmode/lock_mode/lockmode, there are lmode and lockmode\nin the codebase, but I remember someone proposed all changes to lockmode, how\nabout sticking to lockmode in your patch?\n\n0004:\n\n+ sure that the old files do not change during the processing because the\n+ chnages would get lost due to the swap.\ntypo\n\n+ files. The data changes that took place during the creation of the new\n+ table and index files are captured using logical decoding\n+ (<xref linkend=\"logicaldecoding\"/>) and applied before\n+ the <literal>ACCESS EXCLUSIVE</literal> lock is requested. Thus the lock\n+ is typically held only for the time needed to swap the files, which\n+ should be pretty short.\n\nI remember pg_squeeze also did some logical decoding after getting the exclusive\nlock, if that is still true, I guess the doc above is not precise.\n\n+ Note that <command>CLUSTER</command> with the\n+ the <literal>CONCURRENTLY</literal> option does not try to order the\n+ rows inserted into the table after the clustering started.\n\nDo you mean after the *logical decoding* started here? If CLUSTER CONCURRENTLY\ndoes not order rows at all, why bother implementing it?\n\n+ errhint(\"CLUSTER CONCURRENTLY is only allowed for permanent relations\")));\n\nerrhint messages should end with a dot. Why hardcoded to \"CLUSTER CONCURRENTLY\"\ninstead of parameter *stmt*.\n\n+ ResourceOwner oldowner = CurrentResourceOwner;\n+\n+ /*\n+ * In the CONCURRENT case, do the planning in a subtrensaction so that\ntypo\n\nI did not see VacuumStmt changes in gram.y, how do we suppose to\nuse the vacuum full concurrently? I tried the following but no success.\n\n[local] postgres@demo:5432-36097=# vacuum (concurrently) aircrafts_data;\nERROR: CONCURRENTLY can only be specified with VACUUM FULL\n\n[local] postgres@demo:5432-36097=# vacuum full (concurrently) full\naircrafts_data;\nERROR: syntax error at or near \"(\"\nLINE 1: vacuum full (concurrently) full aircrafts_data;\n\n\n-- \nRegards\nJunwang Zhao\n\n\n",
"msg_date": "Fri, 30 Aug 2024 18:18:12 +0800",
"msg_from": "Junwang Zhao <zhjwpku@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "Junwang Zhao <zhjwpku@gmail.com> wrote:\n\n> Thanks for working on this, I think this is a very useful feature.\n> \n> The patch doesn't compile in the debug build with errors:\n> \n> ../postgres/src/backend/commands/cluster.c: In function ‘get_catalog_state’:\n> ../postgres/src/backend/commands/cluster.c:2771:33: error: declaration\n> of ‘td_src’ shadows a previous local [-Werror=shadow=compatible-local]\n> 2771 | TupleDesc td_src, td_dst;\n> | ^~~~~~\n> ../postgres/src/backend/commands/cluster.c:2741:25: note: shadowed\n> declaration is here\n> 2741 | TupleDesc td_src = RelationGetDescr(rel);\n\nok, gcc14 complains here, the compiler I used before did not. Fixed.\n\n> you forgot the meson build for pgoutput_cluster\n> \n> diff --git a/src/backend/meson.build b/src/backend/meson.build\n> index 78c5726814..0f9141a4ac 100644\n> --- a/src/backend/meson.build\n> +++ b/src/backend/meson.build\n> @@ -194,5 +194,6 @@ pg_test_mod_args = pg_mod_args + {\n> subdir('jit/llvm')\n> subdir('replication/libpqwalreceiver')\n> subdir('replication/pgoutput')\n> +subdir('replication/pgoutput_cluster')\n\nFixed, thanks. That might be the reason for the cfbot to fail when using\nmeson.\n\n> I noticed that you use lmode/lock_mode/lockmode, there are lmode and lockmode\n> in the codebase, but I remember someone proposed all changes to lockmode, how\n> about sticking to lockmode in your patch?\n\nFixed.\n\n> 0004:\n> \n> + sure that the old files do not change during the processing because the\n> + chnages would get lost due to the swap.\n> typo\n\nFixed.\n\n> \n> + files. The data changes that took place during the creation of the new\n> + table and index files are captured using logical decoding\n> + (<xref linkend=\"logicaldecoding\"/>) and applied before\n> + the <literal>ACCESS EXCLUSIVE</literal> lock is requested. Thus the lock\n> + is typically held only for the time needed to swap the files, which\n> + should be pretty short.\n> \n> I remember pg_squeeze also did some logical decoding after getting the exclusive\n> lock, if that is still true, I guess the doc above is not precise.\n\nThe decoding takes place before requesting the lock, as well as after\nthat. I've adjusted the paragraph, see 0007.\n\n> + Note that <command>CLUSTER</command> with the\n> + the <literal>CONCURRENTLY</literal> option does not try to order the\n> + rows inserted into the table after the clustering started.\n> \n> Do you mean after the *logical decoding* started here? If CLUSTER CONCURRENTLY\n> does not order rows at all, why bother implementing it?\n\nThe rows inserted before CLUSTER (CONCURRENTLY) started do get ordered, the\nrows inserted after that do not. (Actually what matters is when the snapshot\nfor the initial load is created, but that happens in very early stage of the\nprocessing. Not sure if user is interested in such implementation details.)\n\n\n> + errhint(\"CLUSTER CONCURRENTLY is only allowed for permanent relations\")));\n> \n> errhint messages should end with a dot. Why hardcoded to \"CLUSTER CONCURRENTLY\"\n> instead of parameter *stmt*.\n\nFixed.\n\n> + ResourceOwner oldowner = CurrentResourceOwner;\n> +\n> + /*\n> + * In the CONCURRENT case, do the planning in a subtrensaction so that\n> typo\n\nFixed.\n\n> I did not see VacuumStmt changes in gram.y, how do we suppose to\n> use the vacuum full concurrently? I tried the following but no success.\n\nWith the \"parethesized syntax\", new options can be added w/o changing\ngram.y. (While the \"unparenthesized syntax\" is deprecated.)\n\n> [local] postgres@demo:5432-36097=# vacuum (concurrently) aircrafts_data;\n> ERROR: CONCURRENTLY can only be specified with VACUUM FULL\n\nThe \"lazy\" VACUUM works concurrently as such.\n\n> [local] postgres@demo:5432-36097=# vacuum full (concurrently) full\n> aircrafts_data;\n> ERROR: syntax error at or near \"(\"\n> LINE 1: vacuum full (concurrently) full aircrafts_data;\n\nThis is not specific to the CONCURRENTLY option. For example:\n\npostgres=3D# vacuum full (analyze) full aircrafts_data;\nERROR: syntax error at or near \"(\"\nLINE 1: vacuum full (analyze) full aircrafts_data;\n\n(You seem to combine the parenthesized syntax with the unparenthesized.)\n\n-- \nAntonin Houska\nWeb: https://www.cybertec-postgresql.com",
"msg_date": "Wed, 04 Sep 2024 13:41:35 +0200",
"msg_from": "Antonin Houska <ah@cybertec.at>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "While trying to figure out why the regression tests fail sometimes on the\ncfbot (not sure yet about the reason), I fixed some confusions in\nbegin_concurrent_cluster() and end_concurrent_cluster(). Those functions\nshould be a bit easier to understand now.\n\n-- \nAntonin Houska\nWeb: https://www.cybertec-postgresql.com",
"msg_date": "Fri, 06 Sep 2024 10:08:35 +0200",
"msg_from": "Antonin Houska <ah@cybertec.at>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
},
{
"msg_contents": "On Wed, Sep 4, 2024 at 7:41 PM Antonin Houska <ah@cybertec.at> wrote:\n>\n> Junwang Zhao <zhjwpku@gmail.com> wrote:\n>\n> > Thanks for working on this, I think this is a very useful feature.\n> >\n> > The patch doesn't compile in the debug build with errors:\n> >\n> > ../postgres/src/backend/commands/cluster.c: In function ‘get_catalog_state’:\n> > ../postgres/src/backend/commands/cluster.c:2771:33: error: declaration\n> > of ‘td_src’ shadows a previous local [-Werror=shadow=compatible-local]\n> > 2771 | TupleDesc td_src, td_dst;\n> > | ^~~~~~\n> > ../postgres/src/backend/commands/cluster.c:2741:25: note: shadowed\n> > declaration is here\n> > 2741 | TupleDesc td_src = RelationGetDescr(rel);\n>\n> ok, gcc14 complains here, the compiler I used before did not. Fixed.\n>\n> > you forgot the meson build for pgoutput_cluster\n> >\n> > diff --git a/src/backend/meson.build b/src/backend/meson.build\n> > index 78c5726814..0f9141a4ac 100644\n> > --- a/src/backend/meson.build\n> > +++ b/src/backend/meson.build\n> > @@ -194,5 +194,6 @@ pg_test_mod_args = pg_mod_args + {\n> > subdir('jit/llvm')\n> > subdir('replication/libpqwalreceiver')\n> > subdir('replication/pgoutput')\n> > +subdir('replication/pgoutput_cluster')\n>\n> Fixed, thanks. That might be the reason for the cfbot to fail when using\n> meson.\n>\n> > I noticed that you use lmode/lock_mode/lockmode, there are lmode and lockmode\n> > in the codebase, but I remember someone proposed all changes to lockmode, how\n> > about sticking to lockmode in your patch?\n>\n> Fixed.\n>\n> > 0004:\n> >\n> > + sure that the old files do not change during the processing because the\n> > + chnages would get lost due to the swap.\n> > typo\n>\n> Fixed.\n>\n> >\n> > + files. The data changes that took place during the creation of the new\n> > + table and index files are captured using logical decoding\n> > + (<xref linkend=\"logicaldecoding\"/>) and applied before\n> > + the <literal>ACCESS EXCLUSIVE</literal> lock is requested. Thus the lock\n> > + is typically held only for the time needed to swap the files, which\n> > + should be pretty short.\n> >\n> > I remember pg_squeeze also did some logical decoding after getting the exclusive\n> > lock, if that is still true, I guess the doc above is not precise.\n>\n> The decoding takes place before requesting the lock, as well as after\n> that. I've adjusted the paragraph, see 0007.\n>\n> > + Note that <command>CLUSTER</command> with the\n> > + the <literal>CONCURRENTLY</literal> option does not try to order the\n> > + rows inserted into the table after the clustering started.\n> >\n> > Do you mean after the *logical decoding* started here? If CLUSTER CONCURRENTLY\n> > does not order rows at all, why bother implementing it?\n>\n> The rows inserted before CLUSTER (CONCURRENTLY) started do get ordered, the\n> rows inserted after that do not. (Actually what matters is when the snapshot\n> for the initial load is created, but that happens in very early stage of the\n> processing. Not sure if user is interested in such implementation details.)\n>\n>\n> > + errhint(\"CLUSTER CONCURRENTLY is only allowed for permanent relations\")));\n> >\n> > errhint messages should end with a dot. Why hardcoded to \"CLUSTER CONCURRENTLY\"\n> > instead of parameter *stmt*.\n>\n> Fixed.\n>\n> > + ResourceOwner oldowner = CurrentResourceOwner;\n> > +\n> > + /*\n> > + * In the CONCURRENT case, do the planning in a subtrensaction so that\n> > typo\n>\n> Fixed.\n>\n> > I did not see VacuumStmt changes in gram.y, how do we suppose to\n> > use the vacuum full concurrently? I tried the following but no success.\n>\n> With the \"parethesized syntax\", new options can be added w/o changing\n> gram.y. (While the \"unparenthesized syntax\" is deprecated.)\n>\n> > [local] postgres@demo:5432-36097=# vacuum (concurrently) aircrafts_data;\n> > ERROR: CONCURRENTLY can only be specified with VACUUM FULL\n>\n> The \"lazy\" VACUUM works concurrently as such.\n>\n> > [local] postgres@demo:5432-36097=# vacuum full (concurrently) full\n> > aircrafts_data;\n> > ERROR: syntax error at or near \"(\"\n> > LINE 1: vacuum full (concurrently) full aircrafts_data;\n>\n> This is not specific to the CONCURRENTLY option. For example:\n>\n> postgres=3D# vacuum full (analyze) full aircrafts_data;\n> ERROR: syntax error at or near \"(\"\n> LINE 1: vacuum full (analyze) full aircrafts_data;\n>\n> (You seem to combine the parenthesized syntax with the unparenthesized.)\n\nYeah, my mistake, *vacuum (full, concurrently)* works.\n\n+ if (TransactionIdIsNormal(HeapTupleHeaderGetRawXmax(tuple->t_data)) &&\n+ HeapTupleMVCCNotDeleted(tuple, snapshot, buffer))\n+ {\n+ /* TODO More work needed here?*/\n+ tuple->t_data->t_infomask |= HEAP_XMAX_INVALID;\n+ HeapTupleHeaderSetXmax(tuple->t_data, 0);\n+ }\n\nI don't quite understand the above code, IIUC xmax and xmax invalid\nare set directly on the buffer page. What if the command failed? Will\nthis break the visibility rules?\n\nbtw, v4-0006 failed to apply.\n\n>\n> --\n> Antonin Houska\n> Web: https://www.cybertec-postgresql.com\n>\n\n\n-- \nRegards\nJunwang Zhao\n\n\n",
"msg_date": "Sat, 14 Sep 2024 22:54:06 +0800",
"msg_from": "Junwang Zhao <zhjwpku@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: why there is not VACUUM FULL CONCURRENTLY?"
}
] |
[
{
"msg_contents": "Hi,\n\nI was trying to install newer Perl versions to Windows CI images and\nfound that 003_extrafiles.pl test fails on Windows with:\n\n(0.183s) not ok 2 - file lists match\n(0.000s) # Failed test 'file lists match'\n# at C:/cirrus/src/bin/pg_rewind/t/003_extrafiles.pl line 81.\n(0.000s) # Structures begin differing at:\n# $got->[0] =\n'C:/cirrus/build/testrun/pg_rewind/003_extrafiles/data/t_003_extrafiles_primary_local_data/pgdata/tst_both_dir'\n# $expected->[0] =\n'C:\\cirrus\\build/testrun/pg_rewind/003_extrafiles\\data/t_003_extrafiles_primary_local_data/pgdata/tst_both_dir'\n\n(0.263s) not ok 5 - file lists match\n(0.000s) # Failed test 'file lists match'\n# at C:/cirrus/src/bin/pg_rewind/t/003_extrafiles.pl line 81.\n(0.000s) # Structures begin differing at:\n# $got->[0] =\n'C:/cirrus/build/testrun/pg_rewind/003_extrafiles/data/t_003_extrafiles_primary_remote_data/pgdata/tst_both_dir'\n# $expected->[0] =\n'C:\\cirrus\\build/testrun/pg_rewind/003_extrafiles\\data/t_003_extrafiles_primary_remote_data/pgdata/tst_both_dir'\n\nIt looks like File::Find converts backslashes to slashes in the newer\nPerl versions. I tried to find the related commit and found this:\nhttps://github.com/Perl/perl5/commit/414f14df98cb1c9a20f92c5c54948b67c09f072d\n\nTo solve this, I did the same conversion for Windows before comparing\nthe paths. And to support all Perl versions, I decided to always\nconvert them on Windows regardless of the Perl's version. The fix is\nattached.\n\nI looked at other File::Find appearances in the code but they do not\ncompare the paths. So, I do not think there is any need to fix them.\n\nAny kind of feedback would be appreciated.\n\n--\nRegards,\nNazir Bilal Yavuz\nMicrosoft",
"msg_date": "Tue, 30 Jan 2024 14:21:57 +0300",
"msg_from": "Nazir Bilal Yavuz <byavuz81@gmail.com>",
"msg_from_op": true,
"msg_subject": "003_extrafiles.pl test fails on Windows with the newer Perl versions"
},
{
"msg_contents": "Hi,\n\nOn Tue, 30 Jan 2024 at 14:21, Nazir Bilal Yavuz <byavuz81@gmail.com> wrote:\n>\n> It looks like File::Find converts backslashes to slashes in the newer\n> Perl versions. I tried to find the related commit and found this:\n> https://github.com/Perl/perl5/commit/414f14df98cb1c9a20f92c5c54948b67c09f072d\n\nI forgot to mention that I used Strawberry Perl and these errors\nstarted with 'Perl v5.36.1.1'.\n\n-- \nRegards,\nNazir Bilal Yavuz\nMicrosoft\n\n\n",
"msg_date": "Tue, 30 Jan 2024 14:46:22 +0300",
"msg_from": "Nazir Bilal Yavuz <byavuz81@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: 003_extrafiles.pl test fails on Windows with the newer Perl\n versions"
},
{
"msg_contents": "\nOn 2024-01-30 Tu 06:21, Nazir Bilal Yavuz wrote:\n> Hi,\n>\n> I was trying to install newer Perl versions to Windows CI images and\n> found that 003_extrafiles.pl test fails on Windows with:\n>\n> (0.183s) not ok 2 - file lists match\n> (0.000s) # Failed test 'file lists match'\n> # at C:/cirrus/src/bin/pg_rewind/t/003_extrafiles.pl line 81.\n> (0.000s) # Structures begin differing at:\n> # $got->[0] =\n> 'C:/cirrus/build/testrun/pg_rewind/003_extrafiles/data/t_003_extrafiles_primary_local_data/pgdata/tst_both_dir'\n> # $expected->[0] =\n> 'C:\\cirrus\\build/testrun/pg_rewind/003_extrafiles\\data/t_003_extrafiles_primary_local_data/pgdata/tst_both_dir'\n>\n> (0.263s) not ok 5 - file lists match\n> (0.000s) # Failed test 'file lists match'\n> # at C:/cirrus/src/bin/pg_rewind/t/003_extrafiles.pl line 81.\n> (0.000s) # Structures begin differing at:\n> # $got->[0] =\n> 'C:/cirrus/build/testrun/pg_rewind/003_extrafiles/data/t_003_extrafiles_primary_remote_data/pgdata/tst_both_dir'\n> # $expected->[0] =\n> 'C:\\cirrus\\build/testrun/pg_rewind/003_extrafiles\\data/t_003_extrafiles_primary_remote_data/pgdata/tst_both_dir'\n>\n> It looks like File::Find converts backslashes to slashes in the newer\n> Perl versions. I tried to find the related commit and found this:\n> https://github.com/Perl/perl5/commit/414f14df98cb1c9a20f92c5c54948b67c09f072d\n>\n> To solve this, I did the same conversion for Windows before comparing\n> the paths. And to support all Perl versions, I decided to always\n> convert them on Windows regardless of the Perl's version. The fix is\n> attached.\n>\n> I looked at other File::Find appearances in the code but they do not\n> compare the paths. So, I do not think there is any need to fix them.\n>\n> Any kind of feedback would be appreciated.\n>\n\nLooks reasonable on the face of it. I'll see about pushing this today.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n",
"msg_date": "Tue, 30 Jan 2024 06:49:42 -0500",
"msg_from": "Andrew Dunstan <andrew@dunslane.net>",
"msg_from_op": false,
"msg_subject": "Re: 003_extrafiles.pl test fails on Windows with the newer Perl\n versions"
},
{
"msg_contents": "\nOn 2024-01-30 Tu 06:49, Andrew Dunstan wrote:\n>\n> On 2024-01-30 Tu 06:21, Nazir Bilal Yavuz wrote:\n>> Hi,\n>>\n>> I was trying to install newer Perl versions to Windows CI images and\n>> found that 003_extrafiles.pl test fails on Windows with:\n>>\n>> (0.183s) not ok 2 - file lists match\n>> (0.000s) # Failed test 'file lists match'\n>> # at C:/cirrus/src/bin/pg_rewind/t/003_extrafiles.pl line 81.\n>> (0.000s) # Structures begin differing at:\n>> # $got->[0] =\n>> 'C:/cirrus/build/testrun/pg_rewind/003_extrafiles/data/t_003_extrafiles_primary_local_data/pgdata/tst_both_dir' \n>>\n>> # $expected->[0] =\n>> 'C:\\cirrus\\build/testrun/pg_rewind/003_extrafiles\\data/t_003_extrafiles_primary_local_data/pgdata/tst_both_dir' \n>>\n>>\n>> (0.263s) not ok 5 - file lists match\n>> (0.000s) # Failed test 'file lists match'\n>> # at C:/cirrus/src/bin/pg_rewind/t/003_extrafiles.pl line 81.\n>> (0.000s) # Structures begin differing at:\n>> # $got->[0] =\n>> 'C:/cirrus/build/testrun/pg_rewind/003_extrafiles/data/t_003_extrafiles_primary_remote_data/pgdata/tst_both_dir' \n>>\n>> # $expected->[0] =\n>> 'C:\\cirrus\\build/testrun/pg_rewind/003_extrafiles\\data/t_003_extrafiles_primary_remote_data/pgdata/tst_both_dir' \n>>\n>>\n>> It looks like File::Find converts backslashes to slashes in the newer\n>> Perl versions. I tried to find the related commit and found this:\n>> https://github.com/Perl/perl5/commit/414f14df98cb1c9a20f92c5c54948b67c09f072d \n>>\n>>\n>> To solve this, I did the same conversion for Windows before comparing\n>> the paths. And to support all Perl versions, I decided to always\n>> convert them on Windows regardless of the Perl's version. The fix is\n>> attached.\n>>\n>> I looked at other File::Find appearances in the code but they do not\n>> compare the paths. So, I do not think there is any need to fix them.\n>>\n>> Any kind of feedback would be appreciated.\n>>\n>\n> Looks reasonable on the face of it. I'll see about pushing this today.\n\n\nPushed to all live branches. Thanks for the patch.\n\n\ncheers\n\n\nandrew\n\n-- \n\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n",
"msg_date": "Tue, 30 Jan 2024 17:18:49 -0500",
"msg_from": "Andrew Dunstan <andrew@dunslane.net>",
"msg_from_op": false,
"msg_subject": "Re: 003_extrafiles.pl test fails on Windows with the newer Perl\n versions"
},
{
"msg_contents": "Andrew Dunstan <andrew@dunslane.net> writes:\n> Pushed to all live branches. Thanks for the patch.\n\nv12 and v13 branches aren't looking good:\n\nGlobal symbol \"$test_primary_datadir\" requires explicit package name (did you forget to declare \"my $test_primary_datadir\"?) at t/003_extrafiles.pl line 80.\nExecution of t/003_extrafiles.pl aborted due to compilation errors.\n# Looks like your test exited with 255 before it could output anything.\n[17:19:57] t/003_extrafiles.pl .......... \nDubious, test returned 255 (wstat 65280, 0xff00)\nFailed 5/5 subtests \n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Tue, 30 Jan 2024 18:06:42 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: 003_extrafiles.pl test fails on Windows with the newer Perl\n versions"
},
{
"msg_contents": "\nOn 2024-01-30 Tu 18:06, Tom Lane wrote:\n> Andrew Dunstan <andrew@dunslane.net> writes:\n>> Pushed to all live branches. Thanks for the patch.\n> v12 and v13 branches aren't looking good:\n>\n> Global symbol \"$test_primary_datadir\" requires explicit package name (did you forget to declare \"my $test_primary_datadir\"?) at t/003_extrafiles.pl line 80.\n> Execution of t/003_extrafiles.pl aborted due to compilation errors.\n> # Looks like your test exited with 255 before it could output anything.\n> [17:19:57] t/003_extrafiles.pl ..........\n> Dubious, test returned 255 (wstat 65280, 0xff00)\n> Failed 5/5 subtests\n>\n> \t\n\n\nWill fix.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n",
"msg_date": "Tue, 30 Jan 2024 18:56:37 -0500",
"msg_from": "Andrew Dunstan <andrew@dunslane.net>",
"msg_from_op": false,
"msg_subject": "Re: 003_extrafiles.pl test fails on Windows with the newer Perl\n versions"
},
{
"msg_contents": "Hi,\n\nOn Wed, 31 Jan 2024 at 01:18, Andrew Dunstan <andrew@dunslane.net> wrote:\n>\n> Pushed to all live branches. Thanks for the patch.\n\nThanks for the push!\n\n-- \nRegards,\nNazir Bilal Yavuz\nMicrosoft\n\n\n",
"msg_date": "Wed, 31 Jan 2024 11:45:43 +0300",
"msg_from": "Nazir Bilal Yavuz <byavuz81@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: 003_extrafiles.pl test fails on Windows with the newer Perl\n versions"
},
{
"msg_contents": "Seems like the back branches are still not quite there: I'm seeing\n\nName \"PostgreSQL::Test::Utils::windows_os\" used only once: possible typo at t/003_extrafiles.pl line 74.\n\nin v12 and v13, while it's\n\nName \"PostgreSQL::Test::Utils::windows_os\" used only once: possible typo at t/003_extrafiles.pl line 85.\n\nin v14. v15 and up are OK.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Thu, 01 Feb 2024 12:32:00 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: 003_extrafiles.pl test fails on Windows with the newer Perl\n versions"
},
{
"msg_contents": "\nOn 2024-02-01 Th 12:32, Tom Lane wrote:\n> Seems like the back branches are still not quite there: I'm seeing\n>\n> Name \"PostgreSQL::Test::Utils::windows_os\" used only once: possible typo at t/003_extrafiles.pl line 74.\n>\n> in v12 and v13, while it's\n>\n> Name \"PostgreSQL::Test::Utils::windows_os\" used only once: possible typo at t/003_extrafiles.pl line 85.\n>\n> in v14. v15 and up are OK.\n>\n> \t\t\t\n\n*sigh*\n\n\nHave pushed a fix. Thanks for noticing.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n",
"msg_date": "Thu, 1 Feb 2024 15:36:09 -0500",
"msg_from": "Andrew Dunstan <andrew@dunslane.net>",
"msg_from_op": false,
"msg_subject": "Re: 003_extrafiles.pl test fails on Windows with the newer Perl\n versions"
}
] |
[
{
"msg_contents": "I noticed while answering a question that commit b577743000cd added the\nGUC scram_iterations and marked it GUC_REPORT, but failed to add it to\nthe PQparameterStatus documentation.\n\nHere's a proposed patch to add it there.\n\ndiff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml\nindex d0d5aefadc..13bd82efc6 100644\n--- a/doc/src/sgml/libpq.sgml\n+++ b/doc/src/sgml/libpq.sgml\n@@ -2521,7 +2521,8 @@ const char *PQparameterStatus(const PGconn *conn, const char *paramName);\n <varname>DateStyle</varname>,\n <varname>IntervalStyle</varname>,\n <varname>TimeZone</varname>,\n- <varname>integer_datetimes</varname>, and\n+ <varname>integer_datetimes</varname>,\n+ <varname>scram_iterations</varname>, and\n <varname>standard_conforming_strings</varname>.\n (<varname>server_encoding</varname>, <varname>TimeZone</varname>, and\n <varname>integer_datetimes</varname> were not reported by releases before 8.0;\n\n\nFurther thoughts:\n\n1. that list looks to be in random order. Should we sort it\nalphabetically?\n\n2. the notes about the versions in which some parameters started to be\nreported, look quite outdated. We don't really care about things not\nreported in 8.0 or 8.1 or even 9.0. For all purposes, it seems\nperfectly OK to say that these parameters have been reported forever\n(i.e. don't mention them in these lists). I think we should remove all\nthose, except the note about version 14.\n\n3. Should we list scram_iterations as having started to be reported with\nversion 16? The GUC didn't exist before that; but we could say that if\nit's not reported, then the application can assume that the value is\n4096 (similar to the wording for standard_conforming_strings).\n\nThanks\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"Los cuentos de hadas no dan al niño su primera idea sobre los monstruos.\nLo que le dan es su primera idea de la posible derrota del monstruo.\"\n (G. K. Chesterton)\n\n\n",
"msg_date": "Tue, 30 Jan 2024 13:36:54 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "scram_iterations is undocumented GUC_REPORT"
},
{
"msg_contents": "> On 30 Jan 2024, at 13:36, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> \n> I noticed while answering a question that commit b577743000cd added the\n> GUC scram_iterations and marked it GUC_REPORT, but failed to add it to\n> the PQparameterStatus documentation.\n\nUgh, thanks for fixing!\n\n> 1. that list looks to be in random order. Should we sort it\n> alphabetically?\n\nIt seems to have some semblance of grouping per GUC functionality, but not\nquite. I'm not sure sorting alphabetically will improve the current state\nthough.\n\n> 2. the notes about the versions in which some parameters started to be\n> reported, look quite outdated. We don't really care about things not\n> reported in 8.0 or 8.1 or even 9.0. For all purposes, it seems\n> perfectly OK to say that these parameters have been reported forever\n> (i.e. don't mention them in these lists). I think we should remove all\n> those, except the note about version 14.\n\nAgreed.\n\n> 3. Should we list scram_iterations as having started to be reported with\n> version 16?\n\nYes, similar to in_hot_standby for v14.\n\n> The GUC didn't exist before that; but we could say that if\n> it's not reported, then the application can assume that the value is\n> 4096 (similar to the wording for standard_conforming_strings).\n\nThere is no real practical use for knowing the value if it's not reported,\nsince there isn't anything the user can do differently knowing that. I would\nleave that out to avoid confusion, but I don't have strong feelings if you\nthink it should be added.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Tue, 30 Jan 2024 14:07:12 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: scram_iterations is undocumented GUC_REPORT"
},
{
"msg_contents": "On Tue, 30 Jan 2024 at 13:37, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>\n> I noticed while answering a question that commit b577743000cd added the\n> GUC scram_iterations and marked it GUC_REPORT, but failed to add it to\n> the PQparameterStatus documentation.\n\n+1 the improvements your suggesting (although 3 I don't know enough\nabout to be sure)\n\nOne important note though is that this list is tracked in two\ndifferent places, so both of these places should be updated:\n- doc/src/sgml/protocol.sgml\n- doc/src/sgml/libpq.sgml\n\n\n",
"msg_date": "Tue, 30 Jan 2024 14:12:15 +0100",
"msg_from": "Jelte Fennema-Nio <postgres@jeltef.nl>",
"msg_from_op": false,
"msg_subject": "Re: scram_iterations is undocumented GUC_REPORT"
},
{
"msg_contents": "Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> I noticed while answering a question that commit b577743000cd added the\n> GUC scram_iterations and marked it GUC_REPORT, but failed to add it to\n> the PQparameterStatus documentation.\n\nWhy is it GUC_REPORT at all? I don't see a strong need for that.\n(In particular, the report would be delivered too late to be of any\nuse in client authentication.)\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Tue, 30 Jan 2024 09:36:06 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: scram_iterations is undocumented GUC_REPORT"
},
{
"msg_contents": "On 2024-Jan-30, Jelte Fennema-Nio wrote:\n\n> On Tue, 30 Jan 2024 at 13:37, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> >\n> > I noticed while answering a question that commit b577743000cd added the\n> > GUC scram_iterations and marked it GUC_REPORT, but failed to add it to\n> > the PQparameterStatus documentation.\n> \n> +1 the improvements your suggesting (although 3 I don't know enough\n> about to be sure)\n> \n> One important note though is that this list is tracked in two\n> different places, so both of these places should be updated:\n> - doc/src/sgml/protocol.sgml\n> - doc/src/sgml/libpq.sgml\n\nOoh, you're right. I propose to turn the list into a\n<simplelist type=\"vert\" columns=\"2\">\nwhich looks _much_ nicer to read, as in the attached screenshot of the\nPDF.\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n<inflex> really, I see PHP as like a strange amalgamation of C, Perl, Shell\n<crab> inflex: you know that \"amalgam\" means \"mixture with mercury\",\n more or less, right?\n<crab> i.e., \"deadly poison\"",
"msg_date": "Tue, 30 Jan 2024 15:44:36 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "Re: scram_iterations is undocumented GUC_REPORT"
},
{
"msg_contents": "> On 30 Jan 2024, at 15:36, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n>> I noticed while answering a question that commit b577743000cd added the\n>> GUC scram_iterations and marked it GUC_REPORT, but failed to add it to\n>> the PQparameterStatus documentation.\n> \n> Why is it GUC_REPORT at all? I don't see a strong need for that.\n> (In particular, the report would be delivered too late to be of any\n> use in client authentication.)\n\nIt's needed by PQencryptPasswordConn.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Tue, 30 Jan 2024 16:08:09 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: scram_iterations is undocumented GUC_REPORT"
},
{
"msg_contents": "> On 30 Jan 2024, at 15:44, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n\n> I propose to turn the list into a\n> <simplelist type=\"vert\" columns=\"2\">\n> which looks _much_ nicer to read, as in the attached screenshot of the\n> PDF.\n\n+1, this reads a lot better.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Wed, 7 Feb 2024 14:28:39 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: scram_iterations is undocumented GUC_REPORT"
},
{
"msg_contents": "On 2024-Feb-07, Daniel Gustafsson wrote:\n\n> On 30 Jan 2024, at 15:44, Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n> \n> > I propose to turn the list into a\n> > <simplelist type=\"vert\" columns=\"2\">\n> > which looks _much_ nicer to read, as in the attached screenshot of\n> > the PDF.\n> \n> +1, this reads a lot better.\n\nThanks, applied and backpatched to 16.\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/\n\n\n",
"msg_date": "Wed, 7 Feb 2024 19:29:48 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": true,
"msg_subject": "Re: scram_iterations is undocumented GUC_REPORT"
}
] |
[
{
"msg_contents": "Hello PostgreSQL Hackers, I'm thrilled to share with you a new PostgreSQL extension I've developed, called 'pg_stat_advisor'. The genesis of this extension traces back to a conversation in this: https://www.postgresql.org/message-id/e2512fd5-77a4-825b-e456-c0586e37f293%40enterprisedb.com The 'pg_stat_advisor' extension is architected to optimize query plan. It operates by suggesting when to create extended statistics, particularly in queries where current selectivity estimates fall short. This is achieved through the GUC parameter 'pg_stat_advisor.suggest_statistics_threshold', which assesses the ratio of total tuples compared to the planned rows. This feature is instrumental in identifying scenarios where the planner's estimates could be optimized. A key strength of 'pg_stat_advisor' lies in its ability to recommend extended statistics, significantly bolstering query planning. You can install the extension by LOAD 'pg_stat_advisor';SET pg_stat_advisor.suggest_statistics_threshold = 1.0; Example: CREATE TABLE t (i INT, j INT);INSERT INTO t SELECT i/10, i/100 from generate_series(1, 1000000) i;ANALYZE t; EXPLAIN ANALYZE SELECT * FROM t WHERE i = 100 AND j = 10;NOTICE: pg_stat_advisor suggestion: CREATE STATISTICS t_i_j ON i, j FROM t QUERY PLAN ---------------------------------------------------------------------------------------------------------------- Gather (cost=1000.00..11675.10 rows=1 width=8) (actual time=0.400..59.292 rows=10 loops=1) Workers Planned: 2 Workers Launched: 2 -> Parallel Seq Scan on t (cost=0.00..10675.00 rows=1 width=8) (actual time=35.614..54.291 rows=3 loops=3) Filter: ((i = 100) AND (j = 10)) Rows Removed by Filter: 333330 Planning Time: 0.081 ms Execution Time: 59.413 ms(8 rows) After EXPLAIN ANALYZE command you can see the message of suggestion creating statistics with name 't_i_j' on 'i', 'j' columns from 't' table. I look forward to your thoughts, feedback, and any suggestions you might have. Best regards.Ilia Evdokimov,Tantor Labs LLC.",
"msg_date": "Tue, 30 Jan 2024 16:20:58 +0300",
"msg_from": "=?utf-8?B?0JjQu9GM0Y8g0JXQstC00L7QutC40LzQvtCy?=\n <ilya.evdokimov@tantorlabs.com>",
"msg_from_op": true,
"msg_subject": "pg_stat_advisor extension"
},
{
"msg_contents": "Hi hackers, I'm reaching out again regarding the patch with new extension 'pg_stat_advisor' aimed at enhancing query plan efficiency through the suggestion of creating statistics. I understand the community is busy, but I would greatly value any feedback or thoughts on this extension. Thank you for your time and consideration. Best regards,Ilia Evdokimov,Tantor Labs LLC.\n",
"msg_date": "Mon, 05 Feb 2024 19:06:08 +0300",
"msg_from": "Ilia Evdokimov <ilya.evdokimov@tantorlabs.com>",
"msg_from_op": false,
"msg_subject": "Re: pg_stat_advisor extension"
},
{
"msg_contents": "On Tue, Feb 6, 2024 at 12:06 AM Ilia Evdokimov\n<ilya.evdokimov@tantorlabs.com> wrote:\n>\n> Hi hackers,\n>\n> I'm reaching out again regarding the patch with new extension 'pg_stat_advisor' aimed at enhancing query plan efficiency through the suggestion of creating statistics.\n>\n> I understand the community is busy, but I would greatly value any feedback or thoughts on this extension.\n>\n\n+ /* Define custom GUC variables. */\n+ DefineCustomRealVariable(\"pg_stat_advisor.suggest_statistics_threshold\",\n+ \"Set the threshold for actual/estimated rows\",\n+ \"Zero disables suggestion of creating statistics\",\n+ &pg_stat_advisor_suggest_statistics_threshold,\n+ 0.0,\n+ 0.0,\n+ INT_MAX,\n+ PGC_SUSET,\n+ 0,\n+ NULL,\n+ NULL,\n+ NULL);\n\nINT_MAX\nshould be 1.0?\n\n+ if (!FindExtendedStatisticsOnVars(&rte->relid, colmap))\n+ {\n+ ereport(NOTICE, (errmsg(\"pg_stat_advisor suggestion: CREATE\nSTATISTICS %s %s FROM %s\",\n+ stat_name, create_stat_stmt, rel_name),\n+ errhidestmt(true)));\n+ }\nnow CREATE STATISTICS, the statistics name is optional.\nbut here you explicitly mention the statistics kind would be great.\n\n+ elog(DEBUG1, \"Estimated=%f, actual=%f, error=%f: plan=%s\",\n+ plan->plan_rows,\n+ planstate->instrument->ntuples,\n+ planstate->instrument->ntuples / plan->plan_rows,\n+ nodeToString(plan));\n\n` error=%f` seems not that right.\nAlso since the documentation is limited, more comments explaining\nSuggestMultiColumnStatisticsForNode would be great.\noverall the comments are very little, it should be more (that's my opinion).\n\n\n",
"msg_date": "Thu, 8 Feb 2024 08:00:00 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: pg_stat_advisor extension"
},
{
"msg_contents": "Our further discussion of this new extension takes place in this thread: https://www.postgresql.org/message-id/flat/f822b674-9697-43b9-931b-4d69729a26ff%40tantorlabs.com .Due to technical difficulties in the current thread, I will not be able to conduct a dialogue except in HTML format. And this will make it inconvenient for everyone to read the messages. I apologize for the inconvenience caused. Regards, Ilia Evdokimov, TantorLabs LLC.\n",
"msg_date": "Thu, 08 Feb 2024 17:02:52 +0300",
"msg_from": "Ilia Evdokimov <ilya.evdokimov@tantorlabs.com>",
"msg_from_op": false,
"msg_subject": "Re: pg_stat_advisor extension"
}
] |
[
{
"msg_contents": "Hi hackers,\n\n776621a5e4 added a \"warning\" in the documentation to alter a subscription (to\nensure the slot's failover property matches the subscription's one).\n\nThe same remark could be done for the two_phase option. This patch is an attempt\nto do so.\n\nLooking forward to your feedback,\n\nRegards,\n\n-- \nBertrand Drouvot\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Tue, 30 Jan 2024 15:41:32 +0000",
"msg_from": "Bertrand Drouvot <bertranddrouvot.pg@gmail.com>",
"msg_from_op": true,
"msg_subject": "Documentation: warn about two_phase when altering a subscription"
},
{
"msg_contents": "Hi, thanks for the patch. Here are some review comments for v1\n\n======\n\n(below is not showing the links and other sgml rendering -- all those LGTM)\n\nBEFORE\nWhen altering the slot_name, the failover and two_phase properties\nvalues of the named slot may differ from their counterparts failover\nand two_phase parameters specified in the subscription. When creating\nthe slot, ensure the slot failover and two_phase properties match\ntheir counterparts parameters values of the subscription.\n\nSUGGESTION\nWhen altering the slot_name, the failover and two_phase property\nvalues of the named slot may differ from the counterpart failover and\ntwo_phase parameters specified by the subscription. When creating the\nslot, ensure the slot properties failover and two_phase match their\ncounterpart parameters of the subscription.\n\n~\n\nBEFORE\nOtherwise, the slot on the publisher may behave differently from what\nsubscription's failover and two_phase options say: for example, the\nslot on the publisher could ...\n\nSUGGESTION:\nOtherwise, the slot on the publisher may behave differently from what\nthese subscription options say: for example, the slot on the publisher\ncould ...\n\n======\nKind Regards,\nPeter Smith.\nFujitsu Australia\n\n\n",
"msg_date": "Wed, 31 Jan 2024 13:47:16 +1100",
"msg_from": "Peter Smith <smithpb2250@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Documentation: warn about two_phase when altering a subscription"
},
{
"msg_contents": "Hi,\n\nOn Wed, Jan 31, 2024 at 01:47:16PM +1100, Peter Smith wrote:\n> Hi, thanks for the patch. Here are some review comments for v1\n\nThanks for the review!\n\n> \n> ======\n> \n> (below is not showing the links and other sgml rendering -- all those LGTM)\n> \n> BEFORE\n> When altering the slot_name, the failover and two_phase properties\n> values of the named slot may differ from their counterparts failover\n> and two_phase parameters specified in the subscription. When creating\n> the slot, ensure the slot failover and two_phase properties match\n> their counterparts parameters values of the subscription.\n> \n> SUGGESTION\n> When altering the slot_name, the failover and two_phase property\n> values of the named slot may differ from the counterpart failover and\n> two_phase parameters specified by the subscription. When creating the\n> slot, ensure the slot properties failover and two_phase match their\n> counterpart parameters of the subscription.\n> \n> ~\n> \n> BEFORE\n> Otherwise, the slot on the publisher may behave differently from what\n> subscription's failover and two_phase options say: for example, the\n> slot on the publisher could ...\n> \n> SUGGESTION:\n> Otherwise, the slot on the publisher may behave differently from what\n> these subscription options say: for example, the slot on the publisher\n> could ...\n> \n\nAs a non native English speaker somehow I have to rely on you for those\nsuggestions ;-)\n\nThey make sense to me so applied both in v2 attached.\n\nRegards,\n\n-- \nBertrand Drouvot\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Wed, 31 Jan 2024 05:55:39 +0000",
"msg_from": "Bertrand Drouvot <bertranddrouvot.pg@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Documentation: warn about two_phase when altering a subscription"
},
{
"msg_contents": "On Wed, Jan 31, 2024 at 4:55 PM Bertrand Drouvot\n<bertranddrouvot.pg@gmail.com> wrote:\n...\n> As a non native English speaker somehow I have to rely on you for those\n> suggestions ;-)\n>\n> They make sense to me so applied both in v2 attached.\n>\n\nPatch v2 looks OK to me, but probably there is still room for\nimprovement. Let's see what others think.\n\n======\nKind Regards,\nPeter Smith.\nFujitsu Australia\n\n\n",
"msg_date": "Thu, 1 Feb 2024 09:48:05 +1100",
"msg_from": "Peter Smith <smithpb2250@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Documentation: warn about two_phase when altering a subscription"
},
{
"msg_contents": "On Wed, Jan 31, 2024 at 11:25 AM Bertrand Drouvot\n<bertranddrouvot.pg@gmail.com> wrote:\n>\n> They make sense to me so applied both in v2 attached.\n>\n\nThis patch looks good to me but I think it is better to commit this\nafter we push some more work on failover slots, especially the core\nsync slot functionality because we are changing the existing wording\nof the related work.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Sat, 3 Feb 2024 12:17:08 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Documentation: warn about two_phase when altering a subscription"
},
{
"msg_contents": "The following review has been posted through the commitfest application:\nmake installcheck-world: not tested\nImplements feature: tested, passed\nSpec compliant: not tested\nDocumentation: tested, passed\n\nHello,\r\n\r\nI've reviewed your patch, it applies correctly and the documentation builds without any errors. As for the content of the patch itself, I think so far it's good but would make two modifications. I like how the patch was worded originally when referring to the subscription, stating these parameters were 'in' the subscription rather than 'by' it. So I'd propose changing\r\n\r\n> parameters specified by the subscription. When creating the slot, ensure\r\n\r\nto \r\n\r\n> parameters specified in the subscription. When creating the slot, ensure\r\n\r\nand secondly the section \"ensure the slot properties failover and two_phase match their counterpart parameters of the subscription\" sounds a bit clunky. So I'd also propose changing:\r\n\r\n> the slot properties <literal>failover</literal> and <literal>two_phase</literal>\r\n> match their counterpart parameters of the subscription.\r\n\r\nto\r\n\r\n> the slot properties <literal>failover</literal> and <literal>two_phase</literal>\r\n> match their counterpart parameters in the subscription.\r\n\r\nI feel this makes the description flow a bit better when reading. But other than that I think it's quite clear.\r\n\r\nkind regards,\r\n\r\n-----------------------\r\nTristen Raab\r\nHighgo Software Canada\r\nwww.highgo.ca",
"msg_date": "Fri, 23 Feb 2024 23:50:17 +0000",
"msg_from": "Tristen Raab <tristen.raab@highgo.ca>",
"msg_from_op": false,
"msg_subject": "Re: Documentation: warn about two_phase when altering a subscription"
},
{
"msg_contents": "Hi,\n\nOn Fri, Feb 23, 2024 at 11:50:17PM +0000, Tristen Raab wrote:\n> The following review has been posted through the commitfest application:\n> make installcheck-world: not tested\n> Implements feature: tested, passed\n> Spec compliant: not tested\n> Documentation: tested, passed\n> \n> Hello,\n> \n> I've reviewed your patch,\n\nThanks!\n\n> it applies correctly and the documentation builds without any errors. As for the content of the patch itself, I think so far it's good but would make two modifications. I like how the patch was worded originally when referring to the subscription, stating these parameters were 'in' the subscription rather than 'by' it. So I'd propose changing\n> \n> > parameters specified by the subscription. When creating the slot, ensure\n> \n> to \n> \n> > parameters specified in the subscription. When creating the slot, ensure\n\nAs non native English speaker I don't have a strong opinion on that (though I\nalso preferred how it was worded in V1).\n\n> \n> and secondly the section \"ensure the slot properties failover and two_phase match their counterpart parameters of the subscription\" sounds a bit clunky. So I'd also propose changing:\n> \n> > the slot properties <literal>failover</literal> and <literal>two_phase</literal>\n> > match their counterpart parameters of the subscription.\n> \n> to\n> \n> > the slot properties <literal>failover</literal> and <literal>two_phase</literal>\n> > match their counterpart parameters in the subscription.\n\nSame here, I don't have a strong opinion on that.\n\nAs the patch as it is now looks good to Amit (see [1]), I prefer to let him\ndecide which wording he pefers to push.\n\n> I feel this makes the description flow a bit better when reading. But other than that I think it's quite clear.\n\nThanks!\n\n[1]: https://www.postgresql.org/message-id/CAA4eK1KdZMtJfo%3DK%3DXWsQQu8OHutT_dwJV2D3zs4h9g5zdNz2A%40mail.gmail.com\n\nRegards,\n\n-- \nBertrand Drouvot\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Mon, 26 Feb 2024 09:14:07 +0000",
"msg_from": "Bertrand Drouvot <bertranddrouvot.pg@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Documentation: warn about two_phase when altering a subscription"
},
{
"msg_contents": "\n\n> On 26 Feb 2024, at 14:14, Bertrand Drouvot <bertranddrouvot.pg@gmail.com> wrote:\n> \n> As the patch as it is now looks good to Amit (see [1]), I prefer to let him\n> decide which wording he pefers to push.\n\nAdded Amit to cc, just to be sure. Thanks!\n\n\nBest regards, Andrey Borodin, learning how to be CFM.\n\n",
"msg_date": "Sat, 2 Mar 2024 23:14:35 +0500",
"msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>",
"msg_from_op": false,
"msg_subject": "Re: Documentation: warn about two_phase when altering a subscription"
},
{
"msg_contents": "On Sat, Mar 2, 2024 at 11:44 PM Andrey M. Borodin <x4mmm@yandex-team.ru> wrote:\n>\n> > On 26 Feb 2024, at 14:14, Bertrand Drouvot <bertranddrouvot.pg@gmail.com> wrote:\n> >\n> > As the patch as it is now looks good to Amit (see [1]), I prefer to let him\n> > decide which wording he pefers to push.\n>\n> Added Amit to cc, just to be sure. Thanks!\n>\n\nI'll look into it during this CF.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Sun, 3 Mar 2024 09:33:19 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Documentation: warn about two_phase when altering a subscription"
},
{
"msg_contents": "On Sat, Feb 24, 2024 at 5:21 AM Tristen Raab <tristen.raab@highgo.ca> wrote:\n>\n> I've reviewed your patch, it applies correctly and the documentation builds without any errors. As for the content of the patch itself, I think so far it's good but would make two modifications. I like how the patch was worded originally when referring to the subscription, stating these parameters were 'in' the subscription rather than 'by' it. So I'd propose changing\n>\n> > parameters specified by the subscription. When creating the slot, ensure\n>\n> to\n>\n> > parameters specified in the subscription. When creating the slot, ensure\n>\n\nThis suggestion makes sense, so I updated the patch for this and committed.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Mon, 11 Mar 2024 09:45:27 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Documentation: warn about two_phase when altering a subscription"
}
] |
[
{
"msg_contents": "Patch 1:\n\nPassing NULL as a second argument to memcpy breaks ubsan, and there \ndidn't seem to be anything preventing that in the LogLogicalMessage() \ncodepath. Here is a preventative measure in LogLogicalMessage() and an \nAssert() in CopyXLogRecordToWAL().\n\nPatch 2:\n\nSupport building with -Db_sanitize=address in Meson. Various executables \nare leaky which can cause the builds to fail and tests to fail, when we \nare fine leaking this memory.\n\nPersonally, I am a big stickler for always freeing my memory in \nexecutables even if it gets released at program exit because it makes \nthe leak sanitizer much more effective. However (!), I am not here to \nchange the philosophy of memory management in one-off executables, so \nI have just silenced memory leaks in various executables for now.\n\nPatch 3:\n\nTHIS DOESN'T WORK. DO NOT COMMIT. PROPOSING FOR DISCUSSION!\n\nIn my effort to try to see if the test suite would pass with asan \nenabled, I ran into a max_stack_depth issue. I tried maxing it out \n(hence, the patch), but that still didn't remedy my issue. I tried to \nlook on the list for any relevant emails, but nothing turned up. Maybe \nothers have not attempted this before? Seems doubtful.\n\nNot entirely sure how to fix this issue. I personally find asan \nextremely effective, even more than valgrind, so it would be great if \nI could run Postgres with asan enabled to catch various stupid C issues \nI might create. On my system, ulimit -a returns 8192 kbytes, so Postgres \njust lets me set 7680 kbytes as the max. Whatever asan is doing doesn't \nseem to leave enough stack space for Postgres.\n\n---\n\nI would like to see patch 1 reviewed and committed. Patch 2 honestly \ndoesn't matter unless asan support can be fixed. I can also add a patch \nthat errors out the Meson build if asan support is requested. That way \nothers don't spend time heading down a dead end.\n\n-- \nTristan Partin\nNeon (https://neon.tech)\n\n\n",
"msg_date": "Tue, 30 Jan 2024 09:57:24 -0600",
"msg_from": "\"Tristan Partin\" <tristan@neon.tech>",
"msg_from_op": true,
"msg_subject": "Fix some ubsan/asan related issues"
},
{
"msg_contents": "Spend so much time writing out the email, I once again forget \nattachments...UGH.\n\n-- \nTristan Partin\nNeon (https://neon.tech)",
"msg_date": "Tue, 30 Jan 2024 09:59:25 -0600",
"msg_from": "\"Tristan Partin\" <tristan@neon.tech>",
"msg_from_op": true,
"msg_subject": "Re: Fix some ubsan/asan related issues"
},
{
"msg_contents": "On 30/01/2024 17:57, Tristan Partin wrote:\n> Patch 1:\n> \n> Passing NULL as a second argument to memcpy breaks ubsan, and there\n> didn't seem to be anything preventing that in the LogLogicalMessage()\n> codepath. Here is a preventative measure in LogLogicalMessage() and an\n> Assert() in CopyXLogRecordToWAL().\n\nFor the audience: We ran into this one with the neon extension. The \nsolution is to call LogLogicalMessage(\"\", 0, ...) instead of \nLogLogicalMessage(NULL, 0, ...). . But it's true that it's pointlessfor \nLogLogicalMessage to call XLogRegisterData() if the message is empty. If \nwe do this, we should check for 'size == 0' rather than 'message == NULL'.\n\n> Patch 2:\n> \n> Support building with -Db_sanitize=address in Meson. Various executables\n> are leaky which can cause the builds to fail and tests to fail, when we\n> are fine leaking this memory.\n> \n> Personally, I am a big stickler for always freeing my memory in\n> executables even if it gets released at program exit because it makes\n> the leak sanitizer much more effective. However (!), I am not here to\n> change the philosophy of memory management in one-off executables, so\n> I have just silenced memory leaks in various executables for now.\n> \n> Patch 3:\n> \n> THIS DOESN'T WORK. DO NOT COMMIT. PROPOSING FOR DISCUSSION!\n> \n> In my effort to try to see if the test suite would pass with asan\n> enabled, I ran into a max_stack_depth issue. I tried maxing it out\n> (hence, the patch), but that still didn't remedy my issue. I tried to\n> look on the list for any relevant emails, but nothing turned up. Maybe\n> others have not attempted this before? Seems doubtful.\n> \n> Not entirely sure how to fix this issue. I personally find asan\n> extremely effective, even more than valgrind, so it would be great if\n> I could run Postgres with asan enabled to catch various stupid C issues\n> I might create. On my system, ulimit -a returns 8192 kbytes, so Postgres\n> just lets me set 7680 kbytes as the max. Whatever asan is doing doesn't\n> seem to leave enough stack space for Postgres.\n\nI'm a bit confused by these. We already run with sanitizer in the cirrus \nCI. What does this enable that we're not already doing?\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Tue, 30 Jan 2024 22:05:28 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Fix some ubsan/asan related issues"
},
{
"msg_contents": "Hi,\n\nOn 2024-01-30 22:05:28 +0200, Heikki Linnakangas wrote:\n> On 30/01/2024 17:57, Tristan Partin wrote:\n> > In my effort to try to see if the test suite would pass with asan\n> > enabled, I ran into a max_stack_depth issue. I tried maxing it out\n> > (hence, the patch), but that still didn't remedy my issue. I tried to\n> > look on the list for any relevant emails, but nothing turned up. Maybe\n> > others have not attempted this before? Seems doubtful.\n> > \n> > Not entirely sure how to fix this issue. I personally find asan\n> > extremely effective, even more than valgrind, so it would be great if\n> > I could run Postgres with asan enabled to catch various stupid C issues\n> > I might create. On my system, ulimit -a returns 8192 kbytes, so Postgres\n> > just lets me set 7680 kbytes as the max. Whatever asan is doing doesn't\n> > seem to leave enough stack space for Postgres.\n> \n> I'm a bit confused by these. We already run with sanitizer in the cirrus CI.\n> What does this enable that we're not already doing?\n\nThe reason asan fails is that it uses a \"shadow stack\" to track stack variable\nlifetimes. These confuse our stack depth check. CI doesn't have the issue\nbecause the compiler doesn't yet enable the feature, locally I get around it\nby using ASAN_OPTIONS=detect_stack_use_after_return=0:...\n\nThe checks are actually quite useful, so making our stack depth check work\nwith asan would be worthwhile.\n\nI discussed this in a bit more in\nhttps://postgr.es/m/20231129193920.4vphw7dqxjzf5v5b%40awork3.anarazel.de\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Tue, 30 Jan 2024 13:23:04 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: Fix some ubsan/asan related issues"
},
{
"msg_contents": "Hi,\n\nOn 2024-01-30 09:59:25 -0600, Tristan Partin wrote:\n> From 331cec1c9db6ff60dcc6d9ba62a9c8be4e5e95ed Mon Sep 17 00:00:00 2001\n> From: Tristan Partin <tristan@neon.tech>\n> Date: Mon, 29 Jan 2024 18:03:39 -0600\n> Subject: [PATCH v1 1/3] Refuse to register message in LogLogicalMessage if\n> NULL\n\n> If this occurs, the memcpy of rdata_data in CopyXLogRecordToWAL breaks\n> the API contract of memcpy in glibc. The two pointer arguments are\n> marked as nonnull, even in the event the amount to copy is 0 bytes.\n\nIt seems pretty odd to call LogLogicalMessage() with a NULL argument. Why is\nthat something useful?\n\n\n> From dc9488f3fdee69b981b52c985fb77106d7d301ff Mon Sep 17 00:00:00 2001\n> From: Tristan Partin <tristan@neon.tech>\n> Date: Wed, 24 Jan 2024 17:07:01 -0600\n> Subject: [PATCH v1 2/3] meson: Support compiling with -Db_sanitize=address\n> \n> The ecpg is parser is extremely leaky, so we need to silence leak\n> detection.\n\nThis does stuff beyond epcg...\n\n\n> +if get_option('b_sanitize').contains('address')\n> + cdata.set('USE_ADDRESS_SANITIZER', 1)\n> +endif\n> \n> ###############################################################\n> # NLS / Gettext\n> diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c\n> index ac409b0006..e18e716d9c 100644\n> --- a/src/bin/initdb/initdb.c\n> +++ b/src/bin/initdb/initdb.c\n> @@ -338,6 +338,17 @@ do { \\\n> \t\toutput_failed = true, output_errno = errno; \\\n> } while (0)\n> \n> +#ifdef USE_ADDRESS_SANITIZER\n\nWhen asan is used __SANITIZE_ADDRESS__ is defined, so we don't need to\nimplement this ourselves.\n\n\n> +const char *__asan_default_options(void);\n> +\n> +const char *__asan_default_options(void)\n> +{\n> +\treturn \"detect_leaks=0\";\n> +}\n> +\n> +#endif\n\nWonder if we should move this into some static library and link it into all\nbinaries that don't want leak detection? It doesn't seem great to have to\nadjust this in a bunch of files if we want to adjust the options...\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Tue, 30 Jan 2024 13:58:12 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: Fix some ubsan/asan related issues"
},
{
"msg_contents": "Hello,\n\n30.01.2024 18:57, Tristan Partin wrote:\n> Patch 1:\n>\n> Passing NULL as a second argument to memcpy breaks ubsan, ...\n\nMaybe you would like to fix also one more similar place, reached with:\ncreate extension xml2;\nselect xslt_process('<x/>',\n$$<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n<xsl:template match=\"@*|node()\">\n</xsl:template>\n</xsl:stylesheet>$$);\n\nvarlena.c:201:26: runtime error: null pointer passed as argument 2, which is declared to never be null\n\nThere is also an issue with pg_bsd_indent, I stumble upon when doing\n`make check-world` with the sanitizers enabled:\nhttps://www.postgresql.org/message-id/591971ce-25c1-90f3-0526-5f54e3ebb32e%40gmail.com\n\n31.01.2024 00:23, Andres Freund wrote:\n> The reason asan fails is that it uses a \"shadow stack\" to track stack variable\n> lifetimes. These confuse our stack depth check. CI doesn't have the issue\n> because the compiler doesn't yet enable the feature, locally I get around it\n> by using ASAN_OPTIONS=detect_stack_use_after_return=0:...\n\nEven with detect_stack_use_after_return=0, clang-18's asan makes the test\n012_subtransactions.pl fail:\n2024-01-31 03:24:25.691 UTC [4112455] 012_subtransactions.pl LOG: statement: SELECT hs_subxids(201);\n2024-01-31 03:24:25.714 UTC [4112455] 012_subtransactions.pl ERROR: stack depth limit exceeded\n2024-01-31 03:24:25.714 UTC [4112455] 012_subtransactions.pl HINT: Increase the configuration parameter max_stack_depth \n(currently 2048kB), after ensuring the platform's stack depth limit is adequate.\n\n(All the other tests pass.)\nThough the same test passes when I use clang-16.\n\nBest regards,\nAlexander\n\n\n\n\n\nHello,\n\n 30.01.2024 18:57, Tristan Partin wrote:\n\nPatch 1:\n \n\n Passing NULL as a second argument to memcpy breaks ubsan, ...\n\n\n Maybe you would like to fix also one more similar place, reached\n with:\n create extension xml2;\n select xslt_process('<x/>',\n $$<xsl:stylesheet\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:template match=\"@*|node()\">\n </xsl:template>\n </xsl:stylesheet>$$);\n\n varlena.c:201:26: runtime error: null pointer passed as argument 2,\n which is declared to never be null\n\n There is also an issue with pg_bsd_indent, I stumble upon when doing\n `make check-world` with the sanitizers enabled:\nhttps://www.postgresql.org/message-id/591971ce-25c1-90f3-0526-5f54e3ebb32e%40gmail.com\n\n31.01.2024 00:23, Andres Freund wrote:\n\n\nThe reason asan fails is that it uses a \"shadow stack\" to track stack variable\nlifetimes. These confuse our stack depth check. CI doesn't have the issue\nbecause the compiler doesn't yet enable the feature, locally I get around it\nby using ASAN_OPTIONS=detect_stack_use_after_return=0:...\n\n\n Even with detect_stack_use_after_return=0, clang-18's asan makes the\n test\n 012_subtransactions.pl fail:\n 2024-01-31 03:24:25.691 UTC [4112455] 012_subtransactions.pl LOG: \n statement: SELECT hs_subxids(201);\n 2024-01-31 03:24:25.714 UTC [4112455] 012_subtransactions.pl ERROR: \n stack depth limit exceeded\n 2024-01-31 03:24:25.714 UTC [4112455] 012_subtransactions.pl HINT: \n Increase the configuration parameter max_stack_depth (currently\n 2048kB), after ensuring the platform's stack depth limit is\n adequate.\n\n (All the other tests pass.)\n Though the same test passes when I use clang-16.\n\n Best regards,\n Alexander",
"msg_date": "Wed, 31 Jan 2024 07:00:00 +0300",
"msg_from": "Alexander Lakhin <exclusion@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix some ubsan/asan related issues"
},
{
"msg_contents": "On Tue Jan 30, 2024 at 10:00 PM CST, Alexander Lakhin wrote:\n> Hello,\n>\n> 30.01.2024 18:57, Tristan Partin wrote:\n> > Patch 1:\n> >\n> > Passing NULL as a second argument to memcpy breaks ubsan, ...\n>\n> Maybe you would like to fix also one more similar place, reached with:\n> create extension xml2;\n> select xslt_process('<x/>',\n> $$<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n> <xsl:template match=\"@*|node()\">\n> </xsl:template>\n> </xsl:stylesheet>$$);\n>\n> varlena.c:201:26: runtime error: null pointer passed as argument 2, which is declared to never be null\n>\n> There is also an issue with pg_bsd_indent, I stumble upon when doing\n> `make check-world` with the sanitizers enabled:\n> https://www.postgresql.org/message-id/591971ce-25c1-90f3-0526-5f54e3ebb32e%40gmail.com\n>\n> 31.01.2024 00:23, Andres Freund wrote:\n> > The reason asan fails is that it uses a \"shadow stack\" to track stack variable\n> > lifetimes. These confuse our stack depth check. CI doesn't have the issue\n> > because the compiler doesn't yet enable the feature, locally I get around it\n> > by using ASAN_OPTIONS=detect_stack_use_after_return=0:...\n>\n> Even with detect_stack_use_after_return=0, clang-18's asan makes the test\n> 012_subtransactions.pl fail:\n> 2024-01-31 03:24:25.691 UTC [4112455] 012_subtransactions.pl LOG: statement: SELECT hs_subxids(201);\n> 2024-01-31 03:24:25.714 UTC [4112455] 012_subtransactions.pl ERROR: stack depth limit exceeded\n> 2024-01-31 03:24:25.714 UTC [4112455] 012_subtransactions.pl HINT: Increase the configuration parameter max_stack_depth \n> (currently 2048kB), after ensuring the platform's stack depth limit is adequate.\n>\n> (All the other tests pass.)\n> Though the same test passes when I use clang-16.\n\nThanks Alexander! I will try and take a look at these.\n\n-- \nTristan Partin\nNeon (https://neon.tech)\n\n\n",
"msg_date": "Wed, 31 Jan 2024 12:16:52 -0600",
"msg_from": "\"Tristan Partin\" <tristan@neon.tech>",
"msg_from_op": true,
"msg_subject": "Re: Fix some ubsan/asan related issues"
},
{
"msg_contents": "On Tue Jan 30, 2024 at 3:58 PM CST, Andres Freund wrote:\n> Hi,\n>\n> On 2024-01-30 09:59:25 -0600, Tristan Partin wrote:\n> > From 331cec1c9db6ff60dcc6d9ba62a9c8be4e5e95ed Mon Sep 17 00:00:00 2001\n> > From: Tristan Partin <tristan@neon.tech>\n> > Date: Mon, 29 Jan 2024 18:03:39 -0600\n> > Subject: [PATCH v1 1/3] Refuse to register message in LogLogicalMessage if\n> > NULL\n>\n> > If this occurs, the memcpy of rdata_data in CopyXLogRecordToWAL breaks\n> > the API contract of memcpy in glibc. The two pointer arguments are\n> > marked as nonnull, even in the event the amount to copy is 0 bytes.\n>\n> It seems pretty odd to call LogLogicalMessage() with a NULL argument. Why is\n> that something useful?\n\nDropped. Will change on the Neon side. Should we add an assert \nsomewhere for good measure? Near the memcpy in question?\n\n> > From dc9488f3fdee69b981b52c985fb77106d7d301ff Mon Sep 17 00:00:00 2001\n> > From: Tristan Partin <tristan@neon.tech>\n> > Date: Wed, 24 Jan 2024 17:07:01 -0600\n> > Subject: [PATCH v1 2/3] meson: Support compiling with -Db_sanitize=address\n> > \n> > The ecpg is parser is extremely leaky, so we need to silence leak\n> > detection.\n>\n> This does stuff beyond epcg...\n\nDropped.\n\n> > +if get_option('b_sanitize').contains('address')\n> > + cdata.set('USE_ADDRESS_SANITIZER', 1)\n> > +endif\n> > \n> > ###############################################################\n> > # NLS / Gettext\n> > diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c\n> > index ac409b0006..e18e716d9c 100644\n> > --- a/src/bin/initdb/initdb.c\n> > +++ b/src/bin/initdb/initdb.c\n> > @@ -338,6 +338,17 @@ do { \\\n> > \t\toutput_failed = true, output_errno = errno; \\\n> > } while (0)\n> > \n> > +#ifdef USE_ADDRESS_SANITIZER\n>\n> When asan is used __SANITIZE_ADDRESS__ is defined, so we don't need to\n> implement this ourselves.\n\nThanks!\n\n> > +const char *__asan_default_options(void);\n> > +\n> > +const char *__asan_default_options(void)\n> > +{\n> > +\treturn \"detect_leaks=0\";\n> > +}\n> > +\n> > +#endif\n>\n> Wonder if we should move this into some static library and link it into all\n> binaries that don't want leak detection? It doesn't seem great to have to\n> adjust this in a bunch of files if we want to adjust the options...\n\nSee attached patches. Here is what I found to be necessary to get \na -Db_sanitize=address,undefined build to successfully make it through \ntests. I do have a few concerns about the patch.\n\n1. For whatever reason, __SANITIZE_LEAK__ is not defined when the leak \n sanitizer is enabled. So you will see me use this, to make some \n include directives work. I don't like this as a final solution \n because someone could use -fsanitize=leak.\n2. I tracked down what seems to be a valid leak in adt/xml.c. Attached \n (test.sql) is a fairly minimal reproduction of what is needed to show \n the leak. I didn't spend too much time tracking it down. Might get to \n it later, who knows. Below you will find the backtrace, and whoever \n wants to try their hand at fixing it will need to comment out \n xmlNewNode in the leak.supp file.\n3. I don't love the new library name. Maybe it should be name more lsan \n specific.\n4. Should pg_attribute_no_asan be renamed to \n pg_attribute_no_sanitize_address? That would match \n pg_attribute_no_sanitize_alignment.\n\nI will also attach a Meson test log for good measure. I didn't try \ntesting anything that requires PG_TEST_EXTRA, but I suspect that \neverything will be fine.\n\nAlexander, I haven't yet gotten to the things you pointed out in the \nsibling thread.\n\n==221848==ERROR: LeakSanitizer: detected memory leaks\n\nDirect leak of 120 byte(s) in 1 object(s) allocated from:\n #0 0x7fac4a6d92ef in malloc (/lib64/libasan.so.8+0xd92ef) (BuildId: 7fcb7759bc17ef47f9682414b6d99732d6a6ab0c)\n #1 0x7fac4a48427d in xmlNewNode (/lib64/libxml2.so.2+0x5d27d) (BuildId: 3074681c8fa9b17e0cbed09bc61c25ada5c28e7c)\n #2 0x22107a6 in xmltotext_with_options ../src/backend/utils/adt/xml.c:754\n #3 0xead047 in ExecEvalXmlExpr ../src/backend/executor/execExprInterp.c:4020\n #4 0xe8c119 in ExecInterpExpr ../src/backend/executor/execExprInterp.c:1537\n #5 0xe91f2c in ExecInterpExprStillValid ../src/backend/executor/execExprInterp.c:1881\n #6 0x109632d in ExecEvalExprSwitchContext ../src/include/executor/executor.h:355\n #7 0x109655d in ExecProject ../src/include/executor/executor.h:389\n #8 0x1097186 in ExecResult ../src/backend/executor/nodeResult.c:136\n #9 0xf0f90c in ExecProcNodeFirst ../src/backend/executor/execProcnode.c:464\n #10 0xec9bec in ExecProcNode ../src/include/executor/executor.h:273\n #11 0xed875c in ExecutePlan ../src/backend/executor/execMain.c:1670\n #12 0xecbee0 in standard_ExecutorRun ../src/backend/executor/execMain.c:365\n #13 0xecb529 in ExecutorRun ../src/backend/executor/execMain.c:309\n #14 0x1ae89f6 in PortalRunSelect ../src/backend/tcop/pquery.c:924\n #15 0x1ae7c06 in PortalRun ../src/backend/tcop/pquery.c:768\n #16 0x1ad1b43 in exec_simple_query ../src/backend/tcop/postgres.c:1273\n #17 0x1adf8de in PostgresMain ../src/backend/tcop/postgres.c:4653\n #18 0x170dbce in BackendRun ../src/backend/postmaster/postmaster.c:4464\n #19 0x170bf70 in BackendStartup ../src/backend/postmaster/postmaster.c:4140\n #20 0x170263f in ServerLoop ../src/backend/postmaster/postmaster.c:1776\n #21 0x1701052 in PostmasterMain ../src/backend/postmaster/postmaster.c:1475\n #22 0x11a5f67 in main ../src/backend/main/main.c:198\n #23 0x7fac48e46149 in __libc_start_call_main (/lib64/libc.so.6+0x28149) (BuildId: 7ea8d85df0e89b90c63ac7ed2b3578b2e7728756)\n #24 0x7fac48e4620a in __libc_start_main_impl (/lib64/libc.so.6+0x2820a) (BuildId: 7ea8d85df0e89b90c63ac7ed2b3578b2e7728756)\n #25 0x49c5d4 in _start (/home/tristan957/Projects/work/postgresql/build/tmp_install/home/tristan957/.opt/postgresql/bin/postgres+0x49c5d4) (BuildId: c8ca341e1303be0f9dc0b0271c55c4b9e42af89b)\n\nIndirect leak of 13 byte(s) in 1 object(s) allocated from:\n #0 0x7fac4a6d92ef in malloc (/lib64/libasan.so.8+0xd92ef) (BuildId: 7fcb7759bc17ef47f9682414b6d99732d6a6ab0c)\n #1 0x7fac4a4e106f in xmlStrndup (/lib64/libxml2.so.2+0xba06f) (BuildId: 3074681c8fa9b17e0cbed09bc61c25ada5c28e7c)\n #2 0x7fac4a4842c0 in xmlNewNode (/lib64/libxml2.so.2+0x5d2c0) (BuildId: 3074681c8fa9b17e0cbed09bc61c25ada5c28e7c)\n #3 0x22107a6 in xmltotext_with_options ../src/backend/utils/adt/xml.c:754\n #4 0xead047 in ExecEvalXmlExpr ../src/backend/executor/execExprInterp.c:4020\n #5 0xe8c119 in ExecInterpExpr ../src/backend/executor/execExprInterp.c:1537\n #6 0xe91f2c in ExecInterpExprStillValid ../src/backend/executor/execExprInterp.c:1881\n #7 0x109632d in ExecEvalExprSwitchContext ../src/include/executor/executor.h:355\n #8 0x109655d in ExecProject ../src/include/executor/executor.h:389\n #9 0x1097186 in ExecResult ../src/backend/executor/nodeResult.c:136\n #10 0xf0f90c in ExecProcNodeFirst ../src/backend/executor/execProcnode.c:464\n #11 0xec9bec in ExecProcNode ../src/include/executor/executor.h:273\n #12 0xed875c in ExecutePlan ../src/backend/executor/execMain.c:1670\n #13 0xecbee0 in standard_ExecutorRun ../src/backend/executor/execMain.c:365\n #14 0xecb529 in ExecutorRun ../src/backend/executor/execMain.c:309\n #15 0x1ae89f6 in PortalRunSelect ../src/backend/tcop/pquery.c:924\n #16 0x1ae7c06 in PortalRun ../src/backend/tcop/pquery.c:768\n #17 0x1ad1b43 in exec_simple_query ../src/backend/tcop/postgres.c:1273\n #18 0x1adf8de in PostgresMain ../src/backend/tcop/postgres.c:4653\n #19 0x170dbce in BackendRun ../src/backend/postmaster/postmaster.c:4464\n #20 0x170bf70 in BackendStartup ../src/backend/postmaster/postmaster.c:4140\n #21 0x170263f in ServerLoop ../src/backend/postmaster/postmaster.c:1776\n #22 0x1701052 in PostmasterMain ../src/backend/postmaster/postmaster.c:1475\n #23 0x11a5f67 in main ../src/backend/main/main.c:198\n #24 0x7fac48e46149 in __libc_start_call_main (/lib64/libc.so.6+0x28149) (BuildId: 7ea8d85df0e89b90c63ac7ed2b3578b2e7728756)\n #25 0x7fac48e4620a in __libc_start_main_impl (/lib64/libc.so.6+0x2820a) (BuildId: 7ea8d85df0e89b90c63ac7ed2b3578b2e7728756)\n #26 0x49c5d4 in _start (/home/tristan957/Projects/work/postgresql/build/tmp_install/home/tristan957/.opt/postgresql/bin/postgres+0x49c5d4) (BuildId: c8ca341e1303be0f9dc0b0271c55c4b9e42af89b)\n\nSUMMARY: AddressSanitizer: 133 byte(s) leaked in 2 allocation(s).\n\n-- \nTristan Partin\nNeon (https://neon.tech)",
"msg_date": "Mon, 05 Feb 2024 21:53:40 -0600",
"msg_from": "\"Tristan Partin\" <tristan@neon.tech>",
"msg_from_op": true,
"msg_subject": "Re: Fix some ubsan/asan related issues"
},
{
"msg_contents": "Hi Tristan,\n\nOn Tue, Feb 6, 2024 at 11:53 AM Tristan Partin <tristan@neon.tech> wrote:\n>\n> On Tue Jan 30, 2024 at 3:58 PM CST, Andres Freund wrote:\n> > Hi,\n> >\n> > On 2024-01-30 09:59:25 -0600, Tristan Partin wrote:\n> > > From 331cec1c9db6ff60dcc6d9ba62a9c8be4e5e95ed Mon Sep 17 00:00:00 2001\n> > > From: Tristan Partin <tristan@neon.tech>\n> > > Date: Mon, 29 Jan 2024 18:03:39 -0600\n> > > Subject: [PATCH v1 1/3] Refuse to register message in LogLogicalMessage if\n> > > NULL\n> >\n> > > If this occurs, the memcpy of rdata_data in CopyXLogRecordToWAL breaks\n> > > the API contract of memcpy in glibc. The two pointer arguments are\n> > > marked as nonnull, even in the event the amount to copy is 0 bytes.\n> >\n> > It seems pretty odd to call LogLogicalMessage() with a NULL argument. Why is\n> > that something useful?\n>\n> Dropped. Will change on the Neon side. Should we add an assert\n> somewhere for good measure? Near the memcpy in question?\n>\n> > > From dc9488f3fdee69b981b52c985fb77106d7d301ff Mon Sep 17 00:00:00 2001\n> > > From: Tristan Partin <tristan@neon.tech>\n> > > Date: Wed, 24 Jan 2024 17:07:01 -0600\n> > > Subject: [PATCH v1 2/3] meson: Support compiling with -Db_sanitize=address\n> > >\n> > > The ecpg is parser is extremely leaky, so we need to silence leak\n> > > detection.\n> >\n> > This does stuff beyond epcg...\n>\n> Dropped.\n>\n> > > +if get_option('b_sanitize').contains('address')\n> > > + cdata.set('USE_ADDRESS_SANITIZER', 1)\n> > > +endif\n> > >\n> > > ###############################################################\n> > > # NLS / Gettext\n> > > diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c\n> > > index ac409b0006..e18e716d9c 100644\n> > > --- a/src/bin/initdb/initdb.c\n> > > +++ b/src/bin/initdb/initdb.c\n> > > @@ -338,6 +338,17 @@ do { \\\n> > > output_failed = true, output_errno = errno; \\\n> > > } while (0)\n> > >\n> > > +#ifdef USE_ADDRESS_SANITIZER\n> >\n> > When asan is used __SANITIZE_ADDRESS__ is defined, so we don't need to\n> > implement this ourselves.\n>\n> Thanks!\n>\n> > > +const char *__asan_default_options(void);\n> > > +\n> > > +const char *__asan_default_options(void)\n> > > +{\n> > > + return \"detect_leaks=0\";\n> > > +}\n> > > +\n> > > +#endif\n> >\n> > Wonder if we should move this into some static library and link it into all\n> > binaries that don't want leak detection? It doesn't seem great to have to\n> > adjust this in a bunch of files if we want to adjust the options...\n>\n> See attached patches. Here is what I found to be necessary to get\n> a -Db_sanitize=address,undefined build to successfully make it through\n> tests. I do have a few concerns about the patch.\n>\n> 1. For whatever reason, __SANITIZE_LEAK__ is not defined when the leak\n> sanitizer is enabled. So you will see me use this, to make some\n> include directives work. I don't like this as a final solution\n> because someone could use -fsanitize=leak.\n> 2. I tracked down what seems to be a valid leak in adt/xml.c. Attached\n> (test.sql) is a fairly minimal reproduction of what is needed to show\n> the leak. I didn't spend too much time tracking it down. Might get to\n> it later, who knows. Below you will find the backtrace, and whoever\n> wants to try their hand at fixing it will need to comment out\n> xmlNewNode in the leak.supp file.\n> 3. I don't love the new library name. Maybe it should be name more lsan\n> specific.\n> 4. Should pg_attribute_no_asan be renamed to\n> pg_attribute_no_sanitize_address? That would match\n> pg_attribute_no_sanitize_alignment.\n>\n> I will also attach a Meson test log for good measure. I didn't try\n> testing anything that requires PG_TEST_EXTRA, but I suspect that\n> everything will be fine.\n>\n> Alexander, I haven't yet gotten to the things you pointed out in the\n> sibling thread.\n>\n> ==221848==ERROR: LeakSanitizer: detected memory leaks\n>\n> Direct leak of 120 byte(s) in 1 object(s) allocated from:\n> #0 0x7fac4a6d92ef in malloc (/lib64/libasan.so.8+0xd92ef) (BuildId: 7fcb7759bc17ef47f9682414b6d99732d6a6ab0c)\n> #1 0x7fac4a48427d in xmlNewNode (/lib64/libxml2.so.2+0x5d27d) (BuildId: 3074681c8fa9b17e0cbed09bc61c25ada5c28e7c)\n> #2 0x22107a6 in xmltotext_with_options ../src/backend/utils/adt/xml.c:754\n> #3 0xead047 in ExecEvalXmlExpr ../src/backend/executor/execExprInterp.c:4020\n> #4 0xe8c119 in ExecInterpExpr ../src/backend/executor/execExprInterp.c:1537\n> #5 0xe91f2c in ExecInterpExprStillValid ../src/backend/executor/execExprInterp.c:1881\n> #6 0x109632d in ExecEvalExprSwitchContext ../src/include/executor/executor.h:355\n> #7 0x109655d in ExecProject ../src/include/executor/executor.h:389\n> #8 0x1097186 in ExecResult ../src/backend/executor/nodeResult.c:136\n> #9 0xf0f90c in ExecProcNodeFirst ../src/backend/executor/execProcnode.c:464\n> #10 0xec9bec in ExecProcNode ../src/include/executor/executor.h:273\n> #11 0xed875c in ExecutePlan ../src/backend/executor/execMain.c:1670\n> #12 0xecbee0 in standard_ExecutorRun ../src/backend/executor/execMain.c:365\n> #13 0xecb529 in ExecutorRun ../src/backend/executor/execMain.c:309\n> #14 0x1ae89f6 in PortalRunSelect ../src/backend/tcop/pquery.c:924\n> #15 0x1ae7c06 in PortalRun ../src/backend/tcop/pquery.c:768\n> #16 0x1ad1b43 in exec_simple_query ../src/backend/tcop/postgres.c:1273\n> #17 0x1adf8de in PostgresMain ../src/backend/tcop/postgres.c:4653\n> #18 0x170dbce in BackendRun ../src/backend/postmaster/postmaster.c:4464\n> #19 0x170bf70 in BackendStartup ../src/backend/postmaster/postmaster.c:4140\n> #20 0x170263f in ServerLoop ../src/backend/postmaster/postmaster.c:1776\n> #21 0x1701052 in PostmasterMain ../src/backend/postmaster/postmaster.c:1475\n> #22 0x11a5f67 in main ../src/backend/main/main.c:198\n> #23 0x7fac48e46149 in __libc_start_call_main (/lib64/libc.so.6+0x28149) (BuildId: 7ea8d85df0e89b90c63ac7ed2b3578b2e7728756)\n> #24 0x7fac48e4620a in __libc_start_main_impl (/lib64/libc.so.6+0x2820a) (BuildId: 7ea8d85df0e89b90c63ac7ed2b3578b2e7728756)\n> #25 0x49c5d4 in _start (/home/tristan957/Projects/work/postgresql/build/tmp_install/home/tristan957/.opt/postgresql/bin/postgres+0x49c5d4) (BuildId: c8ca341e1303be0f9dc0b0271c55c4b9e42af89b)\n>\n> Indirect leak of 13 byte(s) in 1 object(s) allocated from:\n> #0 0x7fac4a6d92ef in malloc (/lib64/libasan.so.8+0xd92ef) (BuildId: 7fcb7759bc17ef47f9682414b6d99732d6a6ab0c)\n> #1 0x7fac4a4e106f in xmlStrndup (/lib64/libxml2.so.2+0xba06f) (BuildId: 3074681c8fa9b17e0cbed09bc61c25ada5c28e7c)\n> #2 0x7fac4a4842c0 in xmlNewNode (/lib64/libxml2.so.2+0x5d2c0) (BuildId: 3074681c8fa9b17e0cbed09bc61c25ada5c28e7c)\n> #3 0x22107a6 in xmltotext_with_options ../src/backend/utils/adt/xml.c:754\n> #4 0xead047 in ExecEvalXmlExpr ../src/backend/executor/execExprInterp.c:4020\n> #5 0xe8c119 in ExecInterpExpr ../src/backend/executor/execExprInterp.c:1537\n> #6 0xe91f2c in ExecInterpExprStillValid ../src/backend/executor/execExprInterp.c:1881\n> #7 0x109632d in ExecEvalExprSwitchContext ../src/include/executor/executor.h:355\n> #8 0x109655d in ExecProject ../src/include/executor/executor.h:389\n> #9 0x1097186 in ExecResult ../src/backend/executor/nodeResult.c:136\n> #10 0xf0f90c in ExecProcNodeFirst ../src/backend/executor/execProcnode.c:464\n> #11 0xec9bec in ExecProcNode ../src/include/executor/executor.h:273\n> #12 0xed875c in ExecutePlan ../src/backend/executor/execMain.c:1670\n> #13 0xecbee0 in standard_ExecutorRun ../src/backend/executor/execMain.c:365\n> #14 0xecb529 in ExecutorRun ../src/backend/executor/execMain.c:309\n> #15 0x1ae89f6 in PortalRunSelect ../src/backend/tcop/pquery.c:924\n> #16 0x1ae7c06 in PortalRun ../src/backend/tcop/pquery.c:768\n> #17 0x1ad1b43 in exec_simple_query ../src/backend/tcop/postgres.c:1273\n> #18 0x1adf8de in PostgresMain ../src/backend/tcop/postgres.c:4653\n> #19 0x170dbce in BackendRun ../src/backend/postmaster/postmaster.c:4464\n> #20 0x170bf70 in BackendStartup ../src/backend/postmaster/postmaster.c:4140\n> #21 0x170263f in ServerLoop ../src/backend/postmaster/postmaster.c:1776\n> #22 0x1701052 in PostmasterMain ../src/backend/postmaster/postmaster.c:1475\n> #23 0x11a5f67 in main ../src/backend/main/main.c:198\n> #24 0x7fac48e46149 in __libc_start_call_main (/lib64/libc.so.6+0x28149) (BuildId: 7ea8d85df0e89b90c63ac7ed2b3578b2e7728756)\n> #25 0x7fac48e4620a in __libc_start_main_impl (/lib64/libc.so.6+0x2820a) (BuildId: 7ea8d85df0e89b90c63ac7ed2b3578b2e7728756)\n> #26 0x49c5d4 in _start (/home/tristan957/Projects/work/postgresql/build/tmp_install/home/tristan957/.opt/postgresql/bin/postgres+0x49c5d4) (BuildId: c8ca341e1303be0f9dc0b0271c55c4b9e42af89b)\n>\n> SUMMARY: AddressSanitizer: 133 byte(s) leaked in 2 allocation(s).\n>\n> --\n> Tristan Partin\n> Neon (https://neon.tech)\n\nI tried your v1-0002, it works at compile phase but failed to run initdb\nwith the following leak detected:\n\n=================================================================\n==64983==ERROR: LeakSanitizer: detected memory leaks\n\nDirect leak of 248 byte(s) in 1 object(s) allocated from:\n #0 0x7fc7729df9cf in __interceptor_malloc\n../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:69\n #1 0x55bff5480e8b in save_ps_display_args\n../postgres/src/backend/utils/misc/ps_status.c:190\n #2 0x55bff4a5a298 in main ../postgres/src/backend/main/main.c:90\n #3 0x7fc771924249 in __libc_start_call_main\n../sysdeps/nptl/libc_start_call_main.h:58\n\nIndirect leak of 19 byte(s) in 1 object(s) allocated from:\n #0 0x7fc77299777b in __interceptor_strdup\n../../../../src/libsanitizer/asan/asan_interceptors.cpp:439\n #1 0x55bff5480f41 in save_ps_display_args\n../postgres/src/backend/utils/misc/ps_status.c:198\n #2 0x55bff4a5a298 in main ../postgres/src/backend/main/main.c:90\n #3 0x7fc771924249 in __libc_start_call_main\n../sysdeps/nptl/libc_start_call_main.h:58\n\nI worked around by moving *new_environ* as a global variable, I think this is\nfalse positive report so maybe this deserves a patch?\n\nI tried to apply your v2 patch set but v2-0004 seems out of date.\n\n-- \nRegards\nJunwang Zhao\n\n\n",
"msg_date": "Mon, 16 Sep 2024 21:29:21 +0800",
"msg_from": "Junwang Zhao <zhjwpku@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix some ubsan/asan related issues"
}
] |
[
{
"msg_contents": "Hi, so libpq has this line in its Makefile\nhttps://github.com/postgres/postgres/blob/6ee26c6a4bafabbd22a85f575d2446fd5ec6ad0d/src/interfaces/libpq/Makefile#L116\nwhich checks that libpq does not use any \"exit\" functions. With\nThreadSanitizer it triggers on function `__tsan_func_exit` which is\nused to record returns from functions. Should it be added to exclusion\nlist here?\n\nError looks like this, just in case:\n...\nrm -f libpq.so\nln -s libpq.so.5.15 libpq.so\nlibpq.so.5.15: U __tsan_func_exit\nlibpq must not be calling any function which invokes exit\nmake: *** [Makefile:121: libpq-refs-stamp] Error 1\n\n\n",
"msg_date": "Wed, 31 Jan 2024 04:21:27 +0100",
"msg_from": "Roman Lozko <lozko.roma@gmail.com>",
"msg_from_op": true,
"msg_subject": "libpq fails to build with TSAN"
},
{
"msg_contents": "> On 31 Jan 2024, at 04:21, Roman Lozko <lozko.roma@gmail.com> wrote:\n> \n> Hi, so libpq has this line in its Makefile\n> https://github.com/postgres/postgres/blob/6ee26c6a4bafabbd22a85f575d2446fd5ec6ad0d/src/interfaces/libpq/Makefile#L116\n> which checks that libpq does not use any \"exit\" functions. With\n> ThreadSanitizer it triggers on function `__tsan_func_exit` which is\n> used to record returns from functions. Should it be added to exclusion\n> list here?\n\nI think it should, the idea of that check is to catch calls to actual exits,\nwhile this is instrumentation which has nothing to do with exit(2). The\nattached diff should be enough to handle this.\n\n--\nDaniel Gustafsson",
"msg_date": "Wed, 31 Jan 2024 13:56:55 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: libpq fails to build with TSAN"
},
{
"msg_contents": "Daniel Gustafsson <daniel@yesql.se> writes:\n> I think it should, the idea of that check is to catch calls to actual exits,\n> while this is instrumentation which has nothing to do with exit(2). The\n> attached diff should be enough to handle this.\n\n+1\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Wed, 31 Jan 2024 10:39:41 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: libpq fails to build with TSAN"
},
{
"msg_contents": "> On 31 Jan 2024, at 16:39, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Daniel Gustafsson <daniel@yesql.se> writes:\n>> I think it should, the idea of that check is to catch calls to actual exits,\n>> while this is instrumentation which has nothing to do with exit(2). The\n>> attached diff should be enough to handle this.\n> \n> +1\n\nPushed. It can be argued that it should be backpatched, but for now I've only\npushed it to master. If there are strong opinions on backpatching I'd be happy\nto fix that.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Wed, 31 Jan 2024 23:28:25 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: libpq fails to build with TSAN"
}
] |
[
{
"msg_contents": "Hi,\n\nPSA a small fix for a misleading comment found in the pg_upgrade test code.\n\n======\nKind Regards,\nPeter Smith.\nFujitsu Australia",
"msg_date": "Wed, 31 Jan 2024 15:56:50 +1100",
"msg_from": "Peter Smith <smithpb2250@gmail.com>",
"msg_from_op": true,
"msg_subject": "src/bin/pg_upgrade/t/004_subscription.pl test comment fix"
},
{
"msg_contents": "On Wed, 31 Jan 2024 at 10:27, Peter Smith <smithpb2250@gmail.com> wrote:\n>\n> Hi,\n>\n> PSA a small fix for a misleading comment found in the pg_upgrade test code.\n\nIs the double # intentional here, as I did not see this style of\ncommenting used elsewhere:\n+# # Upgraded regress_sub1 should still have enabled and failover as true.\n+# # Upgraded regress_sub2 should still have enabled and failover as false.\n\nRegards,\nVignesh\n\n\n",
"msg_date": "Wed, 31 Jan 2024 11:21:03 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: src/bin/pg_upgrade/t/004_subscription.pl test comment fix"
},
{
"msg_contents": "On Wed, Jan 31, 2024 at 4:51 PM vignesh C <vignesh21@gmail.com> wrote:\n>\n> On Wed, 31 Jan 2024 at 10:27, Peter Smith <smithpb2250@gmail.com> wrote:\n> >\n> > Hi,\n> >\n> > PSA a small fix for a misleading comment found in the pg_upgrade test code.\n>\n> Is the double # intentional here, as I did not see this style of\n> commenting used elsewhere:\n> +# # Upgraded regress_sub1 should still have enabled and failover as true.\n> +# # Upgraded regress_sub2 should still have enabled and failover as false.\n>\n\nUnintentional caused by copy/paste. Thanks for reporting. I will post\na fixed patch tomorrow.\n\n======\nKind Regards,\nPeter Smith.\nFujitsu Australia\n\n\n",
"msg_date": "Wed, 31 Jan 2024 17:18:51 +1100",
"msg_from": "Peter Smith <smithpb2250@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: src/bin/pg_upgrade/t/004_subscription.pl test comment fix"
},
{
"msg_contents": "How about rewording it more extensively? It doesn't read great IMO.\nI would use something like\n\n# In the upgraded instance, the running status and failover option of the\n# subscription with the failover option should have been preserved; the other\n# should not.\n# So regress_sub1 should still have subenabled,subfailover set to true,\n# while regress_sub2 should have both set to false.\n\nI think the symmetry between the two lines confuses more than helps.\nIt's not a huge thing but since we're editing anyway, why not?\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/\n\"The saddest aspect of life right now is that science gathers knowledge faster\n than society gathers wisdom.\" (Isaac Asimov)\n\n\n",
"msg_date": "Wed, 31 Jan 2024 09:48:00 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: src/bin/pg_upgrade/t/004_subscription.pl test comment fix"
},
{
"msg_contents": "On Wed, Jan 31, 2024 at 7:48 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>\n> How about rewording it more extensively? It doesn't read great IMO.\n> I would use something like\n>\n> # In the upgraded instance, the running status and failover option of the\n> # subscription with the failover option should have been preserved; the other\n> # should not.\n> # So regress_sub1 should still have subenabled,subfailover set to true,\n> # while regress_sub2 should have both set to false.\n>\n\nIIUC this suggested comment is implying that the running status is\n*only* preserved when the failover option is true. But AFAIK that is\nnot correct. e.g. I hacked the test to keep subscription regress_sub2\nas ENABLED but the result after the upgrade was subenabled/subfailover\n= t/f, not f/f.\n\n> I think the symmetry between the two lines confuses more than helps.\n> It's not a huge thing but since we're editing anyway, why not?\n>\n\nOK. Now using your suggested 2nd sentence:\n\n+# The subscription's running status and failover option should be preserved\n+# in the upgraded instance. So regress_sub1 should still have\nsubenabled,subfailover\n+# set to true, while regress_sub2 should have both set to false.\n\n~\n\nI also tweaked some other nearby comments/messages which did not\nmention the 'failover' preservation.\n\nPSA v2.\n\n======\nKind Regards,\nPeter Smith.\nFujitsu Australia",
"msg_date": "Thu, 1 Feb 2024 11:27:43 +1100",
"msg_from": "Peter Smith <smithpb2250@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: src/bin/pg_upgrade/t/004_subscription.pl test comment fix"
},
{
"msg_contents": "On Thu, Feb 1, 2024 at 5:58 AM Peter Smith <smithpb2250@gmail.com> wrote:\n>\n> OK. Now using your suggested 2nd sentence:\n>\n> +# The subscription's running status and failover option should be preserved\n> +# in the upgraded instance. So regress_sub1 should still have\n> subenabled,subfailover\n> +# set to true, while regress_sub2 should have both set to false.\n>\n> ~\n>\n> I also tweaked some other nearby comments/messages which did not\n> mention the 'failover' preservation.\n>\n\nLooks mostly good to me. One minor nitpick:\n*\nalong with retaining the replication origin's remote lsn\n-# and subscription's running status.\n+# and subscription's running status and failover option.\n\nI don't think we need to use 'and' twice in the above sentence. We\nshould use ',' between different properties. I can change this on\nMonday and push it unless you think otherwise.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Sat, 3 Feb 2024 11:58:24 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: src/bin/pg_upgrade/t/004_subscription.pl test comment fix"
},
{
"msg_contents": "On Sat, Feb 3, 2024 at 5:28 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Thu, Feb 1, 2024 at 5:58 AM Peter Smith <smithpb2250@gmail.com> wrote:\n> >\n> > OK. Now using your suggested 2nd sentence:\n> >\n> > +# The subscription's running status and failover option should be preserved\n> > +# in the upgraded instance. So regress_sub1 should still have\n> > subenabled,subfailover\n> > +# set to true, while regress_sub2 should have both set to false.\n> >\n> > ~\n> >\n> > I also tweaked some other nearby comments/messages which did not\n> > mention the 'failover' preservation.\n> >\n>\n> Looks mostly good to me. One minor nitpick:\n> *\n> along with retaining the replication origin's remote lsn\n> -# and subscription's running status.\n> +# and subscription's running status and failover option.\n>\n> I don't think we need to use 'and' twice in the above sentence. We\n> should use ',' between different properties. I can change this on\n> Monday and push it unless you think otherwise.\n>\n\n+1\n\n======\nKind Regards,\nPeter Smith.\nFujitsu Australia\n\n\n",
"msg_date": "Mon, 5 Feb 2024 08:12:18 +1100",
"msg_from": "Peter Smith <smithpb2250@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: src/bin/pg_upgrade/t/004_subscription.pl test comment fix"
},
{
"msg_contents": "On Mon, Feb 5, 2024 at 2:42 AM Peter Smith <smithpb2250@gmail.com> wrote:\n>\n> On Sat, Feb 3, 2024 at 5:28 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > On Thu, Feb 1, 2024 at 5:58 AM Peter Smith <smithpb2250@gmail.com> wrote:\n> > >\n> > > OK. Now using your suggested 2nd sentence:\n> > >\n> > > +# The subscription's running status and failover option should be preserved\n> > > +# in the upgraded instance. So regress_sub1 should still have\n> > > subenabled,subfailover\n> > > +# set to true, while regress_sub2 should have both set to false.\n> > >\n> > > ~\n> > >\n> > > I also tweaked some other nearby comments/messages which did not\n> > > mention the 'failover' preservation.\n> > >\n> >\n> > Looks mostly good to me. One minor nitpick:\n> > *\n> > along with retaining the replication origin's remote lsn\n> > -# and subscription's running status.\n> > +# and subscription's running status and failover option.\n> >\n> > I don't think we need to use 'and' twice in the above sentence. We\n> > should use ',' between different properties. I can change this on\n> > Monday and push it unless you think otherwise.\n> >\n>\n> +1\n>\n\nPushed!\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Mon, 5 Feb 2024 10:35:21 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: src/bin/pg_upgrade/t/004_subscription.pl test comment fix"
}
] |
[
{
"msg_contents": "Hello.\n\nI would like to share some information regarding a recent issue we\nencoutered.\n\nWhile compiling an extension against the RPM package\npostgresql16-devel-16.1-2PGDG.rhel9.x86_64.rpm we faced a problem that\nappears to be caused by the combination of LTO and constant\nfolding/propagation, leading to a SEGV. This crash didn't occur when\nwe gave --fno-lto instead of --flto=auto to the compiler.\n\nTo put this case briefly:\npostgresql16-devel-16.1-2PGDG.rhel9.x86_64.rpm + gcc 11.3\n => building the extension completes but the binary may crash with SEGV\n --fno-lto prevents this crash from occurring.\n\nThe PG package is built with gcc-11.4, and the compiler in our build\nenvironment for the extension was gcc-11.3. A quick search suggests\nthat the LTO bytecode format was optimized in gcc-11.4. Conversely,\nwhen we built the extension with postgresql-16-16.0 and gc-11.4, the\nbuild fails. This failure seems to stem LTO binary format\nincompatibility.\n\n> Error: bad register name `%'\n> Error: open CFI at the end of file; missing .cfi_endproc directive\n> /usr/bin/ld: error: lto-wrapper failed\n\nTo put this case briefly:\npostgresql16-devel-16.0-1PGDG.rhel9.x86_64.rpm + gcc 11.4\n => build failure regarding LTO\n\nGiven these issues, it seems there might be some issues with including\nfat objects in the -devel package.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n",
"msg_date": "Wed, 31 Jan 2024 15:04:22 +0900 (JST)",
"msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>",
"msg_from_op": true,
"msg_subject": "possible inter-gcc-version incompatibility regarding fat objects"
}
] |
[
{
"msg_contents": "Clean pg_walsummary's tmp_check directory.\n\nOversight similar to ba08c10fc.\n\nBranch\n------\nmaster\n\nDetails\n-------\nhttps://git.postgresql.org/pg/commitdiff/9589b038d3203cd5ba708fb4f5c23182c88ad0b3\n\nModified Files\n--------------\nsrc/bin/pg_walsummary/Makefile | 1 +\n1 file changed, 1 insertion(+)",
"msg_date": "Wed, 31 Jan 2024 16:51:00 +0000",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": true,
"msg_subject": "pgsql: Clean pg_walsummary's tmp_check directory."
},
{
"msg_contents": "On Wed, Jan 31, 2024 at 11:51 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Clean pg_walsummary's tmp_check directory.\n\nUgh. The reason I keep doing this is because I've switched to using\nmeson builds, where of course you don't get complaints about this.\n\nAnd it seems like CI doesn't tell you either. Nor does the buildfarm.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n",
"msg_date": "Wed, 31 Jan 2024 12:07:53 -0500",
"msg_from": "Robert Haas <robertmhaas@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: pgsql: Clean pg_walsummary's tmp_check directory."
}
] |
[
{
"msg_contents": "Hi.\n\nPer Coverity.\nCID 1506240: (#1 of 1): Argument cannot be negative (NEGATIVE_RETURNS)\n3. negative_returns: dup(fd) is passed to a parameter that cannot be\nnegative.\n\npg_dump function open_none, tries to associate a stream to a file\ndescriptor,\nusing function dup, which may fail and return negative value.\n\nfdopen cannot receive negative parameters, in this case fail and return\nEBADF.\n\nThis can be confusing for the user, who will be trying to figure out what's\nwrong.\nBetter abort and report the correct failure to the user.\n\nPatch attached.\n\nBest regards,\nRanier Vilela",
"msg_date": "Wed, 31 Jan 2024 14:12:00 -0300",
"msg_from": "Ranier Vilela <ranier.vf@gmail.com>",
"msg_from_op": true,
"msg_subject": "Abort if dup fail (src/bin/pg_dump/compress_none.c)"
}
] |
[
{
"msg_contents": "Hello,\n\nRobert: I've taken the liberty of cc'ing you since you worked on most\nof this code. My apologies if that wasn't appropriate.\n\nWhile working on \"Parallelize correlated subqueries that execute\nwithin each worker\" [1] I noticed that while in the other call to\nset_cheapest (for partially_grouped_rel) in the same function the call\nafter gather_grouping_paths(root, partially_grouped_rel) is not\nsimilarly guarded with a check for a NIL pathlist on\npartially_grouped_rel.\n\nI don't see any inherent reason why we must always assume that\ngather_grouping_paths will always result in having at least one entry\nin pathlist. If, for example, we've disabled incremental sort and the\ncheapest partial path happens to already be sorted, then I don't\nbelieve we'll add any paths. And if that happens then set_cheapest\nwill error with the message \"could not devise a query plan for the\ngiven query\". So I propose we add a similar guard to this call point.\n\nI could be convinced that this should be simply part of the patch in\nthe other thread, but it seemed to me it'd be worth considering\nindependently because as noted above I don't see any reason why this\ncouldn't happen separately. That being said, on master I don't have a\ncase showing this is necessary.\n\nThanks,\nJames Coleman\n\n1: https://www.postgresql.org/message-id/flat/CAAaqYe-Aq6oNf9NPZnpPE7SgRLomXXWJA1Gz9L9ndi_Nv%3D94Yw%40mail.gmail.com#e0b1a803d0fdb97189ce493f15f99c14",
"msg_date": "Wed, 31 Jan 2024 21:04:27 -0500",
"msg_from": "James Coleman <jtc331@gmail.com>",
"msg_from_op": true,
"msg_subject": "set_cheapest without checking pathlist"
},
{
"msg_contents": "On Thu, Feb 1, 2024 at 10:04 AM James Coleman <jtc331@gmail.com> wrote:\n\n> I don't see any inherent reason why we must always assume that\n> gather_grouping_paths will always result in having at least one entry\n> in pathlist. If, for example, we've disabled incremental sort and the\n> cheapest partial path happens to already be sorted, then I don't\n> believe we'll add any paths. And if that happens then set_cheapest\n> will error with the message \"could not devise a query plan for the\n> given query\". So I propose we add a similar guard to this call point.\n\n\nI don't believe that would happen. It seems to me that we should, at\nthe very least, have a path which is Gather on top of the cheapest\npartial path (see generate_gather_paths), as long as the\npartially_grouped_rel has partial paths.\n\nThanks\nRichard\n\nOn Thu, Feb 1, 2024 at 10:04 AM James Coleman <jtc331@gmail.com> wrote:\nI don't see any inherent reason why we must always assume that\ngather_grouping_paths will always result in having at least one entry\nin pathlist. If, for example, we've disabled incremental sort and the\ncheapest partial path happens to already be sorted, then I don't\nbelieve we'll add any paths. And if that happens then set_cheapest\nwill error with the message \"could not devise a query plan for the\ngiven query\". So I propose we add a similar guard to this call point.I don't believe that would happen. It seems to me that we should, atthe very least, have a path which is Gather on top of the cheapestpartial path (see generate_gather_paths), as long as thepartially_grouped_rel has partial paths.ThanksRichard",
"msg_date": "Thu, 1 Feb 2024 11:28:54 +0800",
"msg_from": "Richard Guo <guofenglinux@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: set_cheapest without checking pathlist"
},
{
"msg_contents": "On Thu, 1 Feb 2024 at 16:29, Richard Guo <guofenglinux@gmail.com> wrote:\n>\n>\n> On Thu, Feb 1, 2024 at 10:04 AM James Coleman <jtc331@gmail.com> wrote:\n>>\n>> I don't see any inherent reason why we must always assume that\n>> gather_grouping_paths will always result in having at least one entry\n>> in pathlist. If, for example, we've disabled incremental sort and the\n>> cheapest partial path happens to already be sorted, then I don't\n>> believe we'll add any paths. And if that happens then set_cheapest\n>> will error with the message \"could not devise a query plan for the\n>> given query\". So I propose we add a similar guard to this call point.\n>\n>\n> I don't believe that would happen. It seems to me that we should, at\n> the very least, have a path which is Gather on top of the cheapest\n> partial path (see generate_gather_paths), as long as the\n> partially_grouped_rel has partial paths.\n\nIt will have partial paths because it's nested inside \"if\n(partially_grouped_rel && partially_grouped_rel->partial_pathlist)\"\n\nDavid\n\n\n",
"msg_date": "Thu, 1 Feb 2024 16:37:29 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: set_cheapest without checking pathlist"
},
{
"msg_contents": "On Thu, Feb 1, 2024 at 11:37 AM David Rowley <dgrowleyml@gmail.com> wrote:\n\n> On Thu, 1 Feb 2024 at 16:29, Richard Guo <guofenglinux@gmail.com> wrote:\n> > On Thu, Feb 1, 2024 at 10:04 AM James Coleman <jtc331@gmail.com> wrote:\n> >> I don't see any inherent reason why we must always assume that\n> >> gather_grouping_paths will always result in having at least one entry\n> >> in pathlist. If, for example, we've disabled incremental sort and the\n> >> cheapest partial path happens to already be sorted, then I don't\n> >> believe we'll add any paths. And if that happens then set_cheapest\n> >> will error with the message \"could not devise a query plan for the\n> >> given query\". So I propose we add a similar guard to this call point.\n> >\n> >\n> > I don't believe that would happen. It seems to me that we should, at\n> > the very least, have a path which is Gather on top of the cheapest\n> > partial path (see generate_gather_paths), as long as the\n> > partially_grouped_rel has partial paths.\n>\n> It will have partial paths because it's nested inside \"if\n> (partially_grouped_rel && partially_grouped_rel->partial_pathlist)\"\n\n\nRight. And that leads to the conclusion that gather_grouping_paths will\nalways generate at least one path for partially_grouped_rel. So it\nseems to me that the check added in the patch is not necessary. But\nmaybe we can add an Assert or a comment clarifying that the pathlist of\npartially_grouped_rel cannot be empty here.\n\nThanks\nRichard\n\nOn Thu, Feb 1, 2024 at 11:37 AM David Rowley <dgrowleyml@gmail.com> wrote:On Thu, 1 Feb 2024 at 16:29, Richard Guo <guofenglinux@gmail.com> wrote:\n> On Thu, Feb 1, 2024 at 10:04 AM James Coleman <jtc331@gmail.com> wrote:\n>> I don't see any inherent reason why we must always assume that\n>> gather_grouping_paths will always result in having at least one entry\n>> in pathlist. If, for example, we've disabled incremental sort and the\n>> cheapest partial path happens to already be sorted, then I don't\n>> believe we'll add any paths. And if that happens then set_cheapest\n>> will error with the message \"could not devise a query plan for the\n>> given query\". So I propose we add a similar guard to this call point.\n>\n>\n> I don't believe that would happen. It seems to me that we should, at\n> the very least, have a path which is Gather on top of the cheapest\n> partial path (see generate_gather_paths), as long as the\n> partially_grouped_rel has partial paths.\n\nIt will have partial paths because it's nested inside \"if\n(partially_grouped_rel && partially_grouped_rel->partial_pathlist)\"Right. And that leads to the conclusion that gather_grouping_paths willalways generate at least one path for partially_grouped_rel. So itseems to me that the check added in the patch is not necessary. Butmaybe we can add an Assert or a comment clarifying that the pathlist ofpartially_grouped_rel cannot be empty here.ThanksRichard",
"msg_date": "Thu, 1 Feb 2024 14:36:39 +0800",
"msg_from": "Richard Guo <guofenglinux@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: set_cheapest without checking pathlist"
},
{
"msg_contents": "On Thu, 1 Feb 2024 at 19:36, Richard Guo <guofenglinux@gmail.com> wrote:\n> maybe we can add an Assert or a comment clarifying that the pathlist of\n> partially_grouped_rel cannot be empty here.\n\nThere'd be no need to Assert that as set_cheapest() will raise an\nerror when given a rel with an empty pathlist.\n\nI don't think putting an Assert that would fail in the same situation\nthat we'd later ERROR out on would be a good idea. It'd make it harder\nto debug the issue.\n\nDavid\n\n\n",
"msg_date": "Thu, 1 Feb 2024 22:03:28 +1300",
"msg_from": "David Rowley <dgrowleyml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: set_cheapest without checking pathlist"
},
{
"msg_contents": "On Thu, Feb 1, 2024 at 5:03 PM David Rowley <dgrowleyml@gmail.com> wrote:\n\n> On Thu, 1 Feb 2024 at 19:36, Richard Guo <guofenglinux@gmail.com> wrote:\n> > maybe we can add an Assert or a comment clarifying that the pathlist of\n> > partially_grouped_rel cannot be empty here.\n>\n> There'd be no need to Assert that as set_cheapest() will raise an\n> error when given a rel with an empty pathlist.\n>\n> I don't think putting an Assert that would fail in the same situation\n> that we'd later ERROR out on would be a good idea. It'd make it harder\n> to debug the issue.\n\n\nFair point.\n\nThanks\nRichard\n\nOn Thu, Feb 1, 2024 at 5:03 PM David Rowley <dgrowleyml@gmail.com> wrote:On Thu, 1 Feb 2024 at 19:36, Richard Guo <guofenglinux@gmail.com> wrote:\n> maybe we can add an Assert or a comment clarifying that the pathlist of\n> partially_grouped_rel cannot be empty here.\n\nThere'd be no need to Assert that as set_cheapest() will raise an\nerror when given a rel with an empty pathlist.\n\nI don't think putting an Assert that would fail in the same situation\nthat we'd later ERROR out on would be a good idea. It'd make it harder\nto debug the issue.Fair point.ThanksRichard",
"msg_date": "Fri, 2 Feb 2024 08:50:25 +0800",
"msg_from": "Richard Guo <guofenglinux@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: set_cheapest without checking pathlist"
},
{
"msg_contents": "On Thu, Feb 1, 2024 at 1:36 AM Richard Guo <guofenglinux@gmail.com> wrote:\n>\n>\n> On Thu, Feb 1, 2024 at 11:37 AM David Rowley <dgrowleyml@gmail.com> wrote:\n>>\n>> On Thu, 1 Feb 2024 at 16:29, Richard Guo <guofenglinux@gmail.com> wrote:\n>> > On Thu, Feb 1, 2024 at 10:04 AM James Coleman <jtc331@gmail.com> wrote:\n>> >> I don't see any inherent reason why we must always assume that\n>> >> gather_grouping_paths will always result in having at least one entry\n>> >> in pathlist. If, for example, we've disabled incremental sort and the\n>> >> cheapest partial path happens to already be sorted, then I don't\n>> >> believe we'll add any paths. And if that happens then set_cheapest\n>> >> will error with the message \"could not devise a query plan for the\n>> >> given query\". So I propose we add a similar guard to this call point.\n>> >\n>> >\n>> > I don't believe that would happen. It seems to me that we should, at\n>> > the very least, have a path which is Gather on top of the cheapest\n>> > partial path (see generate_gather_paths), as long as the\n>> > partially_grouped_rel has partial paths.\n>>\n>> It will have partial paths because it's nested inside \"if\n>> (partially_grouped_rel && partially_grouped_rel->partial_pathlist)\"\n>\n>\n> Right. And that leads to the conclusion that gather_grouping_paths will\n> always generate at least one path for partially_grouped_rel. So it\n> seems to me that the check added in the patch is not necessary. But\n> maybe we can add an Assert or a comment clarifying that the pathlist of\n> partially_grouped_rel cannot be empty here.\n\nYes, that's true currently. I don't particularly love that we have the\nknowledge of that baked in at this level, but it won't break anything\ncurrently.\n\nI'll put this as a patch in the parallelization patch series\nreferenced earlier since in that series my changes result in\ngenerate_gather_paths() not necessarily always being able to build a\npath.\n\nRegards,\nJames Coleman\n\n\n",
"msg_date": "Thu, 1 Feb 2024 21:06:41 -0500",
"msg_from": "James Coleman <jtc331@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: set_cheapest without checking pathlist"
}
] |
[
{
"msg_contents": "Motivated by a recent complaint [1] I found the hostssl related material in\nour docs quite verbose and even repetitive. Some of that is normal since\nwe have both an overview/walk-through section as well as a reference\nsection. But the overview in particular was self-repetitive. Here is a\nfirst pass at some improvements. The commit message contains both the\nintent of the patch and some thoughts/questions still being considered.\n\nDavid J.\n\n[1]\nhttps://www.postgresql.org/message-id/170672433664.663.11895343120533141715%40wrigleys.postgresql.org",
"msg_date": "Thu, 1 Feb 2024 15:47:15 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": true,
"msg_subject": "[Doc] Improve hostssl related descriptions and option presentation"
},
{
"msg_contents": "Thoughts anyone?\n\nOn Thu, Feb 1, 2024 at 3:47 PM David G. Johnston <david.g.johnston@gmail.com>\nwrote:\n\n> Motivated by a recent complaint [1] I found the hostssl related material\n> in our docs quite verbose and even repetitive. Some of that is normal\n> since we have both an overview/walk-through section as well as a reference\n> section. But the overview in particular was self-repetitive. Here is a\n> first pass at some improvements. The commit message contains both the\n> intent of the patch and some thoughts/questions still being considered.\n>\n> David J.\n>\n> [1]\n> https://www.postgresql.org/message-id/170672433664.663.11895343120533141715%40wrigleys.postgresql.org\n>\n\nThoughts anyone?On Thu, Feb 1, 2024 at 3:47 PM David G. Johnston <david.g.johnston@gmail.com> wrote:Motivated by a recent complaint [1] I found the hostssl related material in our docs quite verbose and even repetitive. Some of that is normal since we have both an overview/walk-through section as well as a reference section. But the overview in particular was self-repetitive. Here is a first pass at some improvements. The commit message contains both the intent of the patch and some thoughts/questions still being considered.David J.[1] https://www.postgresql.org/message-id/170672433664.663.11895343120533141715%40wrigleys.postgresql.org",
"msg_date": "Mon, 22 Apr 2024 14:20:03 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: [Doc] Improve hostssl related descriptions and option\n presentation"
}
] |
[
{
"msg_contents": "Hi hackers,\n\nduring reading the source code of new incremental backup functionality\nI noticed that the following condition can by unintentional:\n\n /*\n * For newer server versions, likewise create pg_wal/summaries\n */\n if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_WAL_SUMMARIES)\n {\n ...\n\n if (pg_mkdir_p(summarydir, pg_dir_create_mode) != 0 &&\n errno != EEXIST)\n pg_fatal(\"could not create directory \\\"%s\\\": %m\", summarydir);\n }\n\nThis is from src/bin/pg_basebackup/pg_basebackup.c.\n\nIs the condition correct? Shouldn't it be \">=\". Otherwise the function\nwill create \"/summaries\" only for older PostgreSQL versions.\n\nI've attached a patch to fix it in case this is a typo.\n\n-- \nArtur",
"msg_date": "Fri, 2 Feb 2024 01:11:27 +0100",
"msg_from": "Artur Zakirov <zaartur@gmail.com>",
"msg_from_op": true,
"msg_subject": "Checking MINIMUM_VERSION_FOR_WAL_SUMMARIES"
},
{
"msg_contents": "Hi,\n\nOn Fri, 2 Feb 2024 at 03:11, Artur Zakirov <zaartur@gmail.com> wrote:\n>\n> Hi hackers,\n>\n> during reading the source code of new incremental backup functionality\n> I noticed that the following condition can by unintentional:\n>\n> /*\n> * For newer server versions, likewise create pg_wal/summaries\n> */\n> if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_WAL_SUMMARIES)\n> {\n> ...\n>\n> if (pg_mkdir_p(summarydir, pg_dir_create_mode) != 0 &&\n> errno != EEXIST)\n> pg_fatal(\"could not create directory \\\"%s\\\": %m\", summarydir);\n> }\n>\n> This is from src/bin/pg_basebackup/pg_basebackup.c.\n>\n> Is the condition correct? Shouldn't it be \">=\". Otherwise the function\n> will create \"/summaries\" only for older PostgreSQL versions.\n\nYou seem right, nice catch. Also, this change makes the check in\n\n snprintf(summarydir, sizeof(summarydir), \"%s/%s/summaries\",\n basedir,\n PQserverVersion(conn) < MINIMUM_VERSION_FOR_PG_WAL ?\n \"pg_xlog\" : \"pg_wal\");\n\nredundant. PQserverVersion(conn) will always be higher than\nMINIMUM_VERSION_FOR_PG_WAL.\n\n-- \nRegards,\nNazir Bilal Yavuz\nMicrosoft\n\n\n",
"msg_date": "Fri, 2 Feb 2024 11:41:07 +0300",
"msg_from": "Nazir Bilal Yavuz <byavuz81@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Checking MINIMUM_VERSION_FOR_WAL_SUMMARIES"
},
{
"msg_contents": "On Fri, 2 Feb 2024 01:11:27 +0100\nArtur Zakirov <zaartur@gmail.com> wrote:\n\n> Hi hackers,\n> \n> during reading the source code of new incremental backup functionality\n> I noticed that the following condition can by unintentional:\n> \n> /*\n> * For newer server versions, likewise create pg_wal/summaries\n> */\n> if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_WAL_SUMMARIES)\n> {\n> ...\n> \n> if (pg_mkdir_p(summarydir, pg_dir_create_mode) != 0 &&\n> errno != EEXIST)\n> pg_fatal(\"could not create directory \\\"%s\\\": %m\", summarydir);\n> }\n> \n> This is from src/bin/pg_basebackup/pg_basebackup.c.\n> \n> Is the condition correct? Shouldn't it be \">=\". Otherwise the function\n> will create \"/summaries\" only for older PostgreSQL versions.\n> \n> I've attached a patch to fix it in case this is a typo.\n\nI also think it should be \">=\"\nAlso, if so, I don't think the check of MINIMUM_VERSION_FOR_PG_WAL\nin the block is required, because the directory name is always pg_wal\nin the new versions.\n\nRegards,\nYugo Nagata\n\n> \n> -- \n> Artur\n\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>\n\n\n",
"msg_date": "Fri, 2 Feb 2024 17:41:56 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": false,
"msg_subject": "Re: Checking MINIMUM_VERSION_FOR_WAL_SUMMARIES"
},
{
"msg_contents": "On Fri, 2 Feb 2024 at 09:41, Nazir Bilal Yavuz <byavuz81@gmail.com> wrote:\n> You seem right, nice catch. Also, this change makes the check in\n>\n> snprintf(summarydir, sizeof(summarydir), \"%s/%s/summaries\",\n> basedir,\n> PQserverVersion(conn) < MINIMUM_VERSION_FOR_PG_WAL ?\n> \"pg_xlog\" : \"pg_wal\");\n>\n> redundant. PQserverVersion(conn) will always be higher than\n> MINIMUM_VERSION_FOR_PG_WAL.\n\nThank you both for the comments. Indeed, that part now looks redundant.\nI've attached a patch to remove checking MINIMUM_VERSION_FOR_PG_WAL.\n\n-- \nArtur",
"msg_date": "Fri, 2 Feb 2024 10:11:34 +0100",
"msg_from": "Artur Zakirov <zaartur@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Checking MINIMUM_VERSION_FOR_WAL_SUMMARIES"
},
{
"msg_contents": "Hi,\n\nOn Fri, 2 Feb 2024 at 12:11, Artur Zakirov <zaartur@gmail.com> wrote:\n>\n> On Fri, 2 Feb 2024 at 09:41, Nazir Bilal Yavuz <byavuz81@gmail.com> wrote:\n> > You seem right, nice catch. Also, this change makes the check in\n> >\n> > snprintf(summarydir, sizeof(summarydir), \"%s/%s/summaries\",\n> > basedir,\n> > PQserverVersion(conn) < MINIMUM_VERSION_FOR_PG_WAL ?\n> > \"pg_xlog\" : \"pg_wal\");\n> >\n> > redundant. PQserverVersion(conn) will always be higher than\n> > MINIMUM_VERSION_FOR_PG_WAL.\n>\n> Thank you both for the comments. Indeed, that part now looks redundant.\n> I've attached a patch to remove checking MINIMUM_VERSION_FOR_PG_WAL.\n\nThanks for the update. The patch looks good to me.\n\n-- \nRegards,\nNazir Bilal Yavuz\nMicrosoft\n\n\n",
"msg_date": "Fri, 2 Feb 2024 15:11:40 +0300",
"msg_from": "Nazir Bilal Yavuz <byavuz81@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Checking MINIMUM_VERSION_FOR_WAL_SUMMARIES"
},
{
"msg_contents": "On Fri, Feb 02, 2024 at 03:11:40PM +0300, Nazir Bilal Yavuz wrote:\n> Thanks for the update. The patch looks good to me.\n\nYes, you're right. We want the opposite to happen here. I've applied\nthe patch on HEAD.\n--\nMichael",
"msg_date": "Sun, 4 Feb 2024 10:54:08 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Checking MINIMUM_VERSION_FOR_WAL_SUMMARIES"
}
] |
[
{
"msg_contents": "Hi,\n\nThanks a lot to all the members who participated in the commitfest.\n\nHere are the final numbers at the end of the commitfest:\nstatus | w1 | w2 | w3 | w4 | End\n----------------------------+--------+------+--------+---------+----------\nNeeds review: | 238 | 213 | 181 | 146 | N/A\nWaiting on Author | 44 | 46 | 52 | 65 | N/A\nReady for Committer| 27 | 27 | 26 | 24 | N/A\nCommitted: | 36 | 46 | 57 | 71 | 75\nMoved to next CF | 1 | 3 | 4 | 4 | 208\nWithdrawn | 2 | 4 | 12 | 14 | 16\nRWF | 3 | 12 | 18 | 26 | 51\nRejected | 1 | 1 | 2 | 2 | 2\nTotal | 352 | 352 | 352 | 352 | 352\n\nCommitted patches comparison with previous January commitfests:\n2024: 75 committed\n2023: 70 committed\n2022: 58 committed\n2021: 56 committed\n2020: 49 committed\n\n A special thanks to the reviewers/committers who spent tireless\neffort in moving the patches forward.\n\nRegards,\nVignesh\n\n\n",
"msg_date": "Fri, 2 Feb 2024 10:49:30 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": true,
"msg_subject": "Commitfest 2024-01 is now closed"
},
{
"msg_contents": "vignesh C <vignesh21@gmail.com> writes:\n> Thanks a lot to all the members who participated in the commitfest.\n\nThanks for all the work you did running it! CFM is typically a\nthankless exercise in being a nag, but I thought you put in more\nthan the usual amount of effort to keep things moving.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Fri, 02 Feb 2024 00:27:55 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Commitfest 2024-01 is now closed"
},
{
"msg_contents": "On Fri, Feb 2, 2024 at 10:58 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> vignesh C <vignesh21@gmail.com> writes:\n> > Thanks a lot to all the members who participated in the commitfest.\n>\n> Thanks for all the work you did running it! CFM is typically a\n> thankless exercise in being a nag, but I thought you put in more\n> than the usual amount of effort to keep things moving.\n>\n\n+1. Thanks a lot for all the hard work.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Fri, 2 Feb 2024 11:56:36 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Commitfest 2024-01 is now closed"
},
{
"msg_contents": "On Fri, Feb 02, 2024 at 11:56:36AM +0530, Amit Kapila wrote:\n> On Fri, Feb 2, 2024 at 10:58 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Thanks for all the work you did running it! CFM is typically a\n>> thankless exercise in being a nag, but I thought you put in more\n>> than the usual amount of effort to keep things moving.\n>>\n> \n> +1. Thanks a lot for all the hard work.\n\n+1. Thanks!\n--\nMichael",
"msg_date": "Fri, 2 Feb 2024 15:41:08 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Commitfest 2024-01 is now closed"
},
{
"msg_contents": "On Fri, Feb 2, 2024 at 2:19 PM vignesh C <vignesh21@gmail.com> wrote:\n>\n> Hi,\n>\n> Thanks a lot to all the members who participated in the commitfest.\n>\n> Here are the final numbers at the end of the commitfest:\n> status | w1 | w2 | w3 | w4 | End\n> ----------------------------+--------+------+--------+---------+----------\n> Needs review: | 238 | 213 | 181 | 146 | N/A\n> Waiting on Author | 44 | 46 | 52 | 65 | N/A\n> Ready for Committer| 27 | 27 | 26 | 24 | N/A\n> Committed: | 36 | 46 | 57 | 71 | 75\n> Moved to next CF | 1 | 3 | 4 | 4 | 208\n> Withdrawn | 2 | 4 | 12 | 14 | 16\n> RWF | 3 | 12 | 18 | 26 | 51\n> Rejected | 1 | 1 | 2 | 2 | 2\n> Total | 352 | 352 | 352 | 352 | 352\n>\n> Committed patches comparison with previous January commitfests:\n> 2024: 75 committed\n> 2023: 70 committed\n> 2022: 58 committed\n> 2021: 56 committed\n> 2020: 49 committed\n>\n> A special thanks to the reviewers/committers who spent tireless\n> effort in moving the patches forward.\n>\n\nThank you for all the hard work, Vignesh!\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Fri, 2 Feb 2024 15:49:18 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Commitfest 2024-01 is now closed"
},
{
"msg_contents": "On Fri, Feb 2, 2024 at 2:41 PM Michael Paquier <michael@paquier.xyz> wrote:\n\n> On Fri, Feb 02, 2024 at 11:56:36AM +0530, Amit Kapila wrote:\n> > On Fri, Feb 2, 2024 at 10:58 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >> Thanks for all the work you did running it! CFM is typically a\n> >> thankless exercise in being a nag, but I thought you put in more\n> >> than the usual amount of effort to keep things moving.\n> >>\n> >\n> > +1. Thanks a lot for all the hard work.\n>\n> +1. Thanks!\n\n\n+1. Thanks!\n\nThanks\nRichard\n\nOn Fri, Feb 2, 2024 at 2:41 PM Michael Paquier <michael@paquier.xyz> wrote:On Fri, Feb 02, 2024 at 11:56:36AM +0530, Amit Kapila wrote:\n> On Fri, Feb 2, 2024 at 10:58 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Thanks for all the work you did running it! CFM is typically a\n>> thankless exercise in being a nag, but I thought you put in more\n>> than the usual amount of effort to keep things moving.\n>>\n> \n> +1. Thanks a lot for all the hard work.\n\n+1. Thanks!+1. Thanks!ThanksRichard",
"msg_date": "Fri, 2 Feb 2024 15:48:28 +0800",
"msg_from": "Richard Guo <guofenglinux@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Commitfest 2024-01 is now closed"
},
{
"msg_contents": "On Fri, Feb 2, 2024 at 12:28 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Thanks for all the work you did running it! CFM is typically a\n> thankless exercise in being a nag, but I thought you put in more\n> than the usual amount of effort to keep things moving.\n\n+1. The extra effort was really noticeable.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n",
"msg_date": "Fri, 2 Feb 2024 11:11:46 -0500",
"msg_from": "Robert Haas <robertmhaas@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Commitfest 2024-01 is now closed"
}
] |
[
{
"msg_contents": "Hi,\n\nNew WAL space is created by renaming a file into place. Either a\nnewly created file with a temporary name or, ideally, a recyclable old\nfile with a name derived from an old LSN. I think there is a data\nloss window between rename() and fsync(parent_directory). A\nconcurrent backend might open(new_name), write(), fdatasync(), and\nthen we might lose power before the rename hits the disk. The data\nitself would survive the crash, but recovery wouldn't be able to find\nand replay it. That might break the log-before-data rule or forget a\ntransaction that has been reported as committed to a client.\n\nActual breakage would presumably require really bad luck, and I\nhaven't seen this happen or anything, it just occurred to me while\nreading code, and I can't see any existing defences.\n\nOne simple way to address that would be to make XLogFileInitInternal()\nwait for InstallXLogFileSegment() to finish. It's a little\npessimistic to do that unconditionally, though, as then you have to\nwait even for rename operations for segment files later than the one\nyou're opening, so I thought about how to skip waiting in that case --\nsee 0002. I'm not sure if it's worth worrying about or not.",
"msg_date": "Fri, 2 Feb 2024 11:18:18 +0100",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": true,
"msg_subject": "InstallXLogFileSegment() vs concurrent WAL flush"
},
{
"msg_contents": "On Fri, 2 Feb 2024 11:18:18 +0100\nThomas Munro <thomas.munro@gmail.com> wrote:\n\n> Hi,\n> \n> New WAL space is created by renaming a file into place. Either a\n> newly created file with a temporary name or, ideally, a recyclable old\n> file with a name derived from an old LSN. I think there is a data\n> loss window between rename() and fsync(parent_directory). A\n> concurrent backend might open(new_name), write(), fdatasync(), and\n> then we might lose power before the rename hits the disk. The data\n> itself would survive the crash, but recovery wouldn't be able to find\n> and replay it. That might break the log-before-data rule or forget a\n> transaction that has been reported as committed to a client.\n> \n> Actual breakage would presumably require really bad luck, and I\n> haven't seen this happen or anything, it just occurred to me while\n> reading code, and I can't see any existing defences.\n> \n> One simple way to address that would be to make XLogFileInitInternal()\n> wait for InstallXLogFileSegment() to finish. It's a little\n\nOr, can we make sure the rename is durable by calling fsync before\nreturning the fd, as a patch attached here?\n\nRegards,\nYugo Nagata\n\n> pessimistic to do that unconditionally, though, as then you have to\n> wait even for rename operations for segment files later than the one\n> you're opening, so I thought about how to skip waiting in that case --\n> see 0002. I'm not sure if it's worth worrying about or not.\n\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>",
"msg_date": "Fri, 2 Feb 2024 20:56:08 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": false,
"msg_subject": "Re: InstallXLogFileSegment() vs concurrent WAL flush"
},
{
"msg_contents": "On Fri, Feb 2, 2024 at 12:56 PM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\n> On Fri, 2 Feb 2024 11:18:18 +0100\n> Thomas Munro <thomas.munro@gmail.com> wrote:\n> > One simple way to address that would be to make XLogFileInitInternal()\n> > wait for InstallXLogFileSegment() to finish. It's a little\n>\n> Or, can we make sure the rename is durable by calling fsync before\n> returning the fd, as a patch attached here?\n\nRight, yeah, that works too. I'm not sure which way is better.\n\n\n",
"msg_date": "Fri, 2 Feb 2024 14:42:46 +0100",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: InstallXLogFileSegment() vs concurrent WAL flush"
},
{
"msg_contents": "At Fri, 2 Feb 2024 14:42:46 +0100, Thomas Munro <thomas.munro@gmail.com> wrote in \r\n> On Fri, Feb 2, 2024 at 12:56 PM Yugo NAGATA <nagata@sraoss.co.jp> wrote:\r\n> > On Fri, 2 Feb 2024 11:18:18 +0100\r\n> > Thomas Munro <thomas.munro@gmail.com> wrote:\r\n> > > One simple way to address that would be to make XLogFileInitInternal()\r\n> > > wait for InstallXLogFileSegment() to finish. It's a little\r\n> >\r\n> > Or, can we make sure the rename is durable by calling fsync before\r\n> > returning the fd, as a patch attached here?\r\n> \r\n> Right, yeah, that works too. I'm not sure which way is better.\r\n\r\nI'm not sure I like issuing spurious syncs unconditionally. Therefore,\r\nI prefer Thomas' approach in that regard. 0002 would be beneficial,\r\nconsidering the case of a very large max_wal_size, and the code seems\r\nto be the minimal required. I don't think it matters that the lock\r\nattempts occur uselessly until the first segment installation. That\r\nbeing said, we could avoid it by initializing\r\nlast_known_installed_segno properly.\r\n\r\nregards.\r\n\r\n-- \r\nKyotaro Horiguchi\r\nNTT Open Source Software Center\r\n",
"msg_date": "Tue, 06 Feb 2024 16:58:16 +0900 (JST)",
"msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: InstallXLogFileSegment() vs concurrent WAL flush"
}
] |
[
{
"msg_contents": "First-draft release notes for 16.2 are available at\n\nhttps://git.postgresql.org/gitweb/?p=postgresql.git;a=commitdiff;h=87dcc5e45fad3021514f01360d3a2abd4e6480ee\n\nPlease send comments/corrections before Sunday.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Fri, 02 Feb 2024 12:54:48 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": true,
"msg_subject": "Draft release notes for minor releases are up"
},
{
"msg_contents": "On Fri, Feb 02, 2024 at 12:54:48PM -0500, Tom Lane wrote:\n> First-draft release notes for 16.2 are available at\n> \n> https://git.postgresql.org/gitweb/?p=postgresql.git;a=commitdiff;h=87dcc5e45fad3021514f01360d3a2abd4e6480ee\n\n> + <listitem>\n> +<!--\n> +Author: Heikki Linnakangas <heikki.linnakangas@iki.fi>\n> +Branch: master [6a1ea02c4] 2024-01-29 13:46:22 +0200\n> +Branch: REL_16_STABLE [b899e00e7] 2024-01-29 13:46:30 +0200\n> +Branch: REL_15_STABLE [e43425f48] 2024-01-29 13:46:42 +0200\n> +Branch: REL_14_STABLE [f120c0872] 2024-01-29 13:46:43 +0200\n> +Branch: REL_13_STABLE [e74c91665] 2024-01-29 13:46:45 +0200\n> +Branch: REL_12_STABLE [e6511fe64] 2024-01-29 13:46:48 +0200\n> +-->\n> + <para>\n> + Fix insufficient locking when cleaning up an incomplete split of\n> + a GIN index's internal page (Fei Changhong, Heikki Linnakangas)\n> + </para>\n> +\n> + <para>\n> + The code tried to do this with shared rather than exclusive lock on\n> + the buffer. This could lead to index corruption if two processes\n> + attempted the cleanup concurrently.\n> + </para>\n> + </listitem>\n\nShall the top of the notes advise to reindex GIN indexes?\n\n> + <listitem>\n> +<!--\n> +Author: Noah Misch <noah@leadboat.com>\n> +Branch: master [df220714e] 2024-02-01 13:44:19 -0800\n> +Branch: REL_16_STABLE [6d423e9ff] 2024-02-01 13:44:22 -0800\n> +Branch: REL_15_STABLE [d493bed28] 2024-02-01 13:44:22 -0800\n> +Branch: master [0b6517a3b] 2024-02-01 13:44:19 -0800\n> +Branch: REL_16_STABLE [48a6bf5c4] 2024-02-01 13:44:22 -0800\n> +Branch: REL_15_STABLE [8fa4a1ac6] 2024-02-01 13:44:23 -0800\n> +-->\n> + <para>\n> + Add more interlocks between <command>CREATE DATABASE</command> and\n> + base backup (Noah Misch)\n> + </para>\n> +\n> + <para>\n> + This fixes some cases where a base backup taken concurrently\n> + with <command>CREATE DATABASE</command> could produce a corrupt\n> + image of the new database.\n> + </para>\n> + </listitem>\n\nThings I'd like to capture for this one:\n\n- Commit 0b6517a3b deals with crash recovery, not base backups.\n- Connection establishment will fail if one of these bugs corrupted the\n database, so there's no need to worry about silent corruption. (My commit\n messages didn't make that clear.)\n\nPerhaps like this:\n\ndiff --git a/doc/src/sgml/release-16.sgml b/doc/src/sgml/release-16.sgml\nindex 21387e3..8997279 100644\n--- a/doc/src/sgml/release-16.sgml\n+++ b/doc/src/sgml/release-16.sgml\n@@ -750,15 +750,15 @@ Branch: REL_16_STABLE [48a6bf5c4] 2024-02-01 13:44:22 -0800\n Branch: REL_15_STABLE [8fa4a1ac6] 2024-02-01 13:44:23 -0800\n -->\n <para>\n- Add more interlocks between <command>CREATE DATABASE</command> and\n- base backup (Noah Misch)\n+ Fix durability of <command>CREATE DATABASE</command> (Noah Misch)\n </para>\n \n <para>\n- This fixes some cases where a base backup taken concurrently\n- with <command>CREATE DATABASE</command> could produce a corrupt\n- image of the new database.\n+ Recovery failed, or establishing connections to the new database failed.\n+ Effects required an operating system crash or base backup, concurrently\n+ with or shortly after the <command>CREATE DATABASE</command>.\n </para>\n+\n </listitem>\n \n <listitem>\n\n\n",
"msg_date": "Fri, 2 Feb 2024 15:29:23 -0800",
"msg_from": "Noah Misch <noah@leadboat.com>",
"msg_from_op": false,
"msg_subject": "Re: Draft release notes for minor releases are up"
},
{
"msg_contents": "Noah Misch <noah@leadboat.com> writes:\n> Shall the top of the notes advise to reindex GIN indexes?\n\nI thought about that, but it's a pretty low-probability failure\nI think, so I didn't write that advice. Maybe I misjudged it.\n\n> Things I'd like to capture for this one:\n> - Commit 0b6517a3b deals with crash recovery, not base backups.\n> - Connection establishment will fail if one of these bugs corrupted the\n> database, so there's no need to worry about silent corruption. (My commit\n> messages didn't make that clear.)\n> Perhaps like this:\n\nThanks, I'll work on that one some more.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Fri, 02 Feb 2024 20:18:50 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": true,
"msg_subject": "Re: Draft release notes for minor releases are up"
},
{
"msg_contents": "On Fri, Feb 02, 2024 at 08:18:50PM -0500, Tom Lane wrote:\n> Noah Misch <noah@leadboat.com> writes:\n> > Shall the top of the notes advise to reindex GIN indexes?\n> \n> I thought about that, but it's a pretty low-probability failure\n> I think, so I didn't write that advice. Maybe I misjudged it.\n\nI can see there being failures so low-probability to omit that text, e.g. a\nfailure identified theoretically and requiring a process to lose the CPU for\nhours. For this one, the reporter seems to have arrived at it without a\ndeliberate search. This one just needs a recovery at the right WAL record,\nthen two processes reaching the incomplete split concurrently.\n\n\n",
"msg_date": "Fri, 2 Feb 2024 18:27:24 -0800",
"msg_from": "Noah Misch <noah@leadboat.com>",
"msg_from_op": false,
"msg_subject": "Re: Draft release notes for minor releases are up"
},
{
"msg_contents": "Noah Misch <noah@leadboat.com> writes:\n> On Fri, Feb 02, 2024 at 08:18:50PM -0500, Tom Lane wrote:\n>> Noah Misch <noah@leadboat.com> writes:\n>>> Shall the top of the notes advise to reindex GIN indexes?\n\n>> I thought about that, but it's a pretty low-probability failure\n>> I think, so I didn't write that advice. Maybe I misjudged it.\n\n> I can see there being failures so low-probability to omit that text, e.g. a\n> failure identified theoretically and requiring a process to lose the CPU for\n> hours. For this one, the reporter seems to have arrived at it without a\n> deliberate search. This one just needs a recovery at the right WAL record,\n> then two processes reaching the incomplete split concurrently.\n\nThe reporter didn't exactly say, but it did seem that the initial\ndetection was made without any code modifications, so I take your\npoint. I'll add the advice. Also, I now have this text for your\nCREATE DATABASE fixes:\n\n <para>\n Ensure durability of <command>CREATE DATABASE</command> (Noah Misch)\n </para>\n\n <para>\n If an operating system crash occurred during or shortly\n after <command>CREATE DATABASE</command>, recovery could fail, or\n subsequent connections to the new database could fail. If a base\n backup was taken in that window, similar problems could be observed\n when trying to use the backup. The symptom would be that the\n database directory, <filename>PG_VERSION</filename> file, or\n <filename>pg_filenode.map</filename> file was missing or empty.\n </para>\n\nThis is ignoring the point that the set of observable symptoms might\ndiffer between the OS crash and base-backup-recovery cases, but\nI'm not sure that that's actually true, and in any case I don't think\nit matters for the release notes.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Sun, 04 Feb 2024 13:13:53 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": true,
"msg_subject": "Re: Draft release notes for minor releases are up"
},
{
"msg_contents": "On Sun, Feb 04, 2024 at 01:13:53PM -0500, Tom Lane wrote:\n> I now have this text for your CREATE DATABASE fixes:\n> \n> <para>\n> Ensure durability of <command>CREATE DATABASE</command> (Noah Misch)\n> </para>\n> \n> <para>\n> If an operating system crash occurred during or shortly\n> after <command>CREATE DATABASE</command>, recovery could fail, or\n> subsequent connections to the new database could fail. If a base\n> backup was taken in that window, similar problems could be observed\n> when trying to use the backup. The symptom would be that the\n> database directory, <filename>PG_VERSION</filename> file, or\n> <filename>pg_filenode.map</filename> file was missing or empty.\n> </para>\n\nThanks for updating it; this text works for me.\n\n> This is ignoring the point that the set of observable symptoms might\n> differ between the OS crash and base-backup-recovery cases, but\n> I'm not sure that that's actually true, and in any case I don't think\n> it matters for the release notes.\n\nI agree with stopping short of adding that detail; it wouldn't help users make\na known decision.\n\n\n",
"msg_date": "Sun, 4 Feb 2024 10:53:31 -0800",
"msg_from": "Noah Misch <noah@leadboat.com>",
"msg_from_op": false,
"msg_subject": "Re: Draft release notes for minor releases are up"
}
] |
[
{
"msg_contents": "I couldn't find a reference to the 'langispl' attribute, so I removed it (see\nthe diff attached) and the master branch compiled cleanly. Is there yet a\nreason to keep it?\n\n-- \nAntonin Houska\nWeb: https://www.cybertec-postgresql.com",
"msg_date": "Fri, 02 Feb 2024 19:03:22 +0100",
"msg_from": "Antonin Houska <ah@cybertec.at>",
"msg_from_op": true,
"msg_subject": "pg_language(langispl) column apparently not needed"
},
{
"msg_contents": "Antonin Houska <ah@cybertec.at> writes:\n> I couldn't find a reference to the 'langispl' attribute, so I removed it (see\n> the diff attached) and the master branch compiled cleanly. Is there yet a\n> reason to keep it?\n\nYou didn't test pg_dump, I take it.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Fri, 02 Feb 2024 13:16:21 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: pg_language(langispl) column apparently not needed"
}
] |
[
{
"msg_contents": "Looking through the logs of some server that were experiencing out of\nmemory errors, I noticed that errcode_for_file_access() reports\nERRCODE_INTERNAL_ERROR for ENOMEM, while the correct SQLSTATE for this\nshould probably be ERRCODE_OUT_OF_MEMORY. Attached is a small patch to\nfix this.\n\n---\nAlexander Kuzmenkov\nTimescale",
"msg_date": "Fri, 2 Feb 2024 20:02:37 +0100",
"msg_from": "Alexander Kuzmenkov <akuzmenkov@timescale.com>",
"msg_from_op": true,
"msg_subject": "Correct SQLSTATE for ENOMEM in file access"
},
{
"msg_contents": "Alexander Kuzmenkov <akuzmenkov@timescale.com> writes:\n> Looking through the logs of some server that were experiencing out of\n> memory errors, I noticed that errcode_for_file_access() reports\n> ERRCODE_INTERNAL_ERROR for ENOMEM, while the correct SQLSTATE for this\n> should probably be ERRCODE_OUT_OF_MEMORY. Attached is a small patch to\n> fix this.\n\nHmm, do you think this is actually reachable? AFAIK we should only be\ncalling errcode_for_file_access() after functions that are unlikely to\nreport ENOMEM.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Fri, 02 Feb 2024 14:12:13 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Correct SQLSTATE for ENOMEM in file access"
},
{
"msg_contents": "On Fri, Feb 2, 2024 at 8:12 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Hmm, do you think this is actually reachable? AFAIK we should only be\n> calling errcode_for_file_access() after functions that are unlikely to\n> report ENOMEM.\n\nIt's reachable, that's how I noticed. I'm seeing logs like \"XX000:\ncould not load library \\\"/usr/lib/postgresql/15/lib/plpgsql.so\\\": out\nof memory\" from internal_load_library and so on. Not sure what is the\nexact configuration required to reproduce this, probably at least the\novercommit should be disabled.\n\n\n",
"msg_date": "Fri, 2 Feb 2024 20:28:39 +0100",
"msg_from": "Alexander Kuzmenkov <akuzmenkov@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: Correct SQLSTATE for ENOMEM in file access"
},
{
"msg_contents": "Alexander Kuzmenkov <akuzmenkov@timescale.com> writes:\n> On Fri, Feb 2, 2024 at 8:12 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Hmm, do you think this is actually reachable? AFAIK we should only be\n>> calling errcode_for_file_access() after functions that are unlikely to\n>> report ENOMEM.\n\n> It's reachable, that's how I noticed. I'm seeing logs like \"XX000:\n> could not load library \\\"/usr/lib/postgresql/15/lib/plpgsql.so\\\": out\n> of memory\" from internal_load_library and so on. Not sure what is the\n> exact configuration required to reproduce this, probably at least the\n> overcommit should be disabled.\n\nOK, can't argue with experimental evidence ;-)\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Fri, 02 Feb 2024 15:20:13 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Correct SQLSTATE for ENOMEM in file access"
}
] |
[
{
"msg_contents": "If you look at the buildfarm's failures page and filter down to\njust subscriptionCheck failures, what you find is that all of the\nlast 6 such failures are in 031_column_list.pl:\n\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=tamandua&dt=2024-02-02%2019%3A33%3A16\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=calliphoridae&dt=2024-02-02%2011%3A21%3A44\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=flaviventris&dt=2024-02-01%2020%3A34%3A29\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=flaviventris&dt=2024-02-01%2016%3A57%3A14\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=kestrel&dt=2024-01-31%2022%3A18%3A24\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=calliphoridae&dt=2024-01-30%2011%3A29%3A23\n\nThere are some further back too:\n\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mylodon&dt=2023-11-17%2018%3A28%3A24\n\nbut this definitely got way more common in the last few days.\n\nDigging down into the logs, these all look pretty similar. Somehow\nthings get into a state where replication connections fail with\nthe publisher reporting \"publication does not exist\":\n\n2024-02-02 19:42:23.187 UTC [1631708][not initialized][:0] LOG: connection received: host=[local]\n2024-02-02 19:42:23.189 UTC [1631708][walsender][4/287:0] LOG: connection authenticated: user=\"bf\" method=trust (/home/bf/bf-build/tamandua/HEAD/pgsql.build/testrun/subscription/031_column_list/data/t_031_column_list_publisher_data/pgdata/pg_hba.conf:117)\n2024-02-02 19:42:23.189 UTC [1631708][walsender][4/287:0] LOG: replication connection authorized: user=bf application_name=sub1\n2024-02-02 19:42:23.214 UTC [1631708][walsender][4/288:0] LOG: statement: SELECT pg_catalog.set_config('search_path', '', false);\n2024-02-02 19:42:23.226 UTC [1631708][walsender][4/0:0] LOG: received replication command: IDENTIFY_SYSTEM\n2024-02-02 19:42:23.226 UTC [1631708][walsender][4/0:0] STATEMENT: IDENTIFY_SYSTEM\n2024-02-02 19:42:23.226 UTC [1631708][walsender][4/0:0] LOG: received replication command: START_REPLICATION SLOT \"sub1\" LOGICAL 0/15BCDD0 (proto_version '4', origin 'any', publication_names '\"pub7\"')\n2024-02-02 19:42:23.226 UTC [1631708][walsender][4/0:0] STATEMENT: START_REPLICATION SLOT \"sub1\" LOGICAL 0/15BCDD0 (proto_version '4', origin 'any', publication_names '\"pub7\"')\n2024-02-02 19:42:23.226 UTC [1631708][walsender][4/0:0] LOG: acquired logical replication slot \"sub1\"\n2024-02-02 19:42:23.226 UTC [1631708][walsender][4/0:0] STATEMENT: START_REPLICATION SLOT \"sub1\" LOGICAL 0/15BCDD0 (proto_version '4', origin 'any', publication_names '\"pub7\"')\n2024-02-02 19:42:23.242 UTC [1631708][walsender][4/0:0] LOG: starting logical decoding for slot \"sub1\"\n2024-02-02 19:42:23.242 UTC [1631708][walsender][4/0:0] DETAIL: Streaming transactions committing after 0/15BCDD0, reading WAL from 0/15BCDD0.\n2024-02-02 19:42:23.242 UTC [1631708][walsender][4/0:0] STATEMENT: START_REPLICATION SLOT \"sub1\" LOGICAL 0/15BCDD0 (proto_version '4', origin 'any', publication_names '\"pub7\"')\n2024-02-02 19:42:23.243 UTC [1631708][walsender][4/0:0] LOG: logical decoding found consistent point at 0/15BCDD0\n2024-02-02 19:42:23.243 UTC [1631708][walsender][4/0:0] DETAIL: There are no running transactions.\n2024-02-02 19:42:23.243 UTC [1631708][walsender][4/0:0] STATEMENT: START_REPLICATION SLOT \"sub1\" LOGICAL 0/15BCDD0 (proto_version '4', origin 'any', publication_names '\"pub7\"')\n2024-02-02 19:42:23.244 UTC [1631708][walsender][4/0:0] ERROR: publication \"pub7\" does not exist\n2024-02-02 19:42:23.244 UTC [1631708][walsender][4/0:0] CONTEXT: slot \"sub1\", output plugin \"pgoutput\", in the change callback, associated LSN 0/15C7698\n2024-02-02 19:42:23.244 UTC [1631708][walsender][4/0:0] STATEMENT: START_REPLICATION SLOT \"sub1\" LOGICAL 0/15BCDD0 (proto_version '4', origin 'any', publication_names '\"pub7\"')\n2024-02-02 19:42:23.244 UTC [1631708][walsender][4/0:0] LOG: released logical replication slot \"sub1\"\n2024-02-02 19:42:23.834 UTC [1631708][walsender][:0] LOG: disconnection: session time: 0:00:00.647 user=bf database=postgres host=[local]\n\nand then we just repeat that until the test times out. It fails at\ndifferent points in the test script (hence, different publication\nnames), but the pattern looks about the same.\n\nI don't see anything that 031_column_list.pl is doing that is much\ndifferent from other subscription tests, so why is it the only one\nfailing? And more to the point, what's going wrong exactly?\n\nI am suspicious that this somehow represents a failure of the\nhistorical catalog decoding logic, but I don't see how that theory\nexplains this only breaking in one test script.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Fri, 02 Feb 2024 17:07:14 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": true,
"msg_subject": "Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "On Fri, Feb 02, 2024 at 05:07:14PM -0500, Tom Lane wrote:\n> If you look at the buildfarm's failures page and filter down to\n> just subscriptionCheck failures, what you find is that all of the\n> last 6 such failures are in 031_column_list.pl:\n> \n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=tamandua&dt=2024-02-02%2019%3A33%3A16\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=calliphoridae&dt=2024-02-02%2011%3A21%3A44\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=flaviventris&dt=2024-02-01%2020%3A34%3A29\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=flaviventris&dt=2024-02-01%2016%3A57%3A14\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=kestrel&dt=2024-01-31%2022%3A18%3A24\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=calliphoridae&dt=2024-01-30%2011%3A29%3A23\n> \n> There are some further back too:\n> \n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mylodon&dt=2023-11-17%2018%3A28%3A24\n> \n> but this definitely got way more common in the last few days.\n\n> I don't see anything that 031_column_list.pl is doing that is much\n> different from other subscription tests, so why is it the only one\n> failing? And more to the point, what's going wrong exactly?\n\nI don't know, but\nhttps://www.postgresql.org/message-id/flat/16d6d9cc-f97d-0b34-be65-425183ed3721%40gmail.com\nreported a replacement BgWriterDelay value reproducing it. That hasn't\nreproduced it in ~10 runs on my machine, though.\n\n> I am suspicious that this somehow represents a failure of the\n> historical catalog decoding logic, but I don't see how that theory\n> explains this only breaking in one test script.\n\n\n",
"msg_date": "Fri, 2 Feb 2024 14:30:03 -0800",
"msg_from": "Noah Misch <noah@leadboat.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "On Fri, Feb 02, 2024 at 02:30:03PM -0800, Noah Misch wrote:\n> On Fri, Feb 02, 2024 at 05:07:14PM -0500, Tom Lane wrote:\n> > If you look at the buildfarm's failures page and filter down to\n> > just subscriptionCheck failures, what you find is that all of the\n> > last 6 such failures are in 031_column_list.pl:\n> > \n> > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=tamandua&dt=2024-02-02%2019%3A33%3A16\n> > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=calliphoridae&dt=2024-02-02%2011%3A21%3A44\n> > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=flaviventris&dt=2024-02-01%2020%3A34%3A29\n> > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=flaviventris&dt=2024-02-01%2016%3A57%3A14\n> > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=kestrel&dt=2024-01-31%2022%3A18%3A24\n> > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=calliphoridae&dt=2024-01-30%2011%3A29%3A23\n> > \n> > There are some further back too:\n> > \n> > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mylodon&dt=2023-11-17%2018%3A28%3A24\n> > \n> > but this definitely got way more common in the last few days.\n> \n> > I don't see anything that 031_column_list.pl is doing that is much\n> > different from other subscription tests, so why is it the only one\n> > failing? And more to the point, what's going wrong exactly?\n> \n> I don't know, but\n> https://www.postgresql.org/message-id/flat/16d6d9cc-f97d-0b34-be65-425183ed3721%40gmail.com\n> reported a replacement BgWriterDelay value reproducing it.\n\nCorrection: the recipe changes LOG_SNAPSHOT_INTERVAL_MS in addition to\nBgWriterDelay.\n\n> That hasn't reproduced it in ~10 runs on my machine, though.\n\nAfter 207 successes, it did fail once for me.\n\n> > I am suspicious that this somehow represents a failure of the\n> > historical catalog decoding logic, but I don't see how that theory\n> > explains this only breaking in one test script.\n\n\n",
"msg_date": "Fri, 2 Feb 2024 16:01:45 -0800",
"msg_from": "Noah Misch <noah@leadboat.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "Noah Misch <noah@leadboat.com> writes:\n> On Fri, Feb 02, 2024 at 05:07:14PM -0500, Tom Lane wrote:\n>> If you look at the buildfarm's failures page and filter down to\n>> just subscriptionCheck failures, what you find is that all of the\n>> last 6 such failures are in 031_column_list.pl:\n>> ...\n>> I don't see anything that 031_column_list.pl is doing that is much\n>> different from other subscription tests, so why is it the only one\n>> failing? And more to the point, what's going wrong exactly?\n\n> I don't know, but\n> https://www.postgresql.org/message-id/flat/16d6d9cc-f97d-0b34-be65-425183ed3721%40gmail.com\n> reported a replacement BgWriterDelay value reproducing it. That hasn't\n> reproduced it in ~10 runs on my machine, though.\n\nAh, thanks for that link. I like the theory proposed in that thread\nthat the walsender is starting up at an LSN somewhere before where\nthe publication is created. I'm tempted to add some more queries to\nthe test script to see if that can be proven.\n\nI'm still wondering how come the failure seems to have suddenly gotten\nway more common. The only changes that are in vaguely-related places\nand fit the time frame are Amit's 732924043 and 776621a5e, but I sure\ndon't see a connection.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Fri, 02 Feb 2024 20:24:34 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": true,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "Hello Tom and Noah,\n\n03.02.2024 04:24, Tom Lane wrote:\n> I'm still wondering how come the failure seems to have suddenly gotten\n> way more common. The only changes that are in vaguely-related places\n> and fit the time frame are Amit's 732924043 and 776621a5e, but I sure\n> don't see a connection.\n\nI think the failure rate increased due to tamandua, calliphoridae,\nflaviventris, and kestrel were switched from make to meson recently.\nThe last `make` builds for them:\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=tamandua&dt=2024-01-31%2016%3A51%3A31\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=calliphoridae&dt=2024-01-31%2016%3A51%3A38\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=flaviventris&dt=2024-01-31%2016%3A52%3A37\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=kestrel&dt=2024-01-31%2016%3A51%3A53\n\nand since that switch the 031_column_list duration increased significantly,\ne.g., on the last tamandua `make` run it executed for 7 seconds, but\nsuccessful `meson` runs give much longer duration:\n280/283 postgresql:subscription / subscription/031_column_list OK 38.27s 36 subtests passed\n280/283 postgresql:subscription / subscription/031_column_list OK 126.13s 36 subtests passed\n280/283 postgresql:subscription / subscription/031_column_list OK 31.93s 36 subtests passed\n279/283 postgresql:subscription / subscription/031_column_list OK 99.76s 36 subtests passed\n\nSo, looking at the tamandua's failure log, I see:\n2024-02-02 19:41:19.750 UTC [1579219][postmaster][:0] LOG: starting PostgreSQL 17devel on x86_64-linux, compiled by \ngcc-12.3.0, 64-bit\n...\n2024-02-02 19:42:19.973 UTC [1629333][client backend][4/213:0] LOG: statement: ALTER SUBSCRIPTION sub1 SET PUBLICATION pub7\n2024-02-02 19:42:20.131 UTC [1625765][logical replication apply worker][3/122:0] LOG: logical replication worker for \nsubscription \"sub1\" will restart because of a parameter change\n2024-02-02 19:42:20.137 UTC [1629333][client backend][:0] LOG: disconnection: session time: 0:00:00.212 user=bf \ndatabase=postgres host=[local]\n2024-02-02 19:42:20.191 UTC [1629535][logical replication apply worker][3/124:0] LOG: logical replication apply worker \nfor subscription \"sub1\" has started\n...\n2024-02-02 19:42:20.445 UTC [1629535][logical replication apply worker][3/0:0] ERROR: could not receive data from WAL \nstream: ERROR: publication \"pub7\" does not exist\n CONTEXT: slot \"sub1\", output plugin \"pgoutput\", in the change callback, associated LSN 0/15C7698\n\n(The interval between subscriber start and the error is ~ 4 * 15 seconds.)\n\nThus it still may be explained by bgwriter activity, though perhaps\nautovacuum/checkpointer can add something as well.\n\nBest regards,\nAlexander\n\n\n",
"msg_date": "Sat, 3 Feb 2024 10:00:00 +0300",
"msg_from": "Alexander Lakhin <exclusion@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "On Sat, Feb 3, 2024 at 12:30 PM Alexander Lakhin <exclusion@gmail.com> wrote:\n>\n> 03.02.2024 04:24, Tom Lane wrote:\n> > I'm still wondering how come the failure seems to have suddenly gotten\n> > way more common. The only changes that are in vaguely-related places\n> > and fit the time frame are Amit's 732924043 and 776621a5e, but I sure\n> > don't see a connection.\n>\n> I think the failure rate increased due to tamandua, calliphoridae,\n> flaviventris, and kestrel were switched from make to meson recently.\n>\n\nIf this can be reproduced frequently then we can even try to test the\npatch in that thread by Osumi-San [1] (I haven't tested that it\napplies cleanly but shouldn't be difficult to make it work) based on\nthe theory that walsender is starting up at an LSN somewhere before\nwhere the publication is created.\n\n[1] - https://www.postgresql.org/message-id/TYCPR01MB83737A68CD5D554EA82BD7B9EDD39%40TYCPR01MB8373.jpnprd01.prod.outlook.com\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Mon, 5 Feb 2024 17:50:30 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "Hello Amit,\n\n05.02.2024 15:20, Amit Kapila wrote:\n> If this can be reproduced frequently then we can even try to test the\n> patch in that thread by Osumi-San [1] (I haven't tested that it\n> applies cleanly but shouldn't be difficult to make it work) based on\n> the theory that walsender is starting up at an LSN somewhere before\n> where the publication is created.\n>\n> [1] - https://www.postgresql.org/message-id/TYCPR01MB83737A68CD5D554EA82BD7B9EDD39%40TYCPR01MB8373.jpnprd01.prod.outlook.com\n>\n\nYes, with the aforementioned modification of bgwriter.c and when running\n20 tests in parallel, I got failures on iterations 20. 3, 21 ..., but with the\nupdated Osumi-San's patch (which adds wait_for_catchup('sub1') before every\nALTER SUBSCRIPTION sub1 SET PUBLICATION ...) applied, 300 iterations ran\nwith no failures.\n\nBest regards,\nAlexander",
"msg_date": "Tue, 6 Feb 2024 06:00:00 +0300",
"msg_from": "Alexander Lakhin <exclusion@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "On Tue, Feb 6, 2024 at 8:30 AM Alexander Lakhin <exclusion@gmail.com> wrote:\n>\n> 05.02.2024 15:20, Amit Kapila wrote:\n> > If this can be reproduced frequently then we can even try to test the\n> > patch in that thread by Osumi-San [1] (I haven't tested that it\n> > applies cleanly but shouldn't be difficult to make it work) based on\n> > the theory that walsender is starting up at an LSN somewhere before\n> > where the publication is created.\n> >\n> > [1] - https://www.postgresql.org/message-id/TYCPR01MB83737A68CD5D554EA82BD7B9EDD39%40TYCPR01MB8373.jpnprd01.prod.outlook.com\n> >\n>\n> Yes, with the aforementioned modification of bgwriter.c and when running\n> 20 tests in parallel, I got failures on iterations 20. 3, 21 ..., but with the\n> updated Osumi-San's patch (which adds wait_for_catchup('sub1') before every\n> ALTER SUBSCRIPTION sub1 SET PUBLICATION ...) applied, 300 iterations ran\n> with no failures.\n>\n\ncool, is it possible to see whether this patch changes the runtime of\nthis test in any noticeable way?\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Tue, 6 Feb 2024 12:18:05 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "06.02.2024 09:48, Amit Kapila wrote:\n> cool, is it possible to see whether this patch changes the runtime of\n> this test in any noticeable way?\n>\n\nYes, unfortunately it does.\nI've measured duration of 100 tests runs without the patch (with pristine\nbgwriter and with NO_TEMP_INSTALL):\nreal 6m46,031s\nreal 6m52,406s\nreal 6m51,014s\n\nBut with the patched test, I've got:\nreal 9m39,872s\nreal 9m40,044s\nreal 9m38,236s\n(nearly 2 seconds increase per one test run)\n\nUnder Valgrind, the original test run takes:\nFiles=1, Tests=36, 334 wallclock secs ( 0.02 usr 0.00 sys + 163.14 cusr 7.98 csys = 171.14 CPU)\n\nBut the patched one:\nFiles=1, Tests=36, 368 wallclock secs ( 0.02 usr 0.00 sys + 182.16 cusr 8.90 csys = 191.08 CPU)\n(30 seconds increase)\n\nMaybe the more CPU-efficient solution would be disabling bgworker, as was\nproposed in another discussion of tests instability:\nhttps://www.postgresql.org/message-id/ZaTxhjnPygOdosJ4%40ip-10-97-1-34.eu-west-3.compute.internal\n\nThough I think that devising a way to control bgwriter may take more time\nthan we can afford given the current 031 failure rate on the buildfarm\n(17 failures for the last 3 days).\n\nBest regards,\nAlexander\n\n\n",
"msg_date": "Tue, 6 Feb 2024 12:00:00 +0300",
"msg_from": "Alexander Lakhin <exclusion@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "On Tue, Feb 6, 2024 at 2:30 PM Alexander Lakhin <exclusion@gmail.com> wrote:\n>\n> 06.02.2024 09:48, Amit Kapila wrote:\n> > cool, is it possible to see whether this patch changes the runtime of\n> > this test in any noticeable way?\n> >\n>\n> Yes, unfortunately it does.\n> I've measured duration of 100 tests runs without the patch (with pristine\n> bgwriter and with NO_TEMP_INSTALL):\n> real 6m46,031s\n> real 6m52,406s\n> real 6m51,014s\n>\n> But with the patched test, I've got:\n> real 9m39,872s\n> real 9m40,044s\n> real 9m38,236s\n> (nearly 2 seconds increase per one test run)\n>\n> Under Valgrind, the original test run takes:\n> Files=1, Tests=36, 334 wallclock secs ( 0.02 usr 0.00 sys + 163.14 cusr 7.98 csys = 171.14 CPU)\n>\n> But the patched one:\n> Files=1, Tests=36, 368 wallclock secs ( 0.02 usr 0.00 sys + 182.16 cusr 8.90 csys = 191.08 CPU)\n> (30 seconds increase)\n>\n\nYeah, I was worried about that. The other idea I have previously\nthought was to change Alter Subscription to Drop+Create Subscription.\nThat should also help in bringing stability without losing any\nfunctionality.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Tue, 6 Feb 2024 18:08:55 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "Amit Kapila <amit.kapila16@gmail.com> writes:\n> Yeah, I was worried about that. The other idea I have previously\n> thought was to change Alter Subscription to Drop+Create Subscription.\n> That should also help in bringing stability without losing any\n> functionality.\n\nHm, why would that fix it?\n\nMore to the point, aren't these proposals just band-aids that\nwould stabilize the test without fixing the actual problem?\nThe same thing is likely to happen to people in the field,\nunless we do something drastic like removing ALTER SUBSCRIPTION.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Tue, 06 Feb 2024 09:51:56 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": true,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "I wrote:\n> More to the point, aren't these proposals just band-aids that\n> would stabilize the test without fixing the actual problem?\n> The same thing is likely to happen to people in the field,\n> unless we do something drastic like removing ALTER SUBSCRIPTION.\n\nI've been able to make the 031_column_list.pl failure pretty\nreproducible by adding a delay in walsender, as attached.\n\nWhile I'm not too familiar with this code, it definitely does appear\nthat the new walsender is told to start up at an LSN before the\ncreation of the publication, and then if it needs to decide whether\nto stream a particular data change before it's reached that creation,\nkaboom!\n\nI read and understood the upthread worries about it not being\na great idea to ignore publication lookup failures, but I really\ndon't see that we have much choice. As an example, if a subscriber\nis humming along reading publication pub1, and then someone\ndrops and then recreates pub1 on the publisher, I don't think that\nthe subscriber will be able to advance through that gap if there\nare any operations within it that require deciding if they should\nbe streamed. (That is, contrary to Amit's expectation that\nDROP/CREATE would mask the problem, I suspect it will instead turn\nit into a hard failure. I've not experimented though.)\n\nBTW, this same change breaks two other subscription tests:\n015_stream.pl and 022_twophase_cascade.pl.\nThe symptoms are different (no \"publication does not exist\" errors),\nso maybe these are just test problems not fundamental weaknesses.\nBut \"replication falls over if the walsender is slow\" isn't\nsomething I'd call acceptable.\n\n\t\t\tregards, tom lane",
"msg_date": "Tue, 06 Feb 2024 15:36:29 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": true,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "On Tue, 6 Feb 2024 at 08:30, Alexander Lakhin <exclusion@gmail.com> wrote:\n>\n> Hello Amit,\n>\n> 05.02.2024 15:20, Amit Kapila wrote:\n> > If this can be reproduced frequently then we can even try to test the\n> > patch in that thread by Osumi-San [1] (I haven't tested that it\n> > applies cleanly but shouldn't be difficult to make it work) based on\n> > the theory that walsender is starting up at an LSN somewhere before\n> > where the publication is created.\n> >\n> > [1] - https://www.postgresql.org/message-id/TYCPR01MB83737A68CD5D554EA82BD7B9EDD39%40TYCPR01MB8373.jpnprd01.prod.outlook.com\n> >\n>\n> Yes, with the aforementioned modification of bgwriter.c and when running\n> 20 tests in parallel, I got failures on iterations 20. 3, 21 ..., but with the\n> updated Osumi-San's patch (which adds wait_for_catchup('sub1') before every\n> ALTER SUBSCRIPTION sub1 SET PUBLICATION ...) applied, 300 iterations ran\n> with no failures.\n\nI was able to reproduce the issue with the patch changes suggested in\nbgwriter, but for me it failed in the 287th run.\nThen I had run the test 1000 times with the test changes shared at [1]\nand the test had passed all the 1000 times successfully.\n\nI have measured the test execution with average of 10 runs and found\nthat it takes about 1.2 seconds more time to execute with the changes:\nWithout patch: 8.454 seconds\nWith test change patch: 9.672 seconds\n\nFor the test execution comparison I had used a machine which has total\nMemory of 755.536 GB, 120 CPUs and RHEL 7 Operating System.\n\n[1] - https://www.postgresql.org/message-id/e6ce3cf7-4025-f129-e3ac-0f778469f720%40gmail.com\n\nRegards,\nVignesh\n\n\n",
"msg_date": "Wed, 7 Feb 2024 10:49:40 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "On Tue, Feb 6, 2024 at 8:21 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Amit Kapila <amit.kapila16@gmail.com> writes:\n> > Yeah, I was worried about that. The other idea I have previously\n> > thought was to change Alter Subscription to Drop+Create Subscription.\n> > That should also help in bringing stability without losing any\n> > functionality.\n>\n> Hm, why would that fix it?\n>\n\nBecause for new subscriptions, we will start reading WAL from the\nlatest WAL insert pointer on the publisher which will be after the\npoint where publication is created.\n\n> More to the point, aren't these proposals just band-aids that\n> would stabilize the test without fixing the actual problem?\n\nYes, but OTOH, this behavior has been since the beginning of logical\nreplication. This particular test has just exposed it, so keeping BF\nfailing for this particular test doesn't sound like the best way to\nremember it.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Wed, 7 Feb 2024 15:21:18 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "On Wed, Feb 7, 2024 at 2:06 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> I wrote:\n> > More to the point, aren't these proposals just band-aids that\n> > would stabilize the test without fixing the actual problem?\n> > The same thing is likely to happen to people in the field,\n> > unless we do something drastic like removing ALTER SUBSCRIPTION.\n>\n> I've been able to make the 031_column_list.pl failure pretty\n> reproducible by adding a delay in walsender, as attached.\n>\n> While I'm not too familiar with this code, it definitely does appear\n> that the new walsender is told to start up at an LSN before the\n> creation of the publication, and then if it needs to decide whether\n> to stream a particular data change before it's reached that creation,\n> kaboom!\n>\n> I read and understood the upthread worries about it not being\n> a great idea to ignore publication lookup failures, but I really\n> don't see that we have much choice. As an example, if a subscriber\n> is humming along reading publication pub1, and then someone\n> drops and then recreates pub1 on the publisher, I don't think that\n> the subscriber will be able to advance through that gap if there\n> are any operations within it that require deciding if they should\n> be streamed.\n>\n\nRight. One idea to address those worries was to have a new\nsubscription option like ignore_nonexistant_pubs (or some better name\nfor such an option). The 'true' value of this new option means that we\nwill ignore the publication lookup failures and continue replication,\nthe 'false' means give an error as we are doing now. If we agree that\nsuch an option is useful or at least saves us in some cases as\ndiscussed in another thread [1], we can keep the default value as true\nso that users don't face such errors by default and also have a way to\ngo back to current behavior.\n\n>\n (That is, contrary to Amit's expectation that\n> DROP/CREATE would mask the problem, I suspect it will instead turn\n> it into a hard failure. I've not experimented though.)\n>\n\nThis is not contrary because I was suggesting to DROP/CREATE\nSubscription whereas you are talking of drop and recreate of\nPublication.\n\n> BTW, this same change breaks two other subscription tests:\n> 015_stream.pl and 022_twophase_cascade.pl.\n> The symptoms are different (no \"publication does not exist\" errors),\n> so maybe these are just test problems not fundamental weaknesses.\n>\n\nAs per the initial analysis, this is because those cases have somewhat\nlarger transactions (more than 64kB) under test so it just times out\nwaiting for all the data to be replicated. We will do further analysis\nand share the findings.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Wed, 7 Feb 2024 15:25:48 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "On Wed, 7 Feb 2024 at 15:21, Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Tue, Feb 6, 2024 at 8:21 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >\n> > Amit Kapila <amit.kapila16@gmail.com> writes:\n> > > Yeah, I was worried about that. The other idea I have previously\n> > > thought was to change Alter Subscription to Drop+Create Subscription.\n> > > That should also help in bringing stability without losing any\n> > > functionality.\n> >\n> > Hm, why would that fix it?\n> >\n>\n> Because for new subscriptions, we will start reading WAL from the\n> latest WAL insert pointer on the publisher which will be after the\n> point where publication is created.\n\nI was able to reproduce the issue consistently with the changes shared\nby Tom Lane at [1].\nI have made changes to change ALTER SUBSCRIPTION to DROP+CREATE\nSUBSCRIPTION and verified that the test has passed consistently for\n>50 runs that I ran. Also the test execution time increased for this\ncase is very negligibly:\nWithout patch: 7.991 seconds\nWith test change patch: 8.121 seconds\n\nThe test changes for the same are attached.\n\n[1] - https://www.postgresql.org/message-id/631312.1707251789%40sss.pgh.pa.us\n\nRegards,\nVignesh",
"msg_date": "Wed, 7 Feb 2024 16:27:10 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "On Wed, 7 Feb 2024 at 15:26, Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Wed, Feb 7, 2024 at 2:06 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >\n> > I wrote:\n> > > More to the point, aren't these proposals just band-aids that\n> > > would stabilize the test without fixing the actual problem?\n> > > The same thing is likely to happen to people in the field,\n> > > unless we do something drastic like removing ALTER SUBSCRIPTION.\n> >\n> > I've been able to make the 031_column_list.pl failure pretty\n> > reproducible by adding a delay in walsender, as attached.\n> >\n> > While I'm not too familiar with this code, it definitely does appear\n> > that the new walsender is told to start up at an LSN before the\n> > creation of the publication, and then if it needs to decide whether\n> > to stream a particular data change before it's reached that creation,\n> > kaboom!\n> >\n> > I read and understood the upthread worries about it not being\n> > a great idea to ignore publication lookup failures, but I really\n> > don't see that we have much choice. As an example, if a subscriber\n> > is humming along reading publication pub1, and then someone\n> > drops and then recreates pub1 on the publisher, I don't think that\n> > the subscriber will be able to advance through that gap if there\n> > are any operations within it that require deciding if they should\n> > be streamed.\n> >\n>\n> Right. One idea to address those worries was to have a new\n> subscription option like ignore_nonexistant_pubs (or some better name\n> for such an option). The 'true' value of this new option means that we\n> will ignore the publication lookup failures and continue replication,\n> the 'false' means give an error as we are doing now. If we agree that\n> such an option is useful or at least saves us in some cases as\n> discussed in another thread [1], we can keep the default value as true\n> so that users don't face such errors by default and also have a way to\n> go back to current behavior.\n>\n> >\n> (That is, contrary to Amit's expectation that\n> > DROP/CREATE would mask the problem, I suspect it will instead turn\n> > it into a hard failure. I've not experimented though.)\n> >\n>\n> This is not contrary because I was suggesting to DROP/CREATE\n> Subscription whereas you are talking of drop and recreate of\n> Publication.\n>\n> > BTW, this same change breaks two other subscription tests:\n> > 015_stream.pl and 022_twophase_cascade.pl.\n> > The symptoms are different (no \"publication does not exist\" errors),\n> > so maybe these are just test problems not fundamental weaknesses.\n> >\n>\n> As per the initial analysis, this is because those cases have somewhat\n> larger transactions (more than 64kB) under test so it just times out\n> waiting for all the data to be replicated. We will do further analysis\n> and share the findings.\n\nYes, these tests are failing while waiting to catchup the larger\ntransactions to be replicated within180 seconds, as the transactions\nneeds more time to replicate because of the sleep added. To verify\nthis I had tried a couple of things a) I had increased the timeout to\na higher value and verified that both the test runs successfully with\n1800 seconds timeout. b) I reduced the sleep to 1000 microseconds and\nverified that both the test runs successfully.\n\nSo I feel these tests 015_stream.pl and 022_twophase_cascade.pl\nfailing after the sleep added can be ignored.\n\nRegards,\nVignesh\n\n\n",
"msg_date": "Wed, 7 Feb 2024 18:39:49 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "Coincidentally, one of my buildfarm animals hanged several weeks in a\ndifferent test, 035_standby_logical_decoding.pl. A LOG_SNAPSHOT_INTERVAL_MS\nreduction was part of making it reproducible:\n\nOn Fri, Feb 02, 2024 at 04:01:45PM -0800, Noah Misch wrote:\n> On Fri, Feb 02, 2024 at 02:30:03PM -0800, Noah Misch wrote:\n> > On Fri, Feb 02, 2024 at 05:07:14PM -0500, Tom Lane wrote:\n> > > If you look at the buildfarm's failures page and filter down to\n> > > just subscriptionCheck failures, what you find is that all of the\n> > > last 6 such failures are in 031_column_list.pl:\n\n> > https://www.postgresql.org/message-id/flat/16d6d9cc-f97d-0b34-be65-425183ed3721%40gmail.com\n> > reported a replacement BgWriterDelay value reproducing it.\n> \n> Correction: the recipe changes LOG_SNAPSHOT_INTERVAL_MS in addition to\n> BgWriterDelay.\n\nI'm reusing this thread just in case there's overlap with the\n031_column_list.pl cause and fix. The 035_standby_logical_decoding.pl hang is\na race condition arising from an event sequence like this:\n\n- Test script sends CREATE SUBSCRIPTION to subscriber, which loses the CPU.\n- Test script calls pg_log_standby_snapshot() on primary. Emits XLOG_RUNNING_XACTS.\n- checkpoint_timeout makes a primary checkpoint finish. Emits XLOG_RUNNING_XACTS.\n- bgwriter executes LOG_SNAPSHOT_INTERVAL_MS logic. Emits XLOG_RUNNING_XACTS.\n- CREATE SUBSCRIPTION wakes up and sends CREATE_REPLICATION_SLOT to standby.\n\nOther test code already has a solution for this, so the attached patches add a\ntimeout and copy the existing solution. I'm also attaching the hack that\nmakes it 100% reproducible.",
"msg_date": "Sat, 10 Feb 2024 17:02:27 -0800",
"msg_from": "Noah Misch <noah@leadboat.com>",
"msg_from_op": false,
"msg_subject": "035_standby_logical_decoding unbounded hang"
},
{
"msg_contents": "On Wed, 7 Feb 2024 at 16:27, vignesh C <vignesh21@gmail.com> wrote:\n>\n> On Wed, 7 Feb 2024 at 15:21, Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n> > On Tue, Feb 6, 2024 at 8:21 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > >\n> > > Amit Kapila <amit.kapila16@gmail.com> writes:\n> > > > Yeah, I was worried about that. The other idea I have previously\n> > > > thought was to change Alter Subscription to Drop+Create Subscription.\n> > > > That should also help in bringing stability without losing any\n> > > > functionality.\n> > >\n> > > Hm, why would that fix it?\n> > >\n> >\n> > Because for new subscriptions, we will start reading WAL from the\n> > latest WAL insert pointer on the publisher which will be after the\n> > point where publication is created.\n>\n> I was able to reproduce the issue consistently with the changes shared\n> by Tom Lane at [1].\n> I have made changes to change ALTER SUBSCRIPTION to DROP+CREATE\n> SUBSCRIPTION and verified that the test has passed consistently for\n> >50 runs that I ran. Also the test execution time increased for this\n> case is very negligibly:\n> Without patch: 7.991 seconds\n> With test change patch: 8.121 seconds\n>\n> The test changes for the same are attached.\n\nAlternative, this could also be fixed like the changes proposed by\nAmit at [1]. In this case we ignore publications that are not found\nfor the purpose of computing RelSyncEntry attributes. We won't mark\nsuch an entry as valid till all the publications are loaded without\nanything missing. This means we won't publish operations on tables\ncorresponding to that publication till we found such a publication and\nthat seems okay.\n\nTomas had raised a performance issue forcing us to reload it for every\nreplicated change/row in case the publications are invalid at [2]. How\nabout keeping the default option as it is and providing a new option\nskip_not_exist_publication while creating/altering a subscription. In\nthis case if skip_not_exist_publication is specified we will ignore\nthe case if publication is not present and publications will be kept\nin invalid and get validated later.\n\nThe attached patch has the changes for the same. Thoughts?\n\n[1] - https://www.postgresql.org/message-id/CAA4eK1%2BT-ETXeRM4DHWzGxBpKafLCp__5bPA_QZfFQp7-0wj4Q%40mail.gmail.com\n[2] - https://www.postgresql.org/message-id/dc08add3-10a8-738b-983a-191c7406707b%40enterprisedb.com\n\nRegards,\nVignesh",
"msg_date": "Wed, 14 Feb 2024 04:07:16 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "Hi,\n\nOn Sat, Feb 10, 2024 at 05:02:27PM -0800, Noah Misch wrote:\n> Coincidentally, one of my buildfarm animals hanged several weeks in a\n> different test, 035_standby_logical_decoding.pl. A LOG_SNAPSHOT_INTERVAL_MS\n> reduction was part of making it reproducible:\n> \n> On Fri, Feb 02, 2024 at 04:01:45PM -0800, Noah Misch wrote:\n> > On Fri, Feb 02, 2024 at 02:30:03PM -0800, Noah Misch wrote:\n> > > On Fri, Feb 02, 2024 at 05:07:14PM -0500, Tom Lane wrote:\n> > > > If you look at the buildfarm's failures page and filter down to\n> > > > just subscriptionCheck failures, what you find is that all of the\n> > > > last 6 such failures are in 031_column_list.pl:\n> \n> > > https://www.postgresql.org/message-id/flat/16d6d9cc-f97d-0b34-be65-425183ed3721%40gmail.com\n> > > reported a replacement BgWriterDelay value reproducing it.\n> > \n> > Correction: the recipe changes LOG_SNAPSHOT_INTERVAL_MS in addition to\n> > BgWriterDelay.\n> \n> I'm reusing this thread just in case there's overlap with the\n> 031_column_list.pl cause and fix. The 035_standby_logical_decoding.pl hang is\n> a race condition arising from an event sequence like this:\n> \n> - Test script sends CREATE SUBSCRIPTION to subscriber, which loses the CPU.\n> - Test script calls pg_log_standby_snapshot() on primary. Emits XLOG_RUNNING_XACTS.\n> - checkpoint_timeout makes a primary checkpoint finish. Emits XLOG_RUNNING_XACTS.\n> - bgwriter executes LOG_SNAPSHOT_INTERVAL_MS logic. Emits XLOG_RUNNING_XACTS.\n> - CREATE SUBSCRIPTION wakes up and sends CREATE_REPLICATION_SLOT to standby.\n> \n> Other test code already has a solution for this, so the attached patches add a\n> timeout and copy the existing solution. I'm also attaching the hack that\n> makes it 100% reproducible.\n\nThanks!\n\nI did a few tests and confirm that the proposed solution fixes the corner case.\n\nstandby-slot-test-1-timeout-v1.patch LGTM.\n\nRegarding standby-slot-test-2-race-v1.patch:\n\n> +# See corresponding create_logical_slot_on_standby() code.\n> +$node_standby->poll_query_until(\n> +\t'postgres', qq[\n> +\t\tSELECT restart_lsn IS NOT NULL\n> +\t\tFROM pg_catalog.pg_replication_slots WHERE slot_name = 'tap_sub'\n> +\t]) or die \"timed out waiting for logical slot to calculate its restart_lsn\";\n> +\n\nWhat about creating a sub, say wait_for_restart_lsn_calculation() in Cluster.pm\nand then make use of it in create_logical_slot_on_standby() and above? (something\nlike wait_for_restart_lsn_calculation-v1.patch attached).\n\nRegards,\n\n-- \nBertrand Drouvot\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Wed, 14 Feb 2024 15:31:16 +0000",
"msg_from": "Bertrand Drouvot <bertranddrouvot.pg@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: 035_standby_logical_decoding unbounded hang"
},
{
"msg_contents": "On Wed, Feb 14, 2024 at 12:58 PM vignesh C <vignesh21@gmail.com> wrote:\n>\n> On Wed, 7 Feb 2024 at 16:27, vignesh C <vignesh21@gmail.com> wrote:\n> >\n> > I was able to reproduce the issue consistently with the changes shared\n> > by Tom Lane at [1].\n> > I have made changes to change ALTER SUBSCRIPTION to DROP+CREATE\n> > SUBSCRIPTION and verified that the test has passed consistently for\n> > >50 runs that I ran. Also the test execution time increased for this\n> > case is very negligibly:\n> > Without patch: 7.991 seconds\n> > With test change patch: 8.121 seconds\n> >\n> > The test changes for the same are attached.\n>\n> Alternative, this could also be fixed like the changes proposed by\n> Amit at [1]. In this case we ignore publications that are not found\n> for the purpose of computing RelSyncEntry attributes. We won't mark\n> such an entry as valid till all the publications are loaded without\n> anything missing. This means we won't publish operations on tables\n> corresponding to that publication till we found such a publication and\n> that seems okay.\n>\n> Tomas had raised a performance issue forcing us to reload it for every\n> replicated change/row in case the publications are invalid at [2].\n>\n\nDid you measure the performance impact? I think it should impact the\nperformance only when there is a dropped/non-existent publication as\nper the subscription definition. Also, in the same email[2], Tomas\nraised another concern that in such cases it is better to break the\nreplication.\n\n>\n How\n> about keeping the default option as it is and providing a new option\n> skip_not_exist_publication while creating/altering a subscription. In\n> this case if skip_not_exist_publication is specified we will ignore\n> the case if publication is not present and publications will be kept\n> in invalid and get validated later.\n>\n\nI don't know if this deserves a separate option or not but I think it\nis better to discuss this in a separate thread. To resolve the BF\nfailure, I still feel, we should just recreate the subscription. This\nis a pre-existing problem and we can track it via a separate patch\nwith a test case targetting such failures.\n\n> The attached patch has the changes for the same. Thoughts?\n>\n> [1] - https://www.postgresql.org/message-id/CAA4eK1%2BT-ETXeRM4DHWzGxBpKafLCp__5bPA_QZfFQp7-0wj4Q%40mail.gmail.com\n> [2] - https://www.postgresql.org/message-id/dc08add3-10a8-738b-983a-191c7406707b%40enterprisedb.com\n>\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Thu, 15 Feb 2024 08:41:59 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "On Thu, 15 Feb 2024 at 08:42, Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Wed, Feb 14, 2024 at 12:58 PM vignesh C <vignesh21@gmail.com> wrote:\n> >\n> > On Wed, 7 Feb 2024 at 16:27, vignesh C <vignesh21@gmail.com> wrote:\n> > >\n> > > I was able to reproduce the issue consistently with the changes shared\n> > > by Tom Lane at [1].\n> > > I have made changes to change ALTER SUBSCRIPTION to DROP+CREATE\n> > > SUBSCRIPTION and verified that the test has passed consistently for\n> > > >50 runs that I ran. Also the test execution time increased for this\n> > > case is very negligibly:\n> > > Without patch: 7.991 seconds\n> > > With test change patch: 8.121 seconds\n> > >\n> > > The test changes for the same are attached.\n> >\n> > Alternative, this could also be fixed like the changes proposed by\n> > Amit at [1]. In this case we ignore publications that are not found\n> > for the purpose of computing RelSyncEntry attributes. We won't mark\n> > such an entry as valid till all the publications are loaded without\n> > anything missing. This means we won't publish operations on tables\n> > corresponding to that publication till we found such a publication and\n> > that seems okay.\n> >\n> > Tomas had raised a performance issue forcing us to reload it for every\n> > replicated change/row in case the publications are invalid at [2].\n> >\n>\n> Did you measure the performance impact? I think it should impact the\n> performance only when there is a dropped/non-existent publication as\n> per the subscription definition.\n\nThe performance was almost similar in this case:\nWithout patch: 7.991 seconds\nWith skip_not_exist_publication option patch: 7.996 seconds\n\n> Also, in the same email[2], Tomas\n> raised another concern that in such cases it is better to break the\n> replication.\n\nI will handle this in the next version\n\n> >\n> How\n> > about keeping the default option as it is and providing a new option\n> > skip_not_exist_publication while creating/altering a subscription. In\n> > this case if skip_not_exist_publication is specified we will ignore\n> > the case if publication is not present and publications will be kept\n> > in invalid and get validated later.\n> >\n>\n> I don't know if this deserves a separate option or not but I think it\n> is better to discuss this in a separate thread.\n\nI will start a separate thread for this.\n\n> To resolve the BF\n> failure, I still feel, we should just recreate the subscription. This\n> is a pre-existing problem and we can track it via a separate patch\n> with a test case targetting such failures.\n\n+1 for going with recreation of the subscription, the changes for this\nare available at [1].\n[1] - https://www.postgresql.org/message-id/CALDaNm1hLZW4H4Z61swK6WPW6pcNcjzXqw%3D6NqG7e-RMtkFaZA%40mail.gmail.com\n\nRegards,\nVignesh\n\n\n",
"msg_date": "Thu, 15 Feb 2024 10:46:11 +0530",
"msg_from": "vignesh C <vignesh21@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "On Wed, Feb 14, 2024 at 03:31:16PM +0000, Bertrand Drouvot wrote:\n> On Sat, Feb 10, 2024 at 05:02:27PM -0800, Noah Misch wrote:\n> > The 035_standby_logical_decoding.pl hang is\n> > a race condition arising from an event sequence like this:\n> > \n> > - Test script sends CREATE SUBSCRIPTION to subscriber, which loses the CPU.\n> > - Test script calls pg_log_standby_snapshot() on primary. Emits XLOG_RUNNING_XACTS.\n> > - checkpoint_timeout makes a primary checkpoint finish. Emits XLOG_RUNNING_XACTS.\n> > - bgwriter executes LOG_SNAPSHOT_INTERVAL_MS logic. Emits XLOG_RUNNING_XACTS.\n> > - CREATE SUBSCRIPTION wakes up and sends CREATE_REPLICATION_SLOT to standby.\n> > \n> > Other test code already has a solution for this, so the attached patches add a\n> > timeout and copy the existing solution. I'm also attaching the hack that\n> > makes it 100% reproducible.\n\n> I did a few tests and confirm that the proposed solution fixes the corner case.\n\nThanks for reviewing.\n\n> What about creating a sub, say wait_for_restart_lsn_calculation() in Cluster.pm\n> and then make use of it in create_logical_slot_on_standby() and above? (something\n> like wait_for_restart_lsn_calculation-v1.patch attached).\n\nWaiting for restart_lsn is just a prerequisite for calling\npg_log_standby_snapshot(), so I wouldn't separate those two. If we're\nextracting a sub, I would move the pg_log_standby_snapshot() call into the sub\nand make the API like one of these:\n\n $standby->wait_for_subscription_starting_point($primary, $slot_name);\n $primary->log_standby_snapshot($standby, $slot_name);\n\nWould you like to finish the patch in such a way?\n\n\n",
"msg_date": "Thu, 15 Feb 2024 12:48:16 -0800",
"msg_from": "Noah Misch <noah@leadboat.com>",
"msg_from_op": false,
"msg_subject": "Re: 035_standby_logical_decoding unbounded hang"
},
{
"msg_contents": "Hi,\n\nOn Thu, Feb 15, 2024 at 12:48:16PM -0800, Noah Misch wrote:\n> On Wed, Feb 14, 2024 at 03:31:16PM +0000, Bertrand Drouvot wrote:\n> > What about creating a sub, say wait_for_restart_lsn_calculation() in Cluster.pm\n> > and then make use of it in create_logical_slot_on_standby() and above? (something\n> > like wait_for_restart_lsn_calculation-v1.patch attached).\n> \n> Waiting for restart_lsn is just a prerequisite for calling\n> pg_log_standby_snapshot(), so I wouldn't separate those two.\n\nYeah, makes sense.\n\n> If we're\n> extracting a sub, I would move the pg_log_standby_snapshot() call into the sub\n> and make the API like one of these:\n> \n> $standby->wait_for_subscription_starting_point($primary, $slot_name);\n> $primary->log_standby_snapshot($standby, $slot_name);\n> \n> Would you like to finish the patch in such a way?\n\nSure, please find attached standby-slot-test-2-race-v2.patch doing so. I used\nlog_standby_snapshot() as it seems more generic to me.\n\nRegards,\n\n-- \nBertrand Drouvot\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Fri, 16 Feb 2024 06:37:38 +0000",
"msg_from": "Bertrand Drouvot <bertranddrouvot.pg@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: 035_standby_logical_decoding unbounded hang"
},
{
"msg_contents": "On Thu, Feb 15, 2024 at 10:46 AM vignesh C <vignesh21@gmail.com> wrote:\n>\n> On Thu, 15 Feb 2024 at 08:42, Amit Kapila <amit.kapila16@gmail.com> wrote:\n> >\n>\n> > To resolve the BF\n> > failure, I still feel, we should just recreate the subscription. This\n> > is a pre-existing problem and we can track it via a separate patch\n> > with a test case targetting such failures.\n>\n> +1 for going with recreation of the subscription, the changes for this\n> are available at [1].\n> [1] - https://www.postgresql.org/message-id/CALDaNm1hLZW4H4Z61swK6WPW6pcNcjzXqw%3D6NqG7e-RMtkFaZA%40mail.gmail.com\n>\n\nTom, and others, does anyone still object to going ahead with an idea\nby just changing the test to recreate the subscription to silence BF\nfailures for this test?\n\nNote that Vignesh has already started a thread [1] to add an option\n(or otherwise) to ignore publication lookup failures.\n\n[1] - https://www.postgresql.org/message-id/CALDaNm0-n8FGAorM%2BbTxkzn%2BAOUyx5%3DL_XmnvOP6T24%2B-NcBKg%40mail.gmail.com\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Mon, 19 Feb 2024 14:19:54 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "On Fri, Feb 16, 2024 at 06:37:38AM +0000, Bertrand Drouvot wrote:\n> On Thu, Feb 15, 2024 at 12:48:16PM -0800, Noah Misch wrote:\n> > On Wed, Feb 14, 2024 at 03:31:16PM +0000, Bertrand Drouvot wrote:\n> > > What about creating a sub, say wait_for_restart_lsn_calculation() in Cluster.pm\n> > > and then make use of it in create_logical_slot_on_standby() and above? (something\n> > > like wait_for_restart_lsn_calculation-v1.patch attached).\n> > \n> > Waiting for restart_lsn is just a prerequisite for calling\n> > pg_log_standby_snapshot(), so I wouldn't separate those two.\n> \n> Yeah, makes sense.\n> \n> > If we're\n> > extracting a sub, I would move the pg_log_standby_snapshot() call into the sub\n> > and make the API like one of these:\n> > \n> > $standby->wait_for_subscription_starting_point($primary, $slot_name);\n> > $primary->log_standby_snapshot($standby, $slot_name);\n> > \n> > Would you like to finish the patch in such a way?\n> \n> Sure, please find attached standby-slot-test-2-race-v2.patch doing so. I used\n> log_standby_snapshot() as it seems more generic to me.\n\nThanks. Pushed at commit 0e16281.\n\n\n",
"msg_date": "Mon, 19 Feb 2024 15:09:30 -0800",
"msg_from": "Noah Misch <noah@leadboat.com>",
"msg_from_op": false,
"msg_subject": "Re: 035_standby_logical_decoding unbounded hang"
},
{
"msg_contents": "On Mon, Feb 19, 2024 at 2:19 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Thu, Feb 15, 2024 at 10:46 AM vignesh C <vignesh21@gmail.com> wrote:\n> >\n> > On Thu, 15 Feb 2024 at 08:42, Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > >\n> >\n> > > To resolve the BF\n> > > failure, I still feel, we should just recreate the subscription. This\n> > > is a pre-existing problem and we can track it via a separate patch\n> > > with a test case targetting such failures.\n> >\n> > +1 for going with recreation of the subscription, the changes for this\n> > are available at [1].\n> > [1] - https://www.postgresql.org/message-id/CALDaNm1hLZW4H4Z61swK6WPW6pcNcjzXqw%3D6NqG7e-RMtkFaZA%40mail.gmail.com\n> >\n>\n> Tom, and others, does anyone still object to going ahead with an idea\n> by just changing the test to recreate the subscription to silence BF\n> failures for this test?\n>\n\nSeeing no objections, I have pushed the required test changes to silence the BF.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Fri, 23 Feb 2024 09:17:51 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "Amit Kapila <amit.kapila16@gmail.com> writes:\n> Seeing no objections, I have pushed the required test changes to silence the BF.\n\nThe farm is still unhappy in the v16 branch.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Fri, 23 Feb 2024 16:01:04 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": true,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "On Sat, Feb 24, 2024 at 2:31 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Amit Kapila <amit.kapila16@gmail.com> writes:\n> > Seeing no objections, I have pushed the required test changes to silence the BF.\n>\n> The farm is still unhappy in the v16 branch.\n>\n\nAs this feature and tests were introduced in 15, I think we should\nbackpatch till 15. I'll do that early next week unless you or someone\nelse thinks otherwise.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Sat, 24 Feb 2024 07:05:21 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Why is subscription/t/031_column_list.pl failing so much?"
},
{
"msg_contents": "\n\n> On 20 Feb 2024, at 04:09, Noah Misch <noah@leadboat.com> wrote:\n> \n\nI’m not sure if it is connected, but so far many patches in CFbot keep hanging in this test. For example [0].\n\nI haven’t done root cause analysis yet, but hangs may be related to this thread. Maybe someone more familiar with similar issues could take a look there?\n\nThanks!\n\n\nBest regards, Andrey Borodin.\n\n[0] https://cirrus-ci.com/task/5911176840740864?logs=check_world#L292 \n\n",
"msg_date": "Thu, 7 Mar 2024 14:46:55 +0500",
"msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>",
"msg_from_op": false,
"msg_subject": "Re: 035_standby_logical_decoding unbounded hang"
},
{
"msg_contents": "On Thu, Mar 07, 2024 at 02:46:55PM +0500, Andrey M. Borodin wrote:\n> I’m not sure if it is connected, but so far many patches in CFbot keep hanging in this test. For example [0].\n\n> [0] https://cirrus-ci.com/task/5911176840740864?logs=check_world#L292 \n\nRelevant part:\n\n[22:03:10.292] stderr:\n[22:03:10.292] # poll_query_until timed out executing this query:\n[22:03:10.292] # SELECT (SELECT catalog_xmin::text::int - 770 from pg_catalog.pg_replication_slots where slot_name = 'injection_activeslot') > 0\n[22:03:10.292] # expecting this output:\n[22:03:10.292] # t\n[22:03:10.292] # last actual query output:\n[22:03:10.292] # f\n[22:03:10.292] # with stderr:\n[22:03:10.292] # Tests were run but no plan was declared and done_testing() was not seen.\n[22:03:10.292] # Looks like your test exited with 255 just after 57.\n\nThe injection_activeslot test got added after $SUBJECT, in 08a52ab151\n(2024-03-06). It's now reverted in 65db0cfb4c (2024-03-07).\n\n\n",
"msg_date": "Thu, 7 Mar 2024 09:28:59 -0800",
"msg_from": "Noah Misch <noah@leadboat.com>",
"msg_from_op": false,
"msg_subject": "Re: 035_standby_logical_decoding unbounded hang"
}
] |
[
{
"msg_contents": "Hi.\nI previously did some work in COPY FROM save error information to a table.\nstill based on this suggestion:\nhttps://www.postgresql.org/message-id/752672.1699474336%40sss.pgh.pa.us\nNow I refactored it.\n\nthe syntax:\nON_ERROR 'table', TABLE 'error_saving_tbl'\n\nif ON_ERROR is not specified with 'table', TABLE is specified, then error.\nif ON_ERROR is specified with 'table', TABLE is not specified or\nerror_saving_tbl does not exist, then error.\n\nIn BeginCopyFrom, we check the data definition of error_saving_table,\nwe also check if the user has INSERT privilege to error_saving_table\n(all the columns).\nWe also did a preliminary check of the lock condition of error_saving_table.\n\nif it does not meet these conditions, we quickly error out.\nerror_saving_table will be the same schema as the copy from table.\n\nBecause \"table\" is a keyword, I have to add the following changes to gram.y.\n--- a/src/backend/parser/gram.y\n+++ b/src/backend/parser/gram.y\n@@ -3420,6 +3420,10 @@ copy_opt_item:\n {\n $$ = makeDefElem(\"null\", (Node *) makeString($3), @1);\n }\n+ | TABLE opt_as Sconst\n+ {\n+ $$ = makeDefElem(\"table\", (Node *) makeString($3), @1);\n+ }\n\nsince \"table\" is already a keyword, so there is no influence on the\nparsing speed?\n\ndemo:\n\ncreate table err_tbl(\n userid oid, -- the user oid while copy generated this entry\n copy_tbl oid, --copy table\n filename text,\n lineno int8,\n line text,\n colname text,\n raw_field_value text,\n err_message text,\n err_detail text,\n errorcode text\n);\ncreate table t_copy_tbl(a int, b int, c int);\nCOPY t_copy_tbl FROM STDIN WITH (delimiter ',', on_error 'table',\ntable err_tbl);\n1,2,a\n\\.\n\ntable err_tbl \\gx\n-[ RECORD 1 ]---+-------------------------------------------\nuserid | 10\ncopy_tbl | 17920\nfilename | STDIN\nlineno | 1\nline | 1,2,a\ncolname | c\nraw_field_value | a\nerr_message | invalid input syntax for type integer: \"a\"\nerr_detail |\nerrorcode | 22P02",
"msg_date": "Sat, 3 Feb 2024 14:22:34 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": true,
"msg_subject": "on_error table, saving error info to a table"
},
{
"msg_contents": "Thanks for the patch!\n\nI was not able to understand why we need a special error table for COPY?\nCan't we just log it in a new log error file for COPY in a proper format?\nLike\nusing table approach, PG would be unnecessarily be utilising its resources\nlike\nextra CPU to format the data in pages to store in its table format, writing\nand\nkeeping the table in its store (which may or may not be required), the user\nwould be required to make sure it creates the error table with proper\ncolumns\nto be used in COPY, etc..\n\n\nMeanwhile, please find some quick review comments:-\n\n1) Patch needs re-base.\n\n2) If the columns of the error table are fixed, then why not create it\ninternally using\nsome function or something instead of making the user create the table\ncorrectly\nwith all the columns?\n\n3) I think, error messages can be improved, which looks big to me.\n\n4) I think no need of below pstrdup, As CStringGetTextDatum creates a text\ncopy for\nthe same:-\nerr_code =\npstrdup(unpack_sql_state(cstate->escontext->error_data->sqlerrcode));\n\nt_values[9] = CStringGetTextDatum(err_code);\n\n5) Should 'on_error_rel' as not NULL be checked along with below, as I can\nsee it is\npassed as NULL from two locations?\n+ if (cstate->opts.on_error == COPY_ON_ERROR_TABLE)\n+ {\n\n6) Below declarations can be shifted to the if block, where they are used.\nInstead of\nkeeping them as global in function?\n+ HeapTuple on_error_tup;\n+ TupleDesc on_error_tupDesc;\n\n+ if (cstate->opts.on_error == COPY_ON_ERROR_TABLE)\n+ {\n\n7) Below comment going beyond 80 char width:-\n* if on_error is specified with 'table', then on_error_rel is the error\nsaving table\n\n8) Need space after 'false'\nerr_detail ? false: true;\n\n9) Below call can fit in a single line. No need to keep the 2nd and 3rd\nparameter in\nnextlines.\n+ on_error_tup = heap_form_tuple(on_error_tupDesc,\n+ t_values,\n+ t_isnull);\n\n10) Variable declarations Tab Spacing issue at multiple places.\n\n11) Comments in the patch are not matched to PG comment style.\n\n\nKindly note I have not tested the patch properly yet. Only checked it with\na positive test\ncase. As I will wait for a conclusion on my opinion of the proposed patch.\n\n\nRegards,\nNishant Sharma.\nEnterpriseDB, Pune.\n\n\nOn Sat, Feb 3, 2024 at 11:52 AM jian he <jian.universality@gmail.com> wrote:\n\n> Hi.\n> I previously did some work in COPY FROM save error information to a table.\n> still based on this suggestion:\n> https://www.postgresql.org/message-id/752672.1699474336%40sss.pgh.pa.us\n> Now I refactored it.\n>\n> the syntax:\n> ON_ERROR 'table', TABLE 'error_saving_tbl'\n>\n> if ON_ERROR is not specified with 'table', TABLE is specified, then error.\n> if ON_ERROR is specified with 'table', TABLE is not specified or\n> error_saving_tbl does not exist, then error.\n>\n> In BeginCopyFrom, we check the data definition of error_saving_table,\n> we also check if the user has INSERT privilege to error_saving_table\n> (all the columns).\n> We also did a preliminary check of the lock condition of\n> error_saving_table.\n>\n> if it does not meet these conditions, we quickly error out.\n> error_saving_table will be the same schema as the copy from table.\n>\n> Because \"table\" is a keyword, I have to add the following changes to\n> gram.y.\n> --- a/src/backend/parser/gram.y\n> +++ b/src/backend/parser/gram.y\n> @@ -3420,6 +3420,10 @@ copy_opt_item:\n> {\n> $$ = makeDefElem(\"null\", (Node *) makeString($3), @1);\n> }\n> + | TABLE opt_as Sconst\n> + {\n> + $$ = makeDefElem(\"table\", (Node *) makeString($3), @1);\n> + }\n>\n> since \"table\" is already a keyword, so there is no influence on the\n> parsing speed?\n>\n> demo:\n>\n> create table err_tbl(\n> userid oid, -- the user oid while copy generated this entry\n> copy_tbl oid, --copy table\n> filename text,\n> lineno int8,\n> line text,\n> colname text,\n> raw_field_value text,\n> err_message text,\n> err_detail text,\n> errorcode text\n> );\n> create table t_copy_tbl(a int, b int, c int);\n> COPY t_copy_tbl FROM STDIN WITH (delimiter ',', on_error 'table',\n> table err_tbl);\n> 1,2,a\n> \\.\n>\n> table err_tbl \\gx\n> -[ RECORD 1 ]---+-------------------------------------------\n> userid | 10\n> copy_tbl | 17920\n> filename | STDIN\n> lineno | 1\n> line | 1,2,a\n> colname | c\n> raw_field_value | a\n> err_message | invalid input syntax for type integer: \"a\"\n> err_detail |\n> errorcode | 22P02\n>\n\nThanks for the patch!I was not able to understand why we need a special error table for COPY?Can't we just log it in a new log error file for COPY in a proper format? Likeusing table approach, PG would be unnecessarily be utilising its resources likeextra CPU to format the data in pages to store in its table format, writing andkeeping the table in its store (which may or may not be required), the userwould be required to make sure it creates the error table with proper columnsto be used in COPY, etc..Meanwhile, please find some quick review comments:-1) Patch needs re-base.2) If the columns of the error table are fixed, then why not create it internally usingsome function or something instead of making the user create the table correctlywith all the columns?3) I think, error messages can be improved, which looks big to me.4) I think no need of below pstrdup, As CStringGetTextDatum creates a text copy forthe same:-err_code = pstrdup(unpack_sql_state(cstate->escontext->error_data->sqlerrcode));t_values[9] = CStringGetTextDatum(err_code);5) Should 'on_error_rel' as not NULL be checked along with below, as I can see it ispassed as NULL from two locations?+ if (cstate->opts.on_error == COPY_ON_ERROR_TABLE)+ {6) Below declarations can be shifted to the if block, where they are used. Instead ofkeeping them as global in function?+ HeapTuple on_error_tup;+ TupleDesc on_error_tupDesc;+ if (cstate->opts.on_error == COPY_ON_ERROR_TABLE)+ {7) Below comment going beyond 80 char width:-* if on_error is specified with 'table', then on_error_rel is the error saving table8) Need space after 'false'err_detail ? false: true;9) Below call can fit in a single line. No need to keep the 2nd and 3rd parameter innextlines.+ on_error_tup = heap_form_tuple(on_error_tupDesc,+ t_values,+ t_isnull);10) Variable declarations Tab Spacing issue at multiple places.11) Comments in the patch are not matched to PG comment style.Kindly note I have not tested the patch properly yet. Only checked it with a positive testcase. As I will wait for a conclusion on my opinion of the proposed patch.Regards,Nishant Sharma.EnterpriseDB, Pune.On Sat, Feb 3, 2024 at 11:52 AM jian he <jian.universality@gmail.com> wrote:Hi.\nI previously did some work in COPY FROM save error information to a table.\nstill based on this suggestion:\nhttps://www.postgresql.org/message-id/752672.1699474336%40sss.pgh.pa.us\nNow I refactored it.\n\nthe syntax:\nON_ERROR 'table', TABLE 'error_saving_tbl'\n\nif ON_ERROR is not specified with 'table', TABLE is specified, then error.\nif ON_ERROR is specified with 'table', TABLE is not specified or\nerror_saving_tbl does not exist, then error.\n\nIn BeginCopyFrom, we check the data definition of error_saving_table,\nwe also check if the user has INSERT privilege to error_saving_table\n(all the columns).\nWe also did a preliminary check of the lock condition of error_saving_table.\n\nif it does not meet these conditions, we quickly error out.\nerror_saving_table will be the same schema as the copy from table.\n\nBecause \"table\" is a keyword, I have to add the following changes to gram.y.\n--- a/src/backend/parser/gram.y\n+++ b/src/backend/parser/gram.y\n@@ -3420,6 +3420,10 @@ copy_opt_item:\n {\n $$ = makeDefElem(\"null\", (Node *) makeString($3), @1);\n }\n+ | TABLE opt_as Sconst\n+ {\n+ $$ = makeDefElem(\"table\", (Node *) makeString($3), @1);\n+ }\n\nsince \"table\" is already a keyword, so there is no influence on the\nparsing speed?\n\ndemo:\n\ncreate table err_tbl(\n userid oid, -- the user oid while copy generated this entry\n copy_tbl oid, --copy table\n filename text,\n lineno int8,\n line text,\n colname text,\n raw_field_value text,\n err_message text,\n err_detail text,\n errorcode text\n);\ncreate table t_copy_tbl(a int, b int, c int);\nCOPY t_copy_tbl FROM STDIN WITH (delimiter ',', on_error 'table',\ntable err_tbl);\n1,2,a\n\\.\n\ntable err_tbl \\gx\n-[ RECORD 1 ]---+-------------------------------------------\nuserid | 10\ncopy_tbl | 17920\nfilename | STDIN\nlineno | 1\nline | 1,2,a\ncolname | c\nraw_field_value | a\nerr_message | invalid input syntax for type integer: \"a\"\nerr_detail |\nerrorcode | 22P02",
"msg_date": "Mon, 15 Jul 2024 11:12:40 +0530",
"msg_from": "Nishant Sharma <nishant.sharma@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: on_error table, saving error info to a table"
},
{
"msg_contents": "On Mon, Jul 15, 2024 at 1:42 PM Nishant Sharma\n<nishant.sharma@enterprisedb.com> wrote:\n>\n> Thanks for the patch!\n>\n> I was not able to understand why we need a special error table for COPY?\n> Can't we just log it in a new log error file for COPY in a proper format? Like\n> using table approach, PG would be unnecessarily be utilising its resources like\n> extra CPU to format the data in pages to store in its table format, writing and\n> keeping the table in its store (which may or may not be required), the user\n> would be required to make sure it creates the error table with proper columns\n> to be used in COPY, etc..\n>\n>\n> Meanwhile, please find some quick review comments:-\n>\n> 1) Patch needs re-base.\n>\n> 2) If the columns of the error table are fixed, then why not create it internally using\n> some function or something instead of making the user create the table correctly\n> with all the columns?\n\nI'll think about it more.\npreviously, i tried to use SPI to create tables, but at that time, i\nthought that's kind of excessive.\nyou need to create the table, check whether the table name is unique,\ncheck the privilege.\nnow we quickly error out if the error saving table definition does not\nmeet. I guess that's less work to do.\n\n\n> 3) I think, error messages can be improved, which looks big to me.\n>\n> 4) I think no need of below pstrdup, As CStringGetTextDatum creates a text copy for\n> the same:-\n> err_code = pstrdup(unpack_sql_state(cstate->escontext->error_data->sqlerrcode));\n>\n> t_values[9] = CStringGetTextDatum(err_code);\n>\n> 5) Should 'on_error_rel' as not NULL be checked along with below, as I can see it is\n> passed as NULL from two locations?\n> + if (cstate->opts.on_error == COPY_ON_ERROR_TABLE)\n> + {\n>\n> 6) Below declarations can be shifted to the if block, where they are used. Instead of\n> keeping them as global in function?\n> + HeapTuple on_error_tup;\n> + TupleDesc on_error_tupDesc;\n>\n> + if (cstate->opts.on_error == COPY_ON_ERROR_TABLE)\n> + {\n>\n> 7) Below comment going beyond 80 char width:-\n> * if on_error is specified with 'table', then on_error_rel is the error saving table\n>\n> 8) Need space after 'false'\n> err_detail ? false: true;\n>\n> 9) Below call can fit in a single line. No need to keep the 2nd and 3rd parameter in\n> nextlines.\n> + on_error_tup = heap_form_tuple(on_error_tupDesc,\n> + t_values,\n> + t_isnull);\n>\n> 10) Variable declarations Tab Spacing issue at multiple places.\n>\n> 11) Comments in the patch are not matched to PG comment style.\n>\n>\n> Kindly note I have not tested the patch properly yet. Only checked it with a positive test\n> case. As I will wait for a conclusion on my opinion of the proposed patch.\n>\nalmost all these issues have been addressed.\nThe error messages are still not so good. I need to polish it.",
"msg_date": "Tue, 20 Aug 2024 08:00:00 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: on_error table, saving error info to a table"
}
] |
[
{
"msg_contents": "Hello,\r\n\r\n\r\n I found an issue while using the latest version of PG15 (8fa4a1ac61189efffb8b851ee77e1bc87360c445).\r\n\r\n This issue is related to Megre into and other concurrent statements being written. \r\n I obtained different results in Oracle and PG using the same statement below.\r\n Based on my personal judgment, the result set of this statement in pg is abnormal. \r\n Can you provide me with relevant suggestions or modification methods? \r\n I can try to make relevant modifications and repairs in the PG code.\r\n\r\n\r\n Looking forward to your reply.\r\n thanks",
"msg_date": "Sun, 4 Feb 2024 14:42:52 +0800",
"msg_from": "\"=?ISO-8859-1?B?endq?=\" <sxzwj@vip.qq.com>",
"msg_from_op": true,
"msg_subject": "bug report: some issues about\n pg_15_stable(8fa4a1ac61189efffb8b851ee77e1bc87360c445)"
},
{
"msg_contents": "On Sun, 4 Feb 2024 at 18:19, zwj <sxzwj@vip.qq.com> wrote:\n>\n> I found an issue while using the latest version of PG15 (8fa4a1ac61189efffb8b851ee77e1bc87360c445).\n>\n> This issue is related to Megre into and other concurrent statements being written.\n> I obtained different results in Oracle and PG using the same statement below.\n> Based on my personal judgment, the result set of this statement in pg is abnormal.\n>\n\nI would say that the Postgres result is correct here. The merge update\naction would have updated the row with id=2, setting year=30, but\nsince there is a concurrent update, changing that id to 5, it waits to\nsee if that transaction commits. Once it does, the id no longer\nmatches, and merge update action is aborted, and the \"not matched\"\naction is performed instead. That's consistent with the result that\nyou'd get if you performed the 2 transactions serially, doing the\nupdate first then the merge.\n\nOracle, on the other hand, proceeds with the merge update action,\nafter the other transaction commits, even though the row being updated\nno longer matches the join condition. Not only does that seem to be\nincorrect, it's inconsistent with what both Oracle and Postgres do if\nyou replace the merge command with the equivalent standalone update\nfor that row: \"update mergeinto_0023_tb01 set year = 30 where id = 2\"\nin the second session. So I'd say that this is an Oracle bug.\n\nRegards,\nDean\n\n\n",
"msg_date": "Mon, 5 Feb 2024 11:51:25 +0000",
"msg_from": "Dean Rasheed <dean.a.rasheed@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: bug report: some issues about\n pg_15_stable(8fa4a1ac61189efffb8b851ee77e1bc87360c445)"
}
] |
[
{
"msg_contents": "Hackers,\n\nAttached is a patch to add a new function, `parse_type()`. It parses a type string and returns a record with the typid and typmod for the type, or raises an error if the type is invalid. It’s effectively a thin layer over the parser’s parseTypeString() function.\n\nThe purpose of this function is to allow uses to resolve any type name, including aliases, to its formal name as rendered by, for example, pg_dump. An example:\n\ndavid=# WITH s(s) AS (\n SELECT * FROM unnest(ARRAY[\n 'timestamp(4)',\n 'interval(0)',\n 'interval second(0)',\n 'timestamptz',\n 'timestamptz(6)',\n 'varchar',\n 'varchar(128)' \n ]) \n),\np(type, typid, typmod) AS (\n SELECT s, ((parse_type(s)).*)\n FROM s \n) \nSELECT type, format_type(typid, typmod) FROM p;\n type | format_type \n--------------------+--------------------------------\n timestamp(4) | timestamp(4) without time zone\n interval(0) | interval(0)\n interval second(0) | interval second(0)\n timestamptz | timestamp with time zone\n timestamptz(6) | timestamp(6) with time zone\n varchar | character varying\n varchar(128) | character varying(128)\n(7 rows)\n\n\nThe use case leading to this patch was pgTAP column data type assertions. pgTAP traditionally required full type names for testing data types, but recently added support for aliases. This broke for some types, because it was difficult to extract the typmod correctly, and even when we did, it failed for types such as `interval second(0)`, where `second (0)` is the typmod, and there was no sensible way to access the bit mask to generate the proper typmod to pass to `format_type()`.\n\nErik Wienhold wrote this function to solve the problem, and I volunteered to submit a patch.\n\nPotential issues and questions for this patch:\n\n* Is `parse_type()` the right name to use? I can see arguments for `parse_type_string()`, `pg_parse_type()`, and `pg_parse_type_string()`. Whatever the consensus is works for me.\n\n* The function returns a record, which is a little fussy. I could see adding a `format_type_string()` function that just contains `SELECT format_type(p.typmod, p.typid) FROM parse_type($1) p` and returns the formatted type. But I think it might also be useful to have access to the typmod and typid directly via this method, since they’re already exposed as `format_type()`’s arguments.\n\n* Is format_type.c the right home for the function? I put it there because I closely associate it with format_type(), but happy to move it to a more appropriate location.\n\n* I tried to link to `format_type` from the docs entry for `parse_type`, and added an ID for the former, but I’m not sure it resolves.\n\nBest,\n\nDavid",
"msg_date": "Sun, 4 Feb 2024 12:51:29 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Patch: Add parse_type Function"
},
{
"msg_contents": "Hi\n\nne 4. 2. 2024 v 18:51 odesílatel David E. Wheeler <david@justatheory.com>\nnapsal:\n\n> Hackers,\n>\n> Attached is a patch to add a new function, `parse_type()`. It parses a\n> type string and returns a record with the typid and typmod for the type, or\n> raises an error if the type is invalid. It’s effectively a thin layer over\n> the parser’s parseTypeString() function.\n>\n> The purpose of this function is to allow uses to resolve any type name,\n> including aliases, to its formal name as rendered by, for example, pg_dump.\n> An example:\n>\n> david=# WITH s(s) AS (\n> SELECT * FROM unnest(ARRAY[\n> 'timestamp(4)',\n> 'interval(0)',\n> 'interval second(0)',\n> 'timestamptz',\n> 'timestamptz(6)',\n> 'varchar',\n> 'varchar(128)'\n> ])\n> ),\n> p(type, typid, typmod) AS (\n> SELECT s, ((parse_type(s)).*)\n> FROM s\n> )\n> SELECT type, format_type(typid, typmod) FROM p;\n> type | format_type\n> --------------------+--------------------------------\n> timestamp(4) | timestamp(4) without time zone\n> interval(0) | interval(0)\n> interval second(0) | interval second(0)\n> timestamptz | timestamp with time zone\n> timestamptz(6) | timestamp(6) with time zone\n> varchar | character varying\n> varchar(128) | character varying(128)\n> (7 rows)\n>\n>\n> The use case leading to this patch was pgTAP column data type assertions.\n> pgTAP traditionally required full type names for testing data types, but\n> recently added support for aliases. This broke for some types, because it\n> was difficult to extract the typmod correctly, and even when we did, it\n> failed for types such as `interval second(0)`, where `second (0)` is the\n> typmod, and there was no sensible way to access the bit mask to generate\n> the proper typmod to pass to `format_type()`.\n>\n> Erik Wienhold wrote this function to solve the problem, and I volunteered\n> to submit a patch.\n>\n> Potential issues and questions for this patch:\n>\n> * Is `parse_type()` the right name to use? I can see arguments for\n> `parse_type_string()`, `pg_parse_type()`, and `pg_parse_type_string()`.\n> Whatever the consensus is works for me.\n>\n\nthere can be an analogy with parse_ident, so parse_type looks ok\n\n\n> * The function returns a record, which is a little fussy. I could see\n> adding a `format_type_string()` function that just contains `SELECT\n> format_type(p.typmod, p.typid) FROM parse_type($1) p` and returns the\n> formatted type. But I think it might also be useful to have access to the\n> typmod and typid directly via this method, since they’re already exposed as\n> `format_type()`’s arguments.\n>\n\nI think so record has sense for this case\n\n\n>\n> * Is format_type.c the right home for the function? I put it there because\n> I closely associate it with format_type(), but happy to move it to a more\n> appropriate location.\n>\n\nyes\n\n\n>\n> * I tried to link to `format_type` from the docs entry for `parse_type`,\n> and added an ID for the former, but I’m not sure it resolves.\n>\n\nI thinks so proposed functionality can be useful\n\nRegards\n\nPavel\n\n\n>\n> Best,\n>\n> David\n>\n>\n\nHine 4. 2. 2024 v 18:51 odesílatel David E. Wheeler <david@justatheory.com> napsal:Hackers,\n\nAttached is a patch to add a new function, `parse_type()`. It parses a type string and returns a record with the typid and typmod for the type, or raises an error if the type is invalid. It’s effectively a thin layer over the parser’s parseTypeString() function.\n\nThe purpose of this function is to allow uses to resolve any type name, including aliases, to its formal name as rendered by, for example, pg_dump. An example:\n\ndavid=# WITH s(s) AS (\n SELECT * FROM unnest(ARRAY[\n 'timestamp(4)',\n 'interval(0)',\n 'interval second(0)',\n 'timestamptz',\n 'timestamptz(6)',\n 'varchar',\n 'varchar(128)' \n ]) \n),\np(type, typid, typmod) AS (\n SELECT s, ((parse_type(s)).*)\n FROM s \n) \nSELECT type, format_type(typid, typmod) FROM p;\n type | format_type \n--------------------+--------------------------------\n timestamp(4) | timestamp(4) without time zone\n interval(0) | interval(0)\n interval second(0) | interval second(0)\n timestamptz | timestamp with time zone\n timestamptz(6) | timestamp(6) with time zone\n varchar | character varying\n varchar(128) | character varying(128)\n(7 rows)\n\n\nThe use case leading to this patch was pgTAP column data type assertions. pgTAP traditionally required full type names for testing data types, but recently added support for aliases. This broke for some types, because it was difficult to extract the typmod correctly, and even when we did, it failed for types such as `interval second(0)`, where `second (0)` is the typmod, and there was no sensible way to access the bit mask to generate the proper typmod to pass to `format_type()`.\n\nErik Wienhold wrote this function to solve the problem, and I volunteered to submit a patch.\n\nPotential issues and questions for this patch:\n\n* Is `parse_type()` the right name to use? I can see arguments for `parse_type_string()`, `pg_parse_type()`, and `pg_parse_type_string()`. Whatever the consensus is works for me.there can be an analogy with parse_ident, so parse_type looks ok \n\n* The function returns a record, which is a little fussy. I could see adding a `format_type_string()` function that just contains `SELECT format_type(p.typmod, p.typid) FROM parse_type($1) p` and returns the formatted type. But I think it might also be useful to have access to the typmod and typid directly via this method, since they’re already exposed as `format_type()`’s arguments.I think so record has sense for this case \n\n* Is format_type.c the right home for the function? I put it there because I closely associate it with format_type(), but happy to move it to a more appropriate location.yes \n\n* I tried to link to `format_type` from the docs entry for `parse_type`, and added an ID for the former, but I’m not sure it resolves.I thinks so proposed functionality can be useful RegardsPavel \n\nBest,\n\nDavid",
"msg_date": "Sun, 4 Feb 2024 19:02:46 +0100",
"msg_from": "Pavel Stehule <pavel.stehule@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 4, 2024, at 13:02, Pavel Stehule <pavel.stehule@gmail.com> wrote:\n\n> I thinks so proposed functionality can be useful \n\nGreat, thank you!\n\nIs that a review? :-)\n\nD\n\n\n\n\n",
"msg_date": "Sun, 4 Feb 2024 13:29:53 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "ne 4. 2. 2024 v 19:30 odesílatel David E. Wheeler <david@justatheory.com>\nnapsal:\n\n> On Feb 4, 2024, at 13:02, Pavel Stehule <pavel.stehule@gmail.com> wrote:\n>\n> > I thinks so proposed functionality can be useful\n>\n> Great, thank you!\n>\n> Is that a review? :-)\n>\n\nnot yet, but I'll do it\n\nPavel\n\n\n\n\n>\n> D\n>\n>\n>\n\nne 4. 2. 2024 v 19:30 odesílatel David E. Wheeler <david@justatheory.com> napsal:On Feb 4, 2024, at 13:02, Pavel Stehule <pavel.stehule@gmail.com> wrote:\n\n> I thinks so proposed functionality can be useful \n\nGreat, thank you!\n\nIs that a review? :-)not yet, but I'll do itPavel \n\nD",
"msg_date": "Sun, 4 Feb 2024 19:52:34 +0100",
"msg_from": "Pavel Stehule <pavel.stehule@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 4, 2024, at 13:52, Pavel Stehule <pavel.stehule@gmail.com> wrote:\n\n> not yet, but I'll do it\n\nNice, thank you. I put it into the Commitfest.\n\n https://commitfest.postgresql.org/47/4807/\n\nBest,\n\nDavid\n\n\n\n",
"msg_date": "Sun, 4 Feb 2024 14:07:25 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "Hi David,\nThanks for the patch.\n\nOn 04.02.24 18:51, David E. Wheeler wrote:\n> Hackers,\n>\n> Attached is a patch to add a new function, `parse_type()`. It parses a type string and returns a record with the typid and typmod for the type, or raises an error if the type is invalid. It’s effectively a thin layer over the parser’s parseTypeString() function.\n>\n> The purpose of this function is to allow uses to resolve any type name, including aliases, to its formal name as rendered by, for example, pg_dump. An example:\n>\n> david=# WITH s(s) AS (\n> SELECT * FROM unnest(ARRAY[\n> 'timestamp(4)',\n> 'interval(0)',\n> 'interval second(0)',\n> 'timestamptz',\n> 'timestamptz(6)',\n> 'varchar',\n> 'varchar(128)' \n> ]) \n> ),\n> p(type, typid, typmod) AS (\n> SELECT s, ((parse_type(s)).*)\n> FROM s \n> ) \n> SELECT type, format_type(typid, typmod) FROM p;\n> type | format_type \n> --------------------+--------------------------------\n> timestamp(4) | timestamp(4) without time zone\n> interval(0) | interval(0)\n> interval second(0) | interval second(0)\n> timestamptz | timestamp with time zone\n> timestamptz(6) | timestamp(6) with time zone\n> varchar | character varying\n> varchar(128) | character varying(128)\n> (7 rows)\n>\n>\n> The use case leading to this patch was pgTAP column data type assertions. pgTAP traditionally required full type names for testing data types, but recently added support for aliases. This broke for some types, because it was difficult to extract the typmod correctly, and even when we did, it failed for types such as `interval second(0)`, where `second (0)` is the typmod, and there was no sensible way to access the bit mask to generate the proper typmod to pass to `format_type()`.\n>\n> Erik Wienhold wrote this function to solve the problem, and I volunteered to submit a patch.\n>\n> Potential issues and questions for this patch:\n>\n> * Is `parse_type()` the right name to use? I can see arguments for `parse_type_string()`, `pg_parse_type()`, and `pg_parse_type_string()`. Whatever the consensus is works for me.\n>\n> * The function returns a record, which is a little fussy. I could see adding a `format_type_string()` function that just contains `SELECT format_type(p.typmod, p.typid) FROM parse_type($1) p` and returns the formatted type. But I think it might also be useful to have access to the typmod and typid directly via this method, since they’re already exposed as `format_type()`’s arguments.\n>\n> * Is format_type.c the right home for the function? I put it there because I closely associate it with format_type(), but happy to move it to a more appropriate location.\n>\n> * I tried to link to `format_type` from the docs entry for `parse_type`, and added an ID for the former, but I’m not sure it resolves.\n>\n> Best,\n>\n> David\n>\nThe patch applies cleanly\n\nChecking patch doc/src/sgml/func.sgml...\nChecking patch src/backend/utils/adt/format_type.c...\nChecking patch src/include/catalog/pg_proc.dat...\nChecking patch src/include/utils/builtins.h...\nChecking patch src/test/regress/expected/create_type.out...\nChecking patch src/test/regress/sql/create_type.sql...\nApplied patch doc/src/sgml/func.sgml cleanly.\nApplied patch src/backend/utils/adt/format_type.c cleanly.\nApplied patch src/include/catalog/pg_proc.dat cleanly.\nApplied patch src/include/utils/builtins.h cleanly.\nApplied patch src/test/regress/expected/create_type.out cleanly.\nApplied patch src/test/regress/sql/create_type.sql cleanly.\n\nThe docs render just fine and all tests pass (check and check-world).\n\nThere are a few issues though:\n\n1) The function causes a crash when called with a NULL parameter:\n\nSELECT * FROM parse_type(NULL);\nserver closed the connection unexpectedly\n This probably means the server terminated abnormally\n before or while processing the request.\nThe connection to the server was lost. Attempting reset: Failed.\nThe connection to the server was lost. Attempting reset: Failed.\n\nYou have to check it in the beginning of function and either return an\nerror message or just NULL, e.g\n\n if (PG_ARGISNULL(0))\n PG_RETURN_NULL();\n\n2) Add a function call with NULL in the regression tests\n\nSELECT * FROM parse_type(NULL);\n\n3) Add the expected behaviour of calling the function with NULL in the\ndocs (error message or null)\n\n4) The name of the returned columns is repeated in the docs\n> Returns a record with two fields, <parameter>typid</parameter> and\n<parameter>typid</parameter>\n\n-- \nJim\n\n\n\n",
"msg_date": "Mon, 5 Feb 2024 14:02:07 +0100",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 5, 2024, at 08:02, Jim Jones <jim.jones@uni-muenster.de> wrote:\n\n> There are a few issues though:\n\nExcellent, thank you very much! Updated patch attached.\n\nBest,\n\nDavid",
"msg_date": "Mon, 5 Feb 2024 09:10:22 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "Jim Jones <jim.jones@uni-muenster.de> writes:\n\n> 1) The function causes a crash when called with a NULL parameter:\n>\n> SELECT * FROM parse_type(NULL);\n> server closed the connection unexpectedly\n> This probably means the server terminated abnormally\n> before or while processing the request.\n> The connection to the server was lost. Attempting reset: Failed.\n> The connection to the server was lost. Attempting reset: Failed.\n>\n> You have to check it in the beginning of function and either return an\n> error message or just NULL, e.g\n>\n> if (PG_ARGISNULL(0))\n> PG_RETURN_NULL();\n\nInstead of handling this in the function body, the function should be\ndeclared as strict. This is in fact the default in pg_proc.h,\n\n\t/* strict with respect to NULLs? */\n\tbool proisstrict BKI_DEFAULT(t);\n\nso removing the explicit proisstrict => 'f' from the pg_proc.dat entry\nwill fix it with no additional code.\n\n> 2) Add a function call with NULL in the regression tests\n>\n> SELECT * FROM parse_type(NULL);\n>\n> 3) Add the expected behaviour of calling the function with NULL in the\n> docs (error message or null)\n\nOnce the function is declared strict, I don't think either of these is\nnecessary: function strictness is tested elsewhere, and it's the default\nbehaviour. The only functions that explicitly say they return NULL on\nNULL inputs are quote_literal (because you might expect it to return the\nstring 'NULL', but there's qoute_nullable for that) and xmlexists (which\nI don't see any particular reason for).\n\n- ilmari\n\n\n",
"msg_date": "Mon, 05 Feb 2024 14:32:16 +0000",
"msg_from": "=?utf-8?Q?Dagfinn_Ilmari_Manns=C3=A5ker?= <ilmari@ilmari.org>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "\nOn 05.02.24 15:10, David E. Wheeler wrote:\n> Excellent, thank you very much! Updated patch attached.\n>\n> Best,\n>\n> David\n\nv2 no longer crashes with a null parameter.\ndocs and regress tests were updated accordingly.\n\npatch no longer applies cleanly (tiny little indentation issue):\n\n/home/jim/Downloads/v2-0001-Add-parse_type-SQL-function.patch:140:\nindent with spaces.\n PG_RETURN_NULL();\nwarning: 1 line adds whitespace errors.\n\nI read the comments again, and something is not entirely clear to me.\nLine 494 says \"Raises an error on an invalid type.\" and 501 says\n\"Returns NULL for an invalid type.\"\nPerhaps merging both comment blocks and rephrasing these sentences would\nmake things clearer?\n\n-- \nJim\n\n\n\n",
"msg_date": "Mon, 5 Feb 2024 15:43:55 +0100",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "\nOn 05.02.24 15:32, Dagfinn Ilmari Mannsåker wrote:\n> Once the function is declared strict, I don't think either of these is\n> necessary: function strictness is tested elsewhere, and it's the default\n> behaviour. The only functions that explicitly say they return NULL on\n> NULL inputs are quote_literal (because you might expect it to return the\n> string 'NULL', but there's qoute_nullable for that) and xmlexists (which\n> I don't see any particular reason for).\n>\n> - ilmari\n>\n>\n+1\nYes, if the function was strict (which in the current design is not the\ncase) there is no need to check for nulls.\n\n-- \nJim\n\n\n\n",
"msg_date": "Mon, 5 Feb 2024 15:49:29 +0100",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 5, 2024, at 09:49, Jim Jones <jim.jones@uni-muenster.de> wrote:\n\n> Yes, if the function was strict (which in the current design is not the\n> case) there is no need to check for nulls.\n\nRight, done, and cleaned up the redundant comments.\n\nBest,\n\nDavid",
"msg_date": "Mon, 5 Feb 2024 10:14:00 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "\nOn 05.02.24 16:14, David E. Wheeler wrote:\n> Right, done, and cleaned up the redundant comments.\n>\n> Best,\n>\n> David\n\nNice.\nThe patch applies cleanly and it no longer crashes with NULL parameters.\nDocs render fine and regression tests pass. I have nothing more to add.\nLet's now wait for Pavel's review.\n\nThanks!\n\n-- \nJim\n\n\n\n",
"msg_date": "Mon, 5 Feb 2024 16:47:55 +0100",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 5, 2024, at 10:47 AM, Jim Jones <jim.jones@uni-muenster.de> wrote:\n\n> The patch applies cleanly and it no longer crashes with NULL parameters.\n> Docs render fine and regression tests pass. I have nothing more to add.\n> Let's now wait for Pavel's review.\n\nMuch obliged!\n\nD\n\n\n\n",
"msg_date": "Mon, 5 Feb 2024 10:56:23 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "+ /*\n+ * Parse type-name argument to obtain type OID and encoded typmod. We don't\n+ * need to check for parseTypeString failure, but just let the error be\n+ * raised. The 0 arg works both as the `Node *escontext` arg in Postgres 16\n+ * and the `bool missing_ok` arg in 9.4-15.\n+ */\n+ (void) parseTypeString(type, &typid, &typmod, 0);\nif you are wondering around other code deal with NULL, ErrorSaveContext.\nNULL would be more correct?\n`(void) parseTypeString(type, &typid, &typmod, NULL);`\n\nalso parseTypeString already explained the third argument, our\ncomments can be simplified as:\n/*\n* Parse type-name argument to obtain type OID and encoded typmod. We don't\n* need to handle parseTypeString failure, just let the error be\n* raised.\n*/\n\ncosmetic issue. Looking around other error handling code, the format\nshould be something like:\n`\nif (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)\n ereport(ERROR,\n (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n errmsg(\"function returning record called in\"\n \"context that cannot accept type record\")));\n`\n\n`PG_FUNCTION_INFO_V1(parse_type);`\nis unnecessary?\nbased on the error information: https://cirrus-ci.com/task/5899457502380032\nnot sure why it only fails on windows.\n\n+#define PARSE_TYPE_STRING_COLS 2 /* Returns two columns. */\n+#undef PARSE_TYPE_STRING_COLS\nAre these necessary?\ngiven that the comments already say return the OID and type modifier.\n\n\n+ ( <parameter>typid</parameter> <type>oid</type>,\n+ <parameter>typmod</parameter> <type>int4</type> )\nhere `int4` should be `integer`?\n\ncommit message:\n`Also accounts for data typs that require the SQL grammar to be parsed:`\nexcept the typo issue, this sentence is still hard for me to understand.\n\nThe `parse_type()` function uses the underlying `parseTypeString()` C\nfunction to parse a string representing a data type into a type ID and\ntypmod suitabld for passing to `format_type()`.\n\nsuitabld should be suitable.\n\n\n+ <para>\n+ Parses a string representing an SQL type declaration as used in a\n+ <command>CREATE TABLE</command> statement, optionally schema-qualified.\n+ Returns a record with two fields, <parameter>typid</parameter> and\n+ <parameter>typmod</parameter>, representing the OID and\nmodifier for the\n+ type. These correspond to the parameters to pass to the\n+ <link linkend=\"format_type\"><function>format_type</function>\nfunction.</link>\n+ </para>\n\ncan be simplified:\n+ <para>\n+ Parses a string representing an SQL data type, optionally\nschema-qualified.\n+ Returns a record with two fields, <parameter>typid</parameter> and\n+ <parameter>typmod</parameter>, representing the OID and\nmodifier for the\n+ type. These correspond to the parameters to pass to the\n+ <link linkend=\"format_type\"><function>format_type</function>\nfunction.</link>\n+ </para>\n(I don't have a strong opinion though)\n\n\n",
"msg_date": "Sun, 11 Feb 2024 08:00:00 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "Let me comment on some issues since I wrote the very first version of\nparse_type() on which David's patch is based.\n\n> On 2024-02-01 01:00 +0100, jian he <jian.universality@gmail.com> wrote:\n> \n> cosmetic issue. Looking around other error handling code, the format\n> should be something like:\n> `\n> if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)\n> ereport(ERROR,\n> (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n> errmsg(\"function returning record called in\"\n> \"context that cannot accept type record\")));\n> `\n\n+1\n\n> `PG_FUNCTION_INFO_V1(parse_type);`\n> is unnecessary?\n> based on the error information: https://cirrus-ci.com/task/5899457502380032\n> not sure why it only fails on windows.\n\nYeah, it's not necessary for internal functions per [1]. It's a\nleftover from when this function was part of the pgtap extension.\n\n> +#define PARSE_TYPE_STRING_COLS 2 /* Returns two columns. */\n> +#undef PARSE_TYPE_STRING_COLS\n> Are these necessary?\n> given that the comments already say return the OID and type modifier.\n\nNot sure what the convention here is but I found this in a couple of\nplaces, maybe even a tutorial on writing C functions. See\n`git grep '_COLS\\s\\+[1-9]'` for those instances. It's in line with my\nhabit of avoiding magic constants.\n\n> + ( <parameter>typid</parameter> <type>oid</type>,\n> + <parameter>typmod</parameter> <type>int4</type> )\n> here `int4` should be `integer`?\n\n+1\n\n> commit message:\n> `Also accounts for data typs that require the SQL grammar to be parsed:`\n> except the typo issue, this sentence is still hard for me to understand.\n\nYes, the sentence is rather handwavy. What is meant here is that this\nfunction also resolves types whose typmod is determined by the SQL\nparser or some step after that. There are types whose typmod is\nwhatever value is found inside the parenthesis, e.g. bit(13) has typmod\n13. Our first idea before coming up with that function was to do some\nstring manipulation and extract the typmod from inside the parenthesis.\nBut we soon found out that other typmods don't translate one to one,\ne.g. varchar(13) has typmod 17. The interval type is also special\nbecause the typmod is some bitmask encoding of e.g. 'second(0)'. Hence\nthe mention of the SQL grammar.\n\n> + <para>\n> + Parses a string representing an SQL type declaration as used in a\n> + <command>CREATE TABLE</command> statement, optionally schema-qualified.\n> + Returns a record with two fields, <parameter>typid</parameter> and\n> + <parameter>typmod</parameter>, representing the OID and\n> modifier for the\n> + type. These correspond to the parameters to pass to the\n> + <link linkend=\"format_type\"><function>format_type</function>\n> function.</link>\n> + </para>\n> \n> can be simplified:\n> + <para>\n> + Parses a string representing an SQL data type, optionally\n> schema-qualified.\n> + Returns a record with two fields, <parameter>typid</parameter> and\n> + <parameter>typmod</parameter>, representing the OID and\n> modifier for the\n> + type. These correspond to the parameters to pass to the\n> + <link linkend=\"format_type\"><function>format_type</function>\n> function.</link>\n> + </para>\n> (I don't have a strong opinion though)\n\nSounds better. The CREATE TABLE reference is superfluous.\n\n[1] https://www.postgresql.org/docs/current/xfunc-c.html#XFUNC-C-V1-CALL-CONV\n\n-- \nErik\n\n\n",
"msg_date": "Sun, 11 Feb 2024 02:52:56 +0100 (CET)",
"msg_from": "Erik Wienhold <ewie@ewie.name>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 10, 2024, at 20:52, Erik Wienhold <ewie@ewie.name> wrote:\n> \n> Let me comment on some issues since I wrote the very first version of\n> parse_type() on which David's patch is based.\n\nThanks Erik.\n\n>> On 2024-02-01 01:00 +0100, jian he <jian.universality@gmail.com> wrote:\n>> if you are wondering around other code deal with NULL, ErrorSaveContext.\n>> NULL would be more correct?\n>> `(void) parseTypeString(type, &typid, &typmod, NULL);`\n\nFixed.\n\n>> also parseTypeString already explained the third argument, our\n>> comments can be simplified as:\n>> /*\n>> * Parse type-name argument to obtain type OID and encoded typmod. We don't\n>> * need to handle parseTypeString failure, just let the error be\n>> * raised.\n>> */\n\n\nThanks, adopted that language.\n\n>> cosmetic issue. Looking around other error handling code, the format\n>> should be something like:\n>> `\n>> if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)\n>> ereport(ERROR,\n>> (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n>> errmsg(\"function returning record called in\"\n>> \"context that cannot accept type record\")));\n>> `\n> \n> +1\n\nI poked around and found some other examples, yes. I went with a single long line for errmsg following the example in adminpack.c[1]\n\n>> `PG_FUNCTION_INFO_V1(parse_type);`\n>> is unnecessary?\n>> based on the error information: https://cirrus-ci.com/task/5899457502380032\n>> not sure why it only fails on windows.\n> \n> Yeah, it's not necessary for internal functions per [1]. It's a\n> leftover from when this function was part of the pgtap extension.\n\nRemoved.\n\n>> +#define PARSE_TYPE_STRING_COLS 2 /* Returns two columns. */\n>> +#undef PARSE_TYPE_STRING_COLS\n>> Are these necessary?\n>> given that the comments already say return the OID and type modifier.\n> \n> Not sure what the convention here is but I found this in a couple of\n> places, maybe even a tutorial on writing C functions. See\n> `git grep '_COLS\\s\\+[1-9]'` for those instances. It's in line with my\n> habit of avoiding magic constants.\n\nLeft in place for now.\n\n> \n>> + ( <parameter>typid</parameter> <type>oid</type>,\n>> + <parameter>typmod</parameter> <type>int4</type> )\n>> here `int4` should be `integer`?\n> \n> +1\n\nFixed.\n\n> Yes, the sentence is rather handwavy. What is meant here is that this\n> function also resolves types whose typmod is determined by the SQL\n> parser or some step after that. There are types whose typmod is\n> whatever value is found inside the parenthesis, e.g. bit(13) has typmod\n> 13. Our first idea before coming up with that function was to do some\n> string manipulation and extract the typmod from inside the parenthesis.\n> But we soon found out that other typmods don't translate one to one,\n> e.g. varchar(13) has typmod 17. The interval type is also special\n> because the typmod is some bitmask encoding of e.g. 'second(0)'. Hence\n> the mention of the SQL grammar.\n\nI adopted some of your language here --- and fixed the spelling errors :-)\n\n>> can be simplified:\n>> + <para>\n>> + Parses a string representing an SQL data type, optionally\n>> schema-qualified.\n>> + Returns a record with two fields, <parameter>typid</parameter> and\n>> + <parameter>typmod</parameter>, representing the OID and\n>> modifier for the\n>> + type. These correspond to the parameters to pass to the\n>> + <link linkend=\"format_type\"><function>format_type</function>\n>> function.</link>\n>> + </para>\n>> (I don't have a strong opinion though)\n> \n> Sounds better. The CREATE TABLE reference is superfluous.\n\nDone.\n\nBest,\n\nDavid\n[1] https://github.com/postgres/postgres/blob/09eb633e1baa3b7cd7929f3cc77f9c46f63c20b1/contrib/adminpack/adminpack.c#L508-L511",
"msg_date": "Mon, 12 Feb 2024 11:37:46 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "\"David E. Wheeler\" <david@justatheory.com> writes:\n> [ v4-0001-Add-parse_type-SQL-function.patch ]\n\nIt strikes me that this is basically to_regtype() with the additional\noption to return the typmod. That leads to some questions:\n\n* Should we choose a name related to to_regtype? I don't have any\nimmediate suggestions, but since you didn't seem entirely set on\nparse_type, maybe it's worth thinking along those lines. OTOH,\nto the extent that people would use this with format_type, maybe\nparse_type is fine.\n\n* Perhaps the type OID output argument should be declared regtype\nnot plain OID? It wouldn't make any difference for passing it to\nformat_type, but in other use-cases perhaps regtype would be more\nreadable. It's not a deal-breaker either way of course, since\nyou can cast oid to regtype or vice versa.\n\n* Maybe the code should be in adt/regproc.c not format_type.c.\n\n* Experience with to_regtype suggests strongly that people would\nprefer \"return NULL\" to failure for an unrecognized type name.\n\n\nSkimming the patch, I notice that the manual addition to\nbuiltins.h should be unnecessary: the pg_proc.dat entry\nshould be enough to create an extern in fmgrprotos.h.\nAlso, I'm pretty sure that reformat_dat_file.pl will\nthink your pg_proc.dat entry is overly verbose. See\nhttps://www.postgresql.org/docs/devel/system-catalog-initial-data.html\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Mon, 12 Feb 2024 12:53:09 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "I wrote:\n> It strikes me that this is basically to_regtype() with the additional\n> option to return the typmod. That leads to some questions:\n\nBTW, another way that this problem could be approached is to use\nto_regtype() as-is, with a separate function to obtain the typmod:\n\nselect format_type(to_regtype('timestamp(4)'), to_regtypmod('timestamp(4)'));\n\nThis is intellectually ugly, since it implies parsing the same\ntypename string twice. But on the other hand it avoids the notational\npain and runtime overhead involved in using a record-returning\nfunction. So I think it might be roughly a wash for performance.\nQuestion to think about is which way is easier to use. I don't\nhave an opinion particularly; just throwing the idea out there.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Mon, 12 Feb 2024 13:20:04 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "po 12. 2. 2024 v 19:20 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:\n\n> I wrote:\n> > It strikes me that this is basically to_regtype() with the additional\n> > option to return the typmod. That leads to some questions:\n>\n> BTW, another way that this problem could be approached is to use\n> to_regtype() as-is, with a separate function to obtain the typmod:\n>\n> select format_type(to_regtype('timestamp(4)'),\n> to_regtypmod('timestamp(4)'));\n>\n> This is intellectually ugly, since it implies parsing the same\n> typename string twice. But on the other hand it avoids the notational\n> pain and runtime overhead involved in using a record-returning\n> function. So I think it might be roughly a wash for performance.\n> Question to think about is which way is easier to use. I don't\n> have an opinion particularly; just throwing the idea out there.\n>\n\n+1\n\nPavel\n\n>\n> regards, tom lane\n>\n\npo 12. 2. 2024 v 19:20 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:I wrote:\n> It strikes me that this is basically to_regtype() with the additional\n> option to return the typmod. That leads to some questions:\n\nBTW, another way that this problem could be approached is to use\nto_regtype() as-is, with a separate function to obtain the typmod:\n\nselect format_type(to_regtype('timestamp(4)'), to_regtypmod('timestamp(4)'));\n\nThis is intellectually ugly, since it implies parsing the same\ntypename string twice. But on the other hand it avoids the notational\npain and runtime overhead involved in using a record-returning\nfunction. So I think it might be roughly a wash for performance.\nQuestion to think about is which way is easier to use. I don't\nhave an opinion particularly; just throwing the idea out there.+1Pavel\n\n regards, tom lane",
"msg_date": "Mon, 12 Feb 2024 19:26:49 +0100",
"msg_from": "Pavel Stehule <pavel.stehule@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 12, 2024, at 12:53 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> \"David E. Wheeler\" <david@justatheory.com> writes:\n>> [ v4-0001-Add-parse_type-SQL-function.patch ]\n> \n> It strikes me that this is basically to_regtype() with the additional\n> option to return the typmod. That leads to some questions:\n\nHuh. I saw it more on a par with format_type(), at least in the output I expect.\n\n> * Should we choose a name related to to_regtype? I don't have any\n> immediate suggestions, but since you didn't seem entirely set on\n> parse_type, maybe it's worth thinking along those lines. OTOH,\n> to the extent that people would use this with format_type, maybe\n> parse_type is fine.\n\nYeah, and the `to_*` functions return a single OID, not two fields.\n\n> * Perhaps the type OID output argument should be declared regtype\n> not plain OID? It wouldn't make any difference for passing it to\n> format_type, but in other use-cases perhaps regtype would be more\n> readable. It's not a deal-breaker either way of course, since\n> you can cast oid to regtype or vice versa.\n\nSure. I used `oid` because that’s exactly what the argument to format_type() is called, so thought the parity there more appropriate. Maybe its argument should be renamed to regtype?\n\n> * Maybe the code should be in adt/regproc.c not format_type.c.\n\nHappy to move it wherever makes the most sense.\n\n> * Experience with to_regtype suggests strongly that people would\n> prefer \"return NULL\" to failure for an unrecognized type name.\n\nCould do, but as with to_regtype() there’s an issue with error handling when it descends into the SQL parser.\n\n> Skimming the patch, I notice that the manual addition to\n> builtins.h should be unnecessary: the pg_proc.dat entry\n> should be enough to create an extern in fmgrprotos.h.\n\nConfirmed, will remove in next patch.\n\n> Also, I'm pretty sure that reformat_dat_file.pl will\n> think your pg_proc.dat entry is overly verbose. See\n> https://www.postgresql.org/docs/devel/system-catalog-initial-data.html\n\nThere are a bunch of things it reformats:\n\n❯ git diff --name-only \nsrc/include/catalog/pg_aggregate.dat\nsrc/include/catalog/pg_database.dat\nsrc/include/catalog/pg_proc.dat\nsrc/include/catalog/pg_type.dat\nsrc/include/utils/builtins.h\n\nAnd even in pg_proc.dat there are 13 blocks it reformats. I can submit with just my block formatted if you’d prefer.\n\n> BTW, another way that this problem could be approached is to use\n> to_regtype() as-is, with a separate function to obtain the typmod:\n> \n> select format_type(to_regtype('timestamp(4)'), to_regtypmod('timestamp(4)'));\n\nOh interesting.\n\n> This is intellectually ugly, since it implies parsing the same\n> typename string twice. But on the other hand it avoids the notational\n> pain and runtime overhead involved in using a record-returning\n> function. So I think it might be roughly a wash for performance.\n> Question to think about is which way is easier to use. I don't\n> have an opinion particularly; just throwing the idea out there.\n\nHonestly I haven’t cared for the fact that parse_type() returns a record; it makes it a bit clunky. But yeah, so does this to pass the same value to two function calls.\n\nPerhaps it makes sense to add to_regtypmod() as you suggest, but then also something like:\n\nCREATE FUNCTION format_type_string(text) RETURNS TEXT AS $$\n SELECT format_type(to_regtype($1), to_regtypmod($1))\n$$;\n\nBest,\n\nDavid\n\n\n\n",
"msg_date": "Mon, 12 Feb 2024 15:55:58 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 12, 2024, at 15:55, David E. Wheeler <david@justatheory.com> wrote:\n\n> Happy to move it wherever makes the most sense.\n\nUpdate with a bunch of the suggested changes. Some questions still open from the previous post, though. \n\nBest,\n\nDavid",
"msg_date": "Tue, 13 Feb 2024 18:01:46 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On 2024-02-12 19:20 +0100, Tom Lane wrote:\n> I wrote:\n> > It strikes me that this is basically to_regtype() with the additional\n> > option to return the typmod. That leads to some questions:\n> \n> BTW, another way that this problem could be approached is to use\n> to_regtype() as-is, with a separate function to obtain the typmod:\n> \n> select format_type(to_regtype('timestamp(4)'), to_regtypmod('timestamp(4)'));\n> \n> This is intellectually ugly, since it implies parsing the same\n> typename string twice. But on the other hand it avoids the notational\n> pain and runtime overhead involved in using a record-returning\n> function. So I think it might be roughly a wash for performance.\n> Question to think about is which way is easier to use. I don't\n> have an opinion particularly; just throwing the idea out there.\n\nOut of curiosity, I benchmarked this with the attached to_regtypmod()\npatch based on David's v5 applied to a6c21887a9. The script running\npgbench and its output are included at the end.\n\nJust calling parse_type() vs to_regtype()/to_regtypmod() is a wash for\nperformance as you thought. But format_type() performs better with\nto_regtypmod() than with parse_type(). Accessing the record fields\nreturned by parse_type() adds some overhead.\n\nto_regtypmod() is better for our use case in pgTAP which relies on\nformat_type() to normalize the type name. The implementation of\nto_regtypmod() is also simpler than parse_type(). Usage-wise, both are\nclunky IMO.\n\nBenchmark script:\n\n\t#!/usr/bin/env bash\n\t\n\tset -eu\n\t\n\tcat <<'SQL' > parse_type.sql\n\tSELECT parse_type('interval second(0)');\n\tSQL\n\t\n\tcat <<'SQL' > parse_type_and_format.sql\n\tSELECT format_type(p.typid, p.typmod) FROM parse_type('interval second(0)') p;\n\tSQL\n\t\n\tcat <<'SQL' > to_regtypmod.sql\n\tSELECT to_regtype('interval second(0)'), to_regtypmod('interval second(0)');\n\tSQL\n\t\n\tcat <<'SQL' > to_regtypmod_and_format.sql\n\tSELECT format_type(to_regtype('interval second(0)'), to_regtypmod('interval second(0)'));\n\tSQL\n\t\n\tfor f in \\\n\t parse_type.sql \\\n\t parse_type_and_format.sql \\\n\t to_regtypmod.sql \\\n\t to_regtypmod_and_format.sql\n\tdo\n\t pgbench -n -f \"$f\" -T10 postgres\n\t echo\n\tdone\n\npgbench output:\n\n\tpgbench (17devel)\n\ttransaction type: parse_type.sql\n\tscaling factor: 1\n\tquery mode: simple\n\tnumber of clients: 1\n\tnumber of threads: 1\n\tmaximum number of tries: 1\n\tduration: 10 s\n\tnumber of transactions actually processed: 277017\n\tnumber of failed transactions: 0 (0.000%)\n\tlatency average = 0.036 ms\n\tinitial connection time = 1.623 ms\n\ttps = 27706.005513 (without initial connection time)\n\t\n\tpgbench (17devel)\n\ttransaction type: parse_type_and_format.sql\n\tscaling factor: 1\n\tquery mode: simple\n\tnumber of clients: 1\n\tnumber of threads: 1\n\tmaximum number of tries: 1\n\tduration: 10 s\n\tnumber of transactions actually processed: 222487\n\tnumber of failed transactions: 0 (0.000%)\n\tlatency average = 0.045 ms\n\tinitial connection time = 1.603 ms\n\ttps = 22252.095670 (without initial connection time)\n\t\n\tpgbench (17devel)\n\ttransaction type: to_regtypmod.sql\n\tscaling factor: 1\n\tquery mode: simple\n\tnumber of clients: 1\n\tnumber of threads: 1\n\tmaximum number of tries: 1\n\tduration: 10 s\n\tnumber of transactions actually processed: 276134\n\tnumber of failed transactions: 0 (0.000%)\n\tlatency average = 0.036 ms\n\tinitial connection time = 1.570 ms\n\ttps = 27617.628259 (without initial connection time)\n\t\n\tpgbench (17devel)\n\ttransaction type: to_regtypmod_and_format.sql\n\tscaling factor: 1\n\tquery mode: simple\n\tnumber of clients: 1\n\tnumber of threads: 1\n\tmaximum number of tries: 1\n\tduration: 10 s\n\tnumber of transactions actually processed: 270820\n\tnumber of failed transactions: 0 (0.000%)\n\tlatency average = 0.037 ms\n\tinitial connection time = 1.631 ms\n\ttps = 27086.331104 (without initial connection time)\n\n-- \nErik",
"msg_date": "Sun, 18 Feb 2024 19:49:58 +0100",
"msg_from": "Erik Wienhold <ewie@ewie.name>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "Hi\n\nne 18. 2. 2024 v 19:50 odesílatel Erik Wienhold <ewie@ewie.name> napsal:\n\n> On 2024-02-12 19:20 +0100, Tom Lane wrote:\n> > I wrote:\n> > > It strikes me that this is basically to_regtype() with the additional\n> > > option to return the typmod. That leads to some questions:\n> >\n> > BTW, another way that this problem could be approached is to use\n> > to_regtype() as-is, with a separate function to obtain the typmod:\n> >\n> > select format_type(to_regtype('timestamp(4)'),\n> to_regtypmod('timestamp(4)'));\n> >\n> > This is intellectually ugly, since it implies parsing the same\n> > typename string twice. But on the other hand it avoids the notational\n> > pain and runtime overhead involved in using a record-returning\n> > function. So I think it might be roughly a wash for performance.\n> > Question to think about is which way is easier to use. I don't\n> > have an opinion particularly; just throwing the idea out there.\n>\n> Out of curiosity, I benchmarked this with the attached to_regtypmod()\n> patch based on David's v5 applied to a6c21887a9. The script running\n> pgbench and its output are included at the end.\n>\n> Just calling parse_type() vs to_regtype()/to_regtypmod() is a wash for\n> performance as you thought. But format_type() performs better with\n> to_regtypmod() than with parse_type(). Accessing the record fields\n> returned by parse_type() adds some overhead.\n>\n> to_regtypmod() is better for our use case in pgTAP which relies on\n> format_type() to normalize the type name. The implementation of\n> to_regtypmod() is also simpler than parse_type(). Usage-wise, both are\n> clunky IMO.\n>\n> Benchmark script:\n>\n> #!/usr/bin/env bash\n>\n> set -eu\n>\n> cat <<'SQL' > parse_type.sql\n> SELECT parse_type('interval second(0)');\n> SQL\n>\n> cat <<'SQL' > parse_type_and_format.sql\n> SELECT format_type(p.typid, p.typmod) FROM parse_type('interval\n> second(0)') p;\n> SQL\n>\n> cat <<'SQL' > to_regtypmod.sql\n> SELECT to_regtype('interval second(0)'), to_regtypmod('interval\n> second(0)');\n> SQL\n>\n> cat <<'SQL' > to_regtypmod_and_format.sql\n> SELECT format_type(to_regtype('interval second(0)'),\n> to_regtypmod('interval second(0)'));\n> SQL\n>\n> for f in \\\n> parse_type.sql \\\n> parse_type_and_format.sql \\\n> to_regtypmod.sql \\\n> to_regtypmod_and_format.sql\n> do\n> pgbench -n -f \"$f\" -T10 postgres\n> echo\n> done\n>\n> pgbench output:\n>\n> pgbench (17devel)\n> transaction type: parse_type.sql\n> scaling factor: 1\n> query mode: simple\n> number of clients: 1\n> number of threads: 1\n> maximum number of tries: 1\n> duration: 10 s\n> number of transactions actually processed: 277017\n> number of failed transactions: 0 (0.000%)\n> latency average = 0.036 ms\n> initial connection time = 1.623 ms\n> tps = 27706.005513 (without initial connection time)\n>\n> pgbench (17devel)\n> transaction type: parse_type_and_format.sql\n> scaling factor: 1\n> query mode: simple\n> number of clients: 1\n> number of threads: 1\n> maximum number of tries: 1\n> duration: 10 s\n> number of transactions actually processed: 222487\n> number of failed transactions: 0 (0.000%)\n> latency average = 0.045 ms\n> initial connection time = 1.603 ms\n> tps = 22252.095670 (without initial connection time)\n>\n> pgbench (17devel)\n> transaction type: to_regtypmod.sql\n> scaling factor: 1\n> query mode: simple\n> number of clients: 1\n> number of threads: 1\n> maximum number of tries: 1\n> duration: 10 s\n> number of transactions actually processed: 276134\n> number of failed transactions: 0 (0.000%)\n> latency average = 0.036 ms\n> initial connection time = 1.570 ms\n> tps = 27617.628259 (without initial connection time)\n>\n> pgbench (17devel)\n> transaction type: to_regtypmod_and_format.sql\n> scaling factor: 1\n> query mode: simple\n> number of clients: 1\n> number of threads: 1\n> maximum number of tries: 1\n> duration: 10 s\n> number of transactions actually processed: 270820\n> number of failed transactions: 0 (0.000%)\n> latency average = 0.037 ms\n> initial connection time = 1.631 ms\n> tps = 27086.331104 (without initial connection time)\n>\n\nThe overhead of parse_type_and_format can be related to higher planning\ntime. PL/pgSQL can assign composite without usage FROM clause.\n\nRegards\n\nPavel\n\n\n> --\n> Erik\n>\n\nHine 18. 2. 2024 v 19:50 odesílatel Erik Wienhold <ewie@ewie.name> napsal:On 2024-02-12 19:20 +0100, Tom Lane wrote:\n> I wrote:\n> > It strikes me that this is basically to_regtype() with the additional\n> > option to return the typmod. That leads to some questions:\n> \n> BTW, another way that this problem could be approached is to use\n> to_regtype() as-is, with a separate function to obtain the typmod:\n> \n> select format_type(to_regtype('timestamp(4)'), to_regtypmod('timestamp(4)'));\n> \n> This is intellectually ugly, since it implies parsing the same\n> typename string twice. But on the other hand it avoids the notational\n> pain and runtime overhead involved in using a record-returning\n> function. So I think it might be roughly a wash for performance.\n> Question to think about is which way is easier to use. I don't\n> have an opinion particularly; just throwing the idea out there.\n\nOut of curiosity, I benchmarked this with the attached to_regtypmod()\npatch based on David's v5 applied to a6c21887a9. The script running\npgbench and its output are included at the end.\n\nJust calling parse_type() vs to_regtype()/to_regtypmod() is a wash for\nperformance as you thought. But format_type() performs better with\nto_regtypmod() than with parse_type(). Accessing the record fields\nreturned by parse_type() adds some overhead.\n\nto_regtypmod() is better for our use case in pgTAP which relies on\nformat_type() to normalize the type name. The implementation of\nto_regtypmod() is also simpler than parse_type(). Usage-wise, both are\nclunky IMO.\n\nBenchmark script:\n\n #!/usr/bin/env bash\n\n set -eu\n\n cat <<'SQL' > parse_type.sql\n SELECT parse_type('interval second(0)');\n SQL\n\n cat <<'SQL' > parse_type_and_format.sql\n SELECT format_type(p.typid, p.typmod) FROM parse_type('interval second(0)') p;\n SQL\n\n cat <<'SQL' > to_regtypmod.sql\n SELECT to_regtype('interval second(0)'), to_regtypmod('interval second(0)');\n SQL\n\n cat <<'SQL' > to_regtypmod_and_format.sql\n SELECT format_type(to_regtype('interval second(0)'), to_regtypmod('interval second(0)'));\n SQL\n\n for f in \\\n parse_type.sql \\\n parse_type_and_format.sql \\\n to_regtypmod.sql \\\n to_regtypmod_and_format.sql\n do\n pgbench -n -f \"$f\" -T10 postgres\n echo\n done\n\npgbench output:\n\n pgbench (17devel)\n transaction type: parse_type.sql\n scaling factor: 1\n query mode: simple\n number of clients: 1\n number of threads: 1\n maximum number of tries: 1\n duration: 10 s\n number of transactions actually processed: 277017\n number of failed transactions: 0 (0.000%)\n latency average = 0.036 ms\n initial connection time = 1.623 ms\n tps = 27706.005513 (without initial connection time)\n\n pgbench (17devel)\n transaction type: parse_type_and_format.sql\n scaling factor: 1\n query mode: simple\n number of clients: 1\n number of threads: 1\n maximum number of tries: 1\n duration: 10 s\n number of transactions actually processed: 222487\n number of failed transactions: 0 (0.000%)\n latency average = 0.045 ms\n initial connection time = 1.603 ms\n tps = 22252.095670 (without initial connection time)\n\n pgbench (17devel)\n transaction type: to_regtypmod.sql\n scaling factor: 1\n query mode: simple\n number of clients: 1\n number of threads: 1\n maximum number of tries: 1\n duration: 10 s\n number of transactions actually processed: 276134\n number of failed transactions: 0 (0.000%)\n latency average = 0.036 ms\n initial connection time = 1.570 ms\n tps = 27617.628259 (without initial connection time)\n\n pgbench (17devel)\n transaction type: to_regtypmod_and_format.sql\n scaling factor: 1\n query mode: simple\n number of clients: 1\n number of threads: 1\n maximum number of tries: 1\n duration: 10 s\n number of transactions actually processed: 270820\n number of failed transactions: 0 (0.000%)\n latency average = 0.037 ms\n initial connection time = 1.631 ms\n tps = 27086.331104 (without initial connection time)The overhead of parse_type_and_format can be related to higher planning time. PL/pgSQL can assign composite without usage FROM clause.RegardsPavel \n\n-- \nErik",
"msg_date": "Sun, 18 Feb 2024 20:00:36 +0100",
"msg_from": "Pavel Stehule <pavel.stehule@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On 2024-02-18 20:00 +0100, Pavel Stehule wrote:\n> The overhead of parse_type_and_format can be related to higher planning\n> time. PL/pgSQL can assign composite without usage FROM clause.\n\nThanks, didn't know that this makes a difference. In that case both\nvariants are on par.\n\n\tBEGIN;\n\t\n\tCREATE FUNCTION format_with_parse_type(text)\n\tRETURNS text\n\tLANGUAGE plpgsql\n\tSTABLE STRICT\n\tAS $$\n\tDECLARE\n\t p record := parse_type($1);\n\tBEGIN\n\t RETURN format_type(p.typid, p.typmod);\n\tEND\n\t$$;\n\t\n\tCREATE FUNCTION format_with_to_regtypmod(text)\n\tRETURNS text\n\tLANGUAGE plpgsql\n\tSTABLE STRICT\n\tAS $$\n\tBEGIN\n\t RETURN format_type(to_regtype($1), to_regtypmod($1));\n\tEND\n\t$$;\n\t\n\tCOMMIT;\n\nResults:\n\n\tSELECT format_with_parse_type('interval second(0)');\n\n\tpgbench (17devel)\n\ttransaction type: format_with_parse_type.sql\n\tscaling factor: 1\n\tquery mode: simple\n\tnumber of clients: 1\n\tnumber of threads: 1\n\tmaximum number of tries: 1\n\tduration: 10 s\n\tnumber of transactions actually processed: 253530\n\tnumber of failed transactions: 0 (0.000%)\n\tlatency average = 0.039 ms\n\tinitial connection time = 1.846 ms\n\ttps = 25357.551681 (without initial connection time)\n\n\tSELECT format_with_to_regtypmod('interval second(0)');\n\n\tpgbench (17devel)\n\ttransaction type: format_with_to_regtypmod.sql\n\tscaling factor: 1\n\tquery mode: simple\n\tnumber of clients: 1\n\tnumber of threads: 1\n\tmaximum number of tries: 1\n\tduration: 10 s\n\tnumber of transactions actually processed: 257942\n\tnumber of failed transactions: 0 (0.000%)\n\tlatency average = 0.039 ms\n\tinitial connection time = 1.544 ms\n\ttps = 25798.015526 (without initial connection time)\n\n-- \nErik\n\n\n",
"msg_date": "Sun, 18 Feb 2024 21:55:13 +0100",
"msg_from": "Erik Wienhold <ewie@ewie.name>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 18, 2024, at 15:55, Erik Wienhold <ewie@ewie.name> wrote:\n\n>> The overhead of parse_type_and_format can be related to higher planning\n>> time. PL/pgSQL can assign composite without usage FROM clause.\n> \n> Thanks, didn't know that this makes a difference. In that case both\n> variants are on par.\n\nPresumably this is a side-effect of the use of a RECORD here, which requires a FROM clause in pure SQL, yes?\n\nThe only way I can think of to avoid that is to:\n\n1. Add a to_regtypmod() for those who just want the typemod.\n\n2. Add a format_type_string() function that returns a string, the equivalent of this function but in C:\n\nCREATE FUNCTION format_type_string(text) RETURNS TEXT AS $$\n SELECT format_type(to_regtype($1), to_regtypmod($1))\n$$;\n\nWe could also keep the record-returning function for users who want both the regtype and the regytypemod at once, but with the other two I consider it less essential.\n\nThoughts?\n\nBest,\n\nDavid\n\n\n\n",
"msg_date": "Mon, 19 Feb 2024 11:43:34 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "\"David E. Wheeler\" <david@justatheory.com> writes:\n> The only way I can think of to avoid that is to:\n\n> 1. Add a to_regtypmod() for those who just want the typemod.\n\nSeems like there's a good case for doing that.\n\n> 2. Add a format_type_string() function that returns a string, the equivalent of this function but in C:\n\n> CREATE FUNCTION format_type_string(text) RETURNS TEXT AS $$\n> SELECT format_type(to_regtype($1), to_regtypmod($1))\n> $$;\n\nI'm less thrilled about that, mainly because I can't think of\na good name for it (\"format_type_string\" is certainly not that).\nIs the use-case for this functionality really strong enough that\nwe need to provide it as a single function rather than something\nassembled out of spare parts?\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Mon, 19 Feb 2024 15:47:22 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "I wrote:\n> I'm less thrilled about that, mainly because I can't think of\n> a good name for it (\"format_type_string\" is certainly not that).\n\nAfter some time ruminating, a couple of possibilities occurred to\nme:\n\treformat_type(text)\n\tcanonical_type_name(text)\n\n> Is the use-case for this functionality really strong enough that\n> we need to provide it as a single function rather than something\n> assembled out of spare parts?\n\nI'm still unconvinced about that, though.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Mon, 19 Feb 2024 17:13:51 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 19, 2024, at 15:47, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n>> 1. Add a to_regtypmod() for those who just want the typemod.\n> \n> Seems like there's a good case for doing that.\n\nI’ll work on that.\n\n> I'm less thrilled about that, mainly because I can't think of\n> a good name for it (\"format_type_string\" is certainly not that).\n> Is the use-case for this functionality really strong enough that\n> we need to provide it as a single function rather than something\n> assembled out of spare parts?\n\nNot essential for pgTAP, no, as we can just use the parts. It was the typmod bit that was missing.\n\nOn Feb 19, 2024, at 17:13, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> After some time ruminating, a couple of possibilities occurred to\n> me:\n> reformat_type(text)\n> canonical_type_name(text)\n\nI was just thinking about hitting the thesaurus entry for “canonical”, but I quite like reformat_type. It’s super clear and draws the parallel to format_type() more clearly. Will likely steal the name for pgTAP if we don’t add it to core. :-)\n\n> I'm still unconvinced about that, though.\n\nI guess the questions are:\n\n* What are the other use cases for it?\n* How obvious is it how to do it?\n\nFor the latter, it could easily be an example in the docs.\n\nBest,\n\nDavid\n\n\n\n",
"msg_date": "Mon, 19 Feb 2024 17:59:38 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On 2024-02-19 23:59 +0100, David E. Wheeler wrote:\n> On Feb 19, 2024, at 15:47, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> >> 1. Add a to_regtypmod() for those who just want the typemod.\n> > \n> > Seems like there's a good case for doing that.\n> \n> I’ll work on that.\n\nSee the patch I wrote for my benchmarks. But it's pretty easy anyway to\ncut down parse_type() ;)\n\n> > I'm less thrilled about that, mainly because I can't think of a good\n> > name for it (\"format_type_string\" is certainly not that). Is the\n> > use-case for this functionality really strong enough that we need to\n> > provide it as a single function rather than something assembled out\n> > of spare parts?\n> \n> Not essential for pgTAP, no, as we can just use the parts. It was the\n> typmod bit that was missing.\n\nBut you don't actually need reformat_type() in pgTAP. You can just get\nthe type OID and modifier of the want_type and have_type and compare\nthose. Then use format_type() for the error message. Looks a bit\ncleaner to me than doing the string comparison.\n\nOn second thought, I guess comparing the reformatted type names is\nnecessary in order to have a uniform API on older Postgres releases\nwhere pgTAP has to provide its own to_regtypmod() based on typmodin\nfunctions.\n\n> On Feb 19, 2024, at 17:13, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> > After some time ruminating, a couple of possibilities occurred to\n> > me: reformat_type(text) canonical_type_name(text)\n> \n> I was just thinking about hitting the thesaurus entry for “canonical”,\n> but I quite like reformat_type. It’s super clear and draws the\n> parallel to format_type() more clearly. Will likely steal the name for\n> pgTAP if we don’t add it to core. :-)\n> \n> > I'm still unconvinced about that, though.\n> \n> I guess the questions are:\n> \n> * What are the other use cases for it?\n\nCan't think of any right now other than this are-type-names-the-same\ncheck. Perhaps also for pretty-printing user-provided type names where\nwe don't take the type info from e.g. pg_attribute.\n\n> * How obvious is it how to do it?\n> \n> For the latter, it could easily be an example in the docs.\n\nCan be mentioned right under format_type().\n\n-- \nErik\n\n\n",
"msg_date": "Tue, 20 Feb 2024 03:58:05 +0100",
"msg_from": "Erik Wienhold <ewie@ewie.name>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 19, 2024, at 21:58, Erik Wienhold <ewie@ewie.name> wrote:\n\n> See the patch I wrote for my benchmarks. But it's pretty easy anyway to\n> cut down parse_type() ;)\n\nLOL, I missed that, just wrote it myself in the last hour. :-) v6 attached.\n\n> But you don't actually need reformat_type() in pgTAP. You can just get\n> the type OID and modifier of the want_type and have_type and compare\n> those. Then use format_type() for the error message. Looks a bit\n> cleaner to me than doing the string comparison.\n\nFair.\n\n> On second thought, I guess comparing the reformatted type names is\n> necessary in order to have a uniform API on older Postgres releases\n> where pgTAP has to provide its own to_regtypmod() based on typmodin\n> functions.\n\nMaybe. Worth playing with.\n\n>> For the latter, it could easily be an example in the docs.\n> \n> Can be mentioned right under format_type().\n\nWell I included it in the to_regtypemod docs here, but could so either.\n\nBest,\n\nDavid",
"msg_date": "Mon, 19 Feb 2024 22:06:13 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Tue, Feb 20, 2024 at 11:06 AM David E. Wheeler <david@justatheory.com> wrote:\n>\n> LOL, I missed that, just wrote it myself in the last hour. :-) v6 attached.\n>\n\n+SELECT to_regtypemod('interval nonesuch'); -- grammar error expected\n+ERROR: syntax error at or near \"nonesuch\"\n+LINE 1: SELECT to_regtypemod('interval nonesuch');\n+ ^\n+CONTEXT: invalid type name \"interval nonesuch\"\n+SELECT to_regtypemod('year(4)'); -- grammar error expected\n+ to_regtypemod\n+---------------\n+\n+(1 row)\n+\n\nthe second hint `-- grammar error expected` seems to contradict with\nthe results?\n\n\n",
"msg_date": "Tue, 20 Feb 2024 14:30:36 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 20, 2024, at 01:30, jian he <jian.universality@gmail.com> wrote:\n\n> the second hint `-- grammar error expected` seems to contradict with\n> the results?\n\nQuite right, thank you, that’s actually a trapped error. I’ve tweaked the comments and their order in v7, attached.\n\nThis goes back to the discussion of the error raising of to_regtype[1], so I’ve incorporated the patch from that thread into this patch, and set up the docs for to_regtypemod() with similar information. The wording is still a little opaque for my taste, though, written more for someone who knows a bit about the internals, but it’s a start.\n\nI’ve also fixed the wayward parameter in the function signature in the docs, and added a note about why I’ve also patched genbki.pl.\n\nBest,\n\nDavid\n\n[1] https://www.postgresql.org/message-id/flat/57E1FDDC-5A38-452D-82D7-A44DA2E13862%40justatheory.com#1ae0b11634bc33c7ad3cd728e43d504e",
"msg_date": "Tue, 20 Feb 2024 09:44:48 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On 2024-02-20 15:44 +0100, David E. Wheeler wrote:\n> I’ve tweaked the comments and their order in v7, attached.\n> \n> This goes back to the discussion of the error raising of\n> to_regtype[1], so I’ve incorporated the patch from that thread into\n> this patch, and set up the docs for to_regtypemod() with similar\n> information.\n\nMakes sense.\n\n> [1] https://www.postgresql.org/message-id/flat/57E1FDDC-5A38-452D-82D7-A44DA2E13862%40justatheory.com#1ae0b11634bc33c7ad3cd728e43d504e\n\n> - <entry role=\"func_table_entry\"><para role=\"func_signature\">\n> + <entry id=\"format_type\" role=\"func_table_entry\"><para role=\"func_signature\">\n> <indexterm>\n> <primary>format_type</primary>\n> </indexterm>\n> @@ -25462,7 +25462,7 @@ SELECT collation for ('foo' COLLATE \"de_DE\");\n> </row>\n> \n> <row>\n> - <entry role=\"func_table_entry\"><para role=\"func_signature\">\n> + <entry id=\"to_regtype\" role=\"func_table_entry\"><para role=\"func_signature\">\n\nThe references are printed as \"???\" right now. Can be fixed with\nxreflabel=\"format_type\" and xreflabel=\"to_regtype\" on those <entry>\nelements.\n\n> + <function>to_regtypemod</function> ( <parameter>type</parameter> <type>text</type> )\n\nThe docs show parameter name \"type\" but pg_proc.data does not define\nproargnames. So the to_regtypemod() cannot be called using named\nnotation:\n\n\ttest=> select to_regtypemod(type => 'int'::text);\n\tERROR: function to_regtypemod(type => text) does not exist\n\n> + Parses a string of text, extracts a potential type name from it, and\n> + translates its typmod, the modifier for the type, if any. Failure to\n\ns/typmod, the modifier of the type/type modifier/\n\nBecause format_type() already uses \"type modifier\" and I think it helps\nsearchability to use the same wording.\n\n-- \nErik\n\n\n",
"msg_date": "Wed, 21 Feb 2024 03:09:59 +0100",
"msg_from": "Erik Wienhold <ewie@ewie.name>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 20, 2024, at 21:09, Erik Wienhold <ewie@ewie.name> wrote:\n\n> The references are printed as \"???\" right now. Can be fixed with\n> xreflabel=\"format_type\" and xreflabel=\"to_regtype\" on those <entry>\n> elements.\n\nThanks.\n\n> The docs show parameter name \"type\" but pg_proc.data does not define\n> proargnames. So the to_regtypemod() cannot be called using named\n> notation:\n> \n> test=> select to_regtypemod(type => 'int'::text);\n> ERROR: function to_regtypemod(type => text) does not exist\n\nYes, this format is identical to that of to_regtype():\n\ndavid=# select to_regtype(type => 'int'::text);\nERROR: function to_regtype(type => text) does not exist\n\n> + Parses a string of text, extracts a potential type name from it, and\n>> + translates its typmod, the modifier for the type, if any. Failure to\n> \n> s/typmod, the modifier of the type/type modifier/\n> \n> Because format_type() already uses \"type modifier\" and I think it helps\n> searchability to use the same wording.\n\nYes, definitely better wording, thanks. V8 attached.\n\nBest,\n\nDavid",
"msg_date": "Wed, 21 Feb 2024 10:14:02 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On 2024-02-21 16:14 +0100, David E. Wheeler wrote:\n>\n> V8 attached.\n\nThanks. But it's an applefile again, not a patch :P\n\n-- \nErik\n\n\n",
"msg_date": "Wed, 21 Feb 2024 17:18:42 +0100",
"msg_from": "Erik Wienhold <ewie@ewie.name>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 21, 2024, at 11:18, Erik Wienhold <ewie@ewie.name> wrote:\n\n> Thanks. But it's an applefile again, not a patch :P\n\nWTF. I still have that feature disabled.\n\nOh, I think I deleted the file after dragged it into Mail but before sending, because it’s empty everywhere I look. 🤦🏻♂️ Let’s try that again.\n\nBest,\n\nDavid",
"msg_date": "Wed, 21 Feb 2024 11:51:59 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On 2024-02-21 17:51 +0100, David E. Wheeler wrote:\n> On Feb 21, 2024, at 11:18, Erik Wienhold <ewie@ewie.name> wrote:\n> \n> > Thanks. But it's an applefile again, not a patch :P\n> \n> Let’s try that again.\n\nThanks.\n\n> + <function>to_regtypemod</function> ( <parameter>type</parameter> <type>text</type> )\n\nThe docs still state that to_regtypemod() has a named parameter, which\nis not the case per pg_proc.dat.\n\nBesides that, LGTM.\n\n-- \nErik\n\n\n",
"msg_date": "Wed, 21 Feb 2024 22:43:15 +0100",
"msg_from": "Erik Wienhold <ewie@ewie.name>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 21, 2024, at 16:43, Erik Wienhold <ewie@ewie.name> wrote:\n\n> The docs still state that to_regtypemod() has a named parameter, which\n> is not the case per pg_proc.dat.\n\nBah, I cleaned it up before but somehow put it back. Thanks for the catch. Fixed.\n\nBest,\n\nDavid",
"msg_date": "Wed, 21 Feb 2024 16:49:35 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On 2024-02-21 22:49 +0100, David E. Wheeler wrote:\n> On Feb 21, 2024, at 16:43, Erik Wienhold <ewie@ewie.name> wrote:\n> \n> > The docs still state that to_regtypemod() has a named parameter, which\n> > is not the case per pg_proc.dat.\n> \n> Bah, I cleaned it up before but somehow put it back. Thanks for the\n> catch. Fixed.\n\nThanks David! LGTM.\n\n-- \nErik\n\n\n",
"msg_date": "Wed, 21 Feb 2024 23:19:26 +0100",
"msg_from": "Erik Wienhold <ewie@ewie.name>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 21, 2024, at 17:19, Erik Wienhold <ewie@ewie.name> wrote:\n\n> Thanks David! LGTM.\n\nThanks. Anyone else? Or is it ready for committer?\n\nBest,\n\nDavid\n\n\n\n",
"msg_date": "Wed, 21 Feb 2024 19:13:14 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 21, 2024, at 19:13, David E. Wheeler <david@justatheory.com> wrote:\n\n> Thanks. Anyone else? Or is it ready for committer?\n\nWhat’s the protocol for marking a patch ready for committer?\n\nThanks,\n\nDavid\n\n\n\n",
"msg_date": "Sat, 24 Feb 2024 08:46:47 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "\n\nOn 24.02.24 14:46, David E. Wheeler wrote:\n> What’s the protocol for marking a patch ready for committer?\nI guess after the review of the last assigned reviewer\n\n\nv9 applies cleanly, all tests pass and documentation builds correctly.\n\nJust a very small observation:\n\nThe fact that a completely invalid type returns NULL ..\n\nSELECT to_regtypemod('foo');\n to_regtypemod\n---------------\n \n(1 row)\n\n\n.. but a \"partially\" valid one returns an error might be confusing\n\npostgres=# SELECT to_regtypemod('timestamp(-4)');\nERROR: syntax error at or near \"-\"\nLINE 1: SELECT to_regtypemod('timestamp(-4)');\n ^\nCONTEXT: invalid type name \"timestamp(-4)\"\n\npostgres=# SELECT to_regtypemod('text(-4)');\nERROR: type modifier is not allowed for type \"text\"\n\n\nThis behaviour is mentioned in the documentation, so I'd say it is ok.\n\n+ <xref linkend=\"datatype-oid\"/>). Failure to extract a valid\npotential\n+ type name results in an error; however, if the extracted name\nis not\n+ known to the system, this function will return\n<literal>NULL</literal>.\n\nI would personally prefer either NULL or an error in both cases, but I\ncan totally live with the current design.\n\nOTOH, format_type returns \"???\" and it seems to be fine, so don't take\nthis comment too seriously :)\n\nSELECT format_type(-1,-1);\n format_type\n-------------\n ???\n(1 row)\n\n\nOther than that, LGTM.\n\nThanks David!\n\nBest,\nJim\n\n-- \nJim\n\n\n\n",
"msg_date": "Sun, 25 Feb 2024 01:11:42 +0100",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Feb 24, 2024, at 19:11, Jim Jones <jim.jones@uni-muenster.de> wrote:\n\n>> What’s the protocol for marking a patch ready for committer?\n> \n> I guess after the review of the last assigned reviewer\n\nOh, I didn’t realize someone was assigned. :-)\n\n> The fact that a completely invalid type returns NULL ..\n> \n> SELECT to_regtypemod('foo');\n> to_regtypemod\n> ---------------\n> \n> (1 row)\n> \n> \n> .. but a \"partially\" valid one returns an error might be confusing\n> \n> postgres=# SELECT to_regtypemod('timestamp(-4)');\n> ERROR: syntax error at or near \"-\"\n> LINE 1: SELECT to_regtypemod('timestamp(-4)');\n> ^\n> CONTEXT: invalid type name \"timestamp(-4)\"\n> \n> postgres=# SELECT to_regtypemod('text(-4)');\n> ERROR: type modifier is not allowed for type \"text\"\n\nYeah, there was quite a bit of discussion of this issue back in September[1].\n\n> This behaviour is mentioned in the documentation, so I'd say it is ok.\n\nThis is my attempt to make it clearer that it can return an error, but I don’t love the wording TBH.\n\n> I would personally prefer either NULL or an error in both cases, but I\n> can totally live with the current design.\n\nSAME.\n\nBest,\n\nDavid\n\n[1] https://www.postgresql.org/message-id/flat/09F9CAD6-5096-43CC-B6A7-685703E4714D@justatheory.com\n\n\n\n",
"msg_date": "Sun, 25 Feb 2024 13:00:24 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "Hello Hackers,\n\nOn Feb 25, 2024, at 13:00, David E. Wheeler <david@justatheory.com> wrote:\n\n>> postgres=# SELECT to_regtypemod('timestamp(-4)');\n>> ERROR: syntax error at or near \"-\"\n>> LINE 1: SELECT to_regtypemod('timestamp(-4)');\n>> ^\n>> CONTEXT: invalid type name \"timestamp(-4)\"\n>> \n>> postgres=# SELECT to_regtypemod('text(-4)');\n>> ERROR: type modifier is not allowed for type \"text\"\n> \n> Yeah, there was quite a bit of discussion of this issue back in September[1].\n> \n>> This behaviour is mentioned in the documentation, so I'd say it is ok.\n> \n> This is my attempt to make it clearer that it can return an error, but I don’t love the wording TBH.\n\nI’ve rebased the patch and, in an attempt to clarify this behavior, added a couple of examples to the docs for to_regtype. Updated patch attached.\n\nBest,\n\nDavid",
"msg_date": "Thu, 7 Mar 2024 20:37:03 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "Hi David,\n\nOn 2024-03-08 02:37 +0100, David E. Wheeler wrote:\n> I’ve rebased the patch and, in an attempt to clarify this behavior,\n> added a couple of examples to the docs for to_regtype. Updated patch\n> attached.\n\nOn your latest addition:\n\n> + <xref linkend=\"datatype-oid\"/>). Failure to extract a valid potential\n> + type name results in an error. For example:\n> +<programlisting>\n> +SELECT to_regtype('party');\n> + to_regtype\n> +------------\n> +\n> +</programlisting>\n> + However, if the extracted name is not known to the system, this function\n> + will return <literal>NULL</literal>. For example:\n> +<programlisting>\n> +SELECT to_regtype('interval nonesuch');\n> +ERROR: syntax error at or near \"nonesuch\"\n> +LINE 1: select to_regtype('interval nonesuch');\n> + ^\n> +CONTEXT: invalid type name \"interval nonesuch\"\n> +</programlisting>\n\nI think you need to swap the examples. The text mentions the error case\nfirst and the NULL case second.\n\n-- \nErik\n\n\n",
"msg_date": "Fri, 8 Mar 2024 05:39:34 +0100",
"msg_from": "Erik Wienhold <ewie@ewie.name>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Mar 7, 2024, at 23:39, Erik Wienhold <ewie@ewie.name> wrote:\n\n> I think you need to swap the examples. The text mentions the error case\n> first and the NULL case second.\n\n🤦🏻♂️\n\nThanks, fixed in the attached patch.\n\nDavid",
"msg_date": "Fri, 8 Mar 2024 20:42:07 -0500",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On 2024-03-09 02:42 +0100, David E. Wheeler wrote:\n> On Mar 7, 2024, at 23:39, Erik Wienhold <ewie@ewie.name> wrote:\n> \n> > I think you need to swap the examples. The text mentions the error case\n> > first and the NULL case second.\n> \n> 🤦🏻♂️\n> \n> Thanks, fixed in the attached patch.\n\nThanks, LGTM.\n\n-- \nErik\n\n\n",
"msg_date": "Tue, 12 Mar 2024 01:33:55 +0100",
"msg_from": "Erik Wienhold <ewie@ewie.name>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "\"David E. Wheeler\" <david@justatheory.com> writes:\n> Thanks, fixed in the attached patch.\n\nPushed with some editorialization. Mostly, I whacked the\ndocumentation around pretty heavily: we have a convention for what\nexamples in function descriptions should look like, and this wasn't\nit. Not entirely your fault, since some nearby entries in that\ntable hadn't gotten the word either.\n\nAlso, I made a point of adding tests for a corner case that\nI initially thought the patch would not get right:\n\nSELECT format_type(to_regtype('bit'), to_regtypemod('bit'));\n format_type \n-------------\n bit(1)\n(1 row)\n\nSELECT format_type(to_regtype('\"bit\"'), to_regtypemod('\"bit\"'));\n format_type \n-------------\n \"bit\"\n(1 row)\n\nThis comes from the comment in format_type():\n\n /*\n * bit with typmod -1 is not the same as BIT, which means\n * BIT(1) per SQL spec. Report it as the quoted typename so\n * that parser will not assign a bogus typmod.\n */\n\nMy initial fear was that we'd have to emit NULL for no typmod in order\nto round-trip the second case, but it seems to work as-is, so that's good.\nI left it emitting -1 for no typmod, and documented that explicitly.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Wed, 20 Mar 2024 17:23:21 -0400",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Patch: Add parse_type Function"
},
{
"msg_contents": "On Mar 20, 2024, at 17:23, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Pushed with some editorialization. Mostly, I whacked the\n> documentation around pretty heavily: we have a convention for what\n> examples in function descriptions should look like, and this wasn't\n> it. Not entirely your fault, since some nearby entries in that\n> table hadn't gotten the word either.\n\nAh, great, and your wording on the parser error issue is much better, thank you!\n\nBest,\n\nDavid\n\n\n\n",
"msg_date": "Wed, 20 Mar 2024 19:43:16 -0400",
"msg_from": "\"David E. Wheeler\" <david@justatheory.com>",
"msg_from_op": true,
"msg_subject": "Re: Patch: Add parse_type Function"
}
] |
[
{
"msg_contents": "Hi all,\n\nI have a postgresql 15 instance with two databases in it, and I have a need to grant read-only access to one of those databases to a given user.\n\nTo do this I created a dedicated role for readonly access to the database db1:\n\nCREATE ROLE \"dv_read_db1\"\nGRANT CONNECT ON DATABASE db1 TO dv_read_db1\nGRANT USAGE ON SCHEMA public TO “dv_read_db1\"\nGRANT SELECT ON ALL TABLES IN SCHEMA public TO “dv_read_db1\"\nALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO “dv_read_db1\"\n\nCREATE USER minfrin LOGIN;\nGRANT dv_read_db1 TO minfrin;\n\nOn the surface this works, I get readonly access to db1.\n\nTrouble is, I can create tables in db1 which is write access. I can also connect to db2 (bad), and I can enumerate the tables in db2 (bad), although the queries of the contents say access is denied.\n\nI appears the mechanism I am using above has insecure side effects.\n\nWhat is the way to grant read only access to a single database, without exposing other databases, and being futureproof against future features offering potential write access to a read only user?\n\nRegards,\nGraham\n—\n\n\n\n",
"msg_date": "Mon, 5 Feb 2024 00:03:50 +0000",
"msg_from": "Graham Leggett <minfrin@sharp.fm>",
"msg_from_op": true,
"msg_subject": "Grant read-only access to exactly one database amongst many"
},
{
"msg_contents": "Graham Leggett <minfrin@sharp.fm> writes:\n> Trouble is, I can create tables in db1 which is write access. I can also connect to db2 (bad), and I can enumerate the tables in db2 (bad), although the queries of the contents say access is denied.\n\nYou need to read the docs about default privileges: see about\nhalfway down\n\nhttps://www.postgresql.org/docs/15/ddl-priv.html\n\nwhere it says \"PostgreSQL grants privileges on some types of objects\nto PUBLIC by default ...\". In this case I think you likely need to\nrevoke the default public CREATE privilege on schema public in db1,\nand revoke the default public CONNECT privilege on database db2.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Sun, 04 Feb 2024 19:53:52 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Grant read-only access to exactly one database amongst many"
},
{
"msg_contents": "On Sun, Feb 4, 2024 at 5:04 PM Graham Leggett <minfrin@sharp.fm> wrote:\n\n> Hi all,\n>\n> I have a postgresql 15 instance with two databases in it, and I have a\n> need to grant read-only access to one of those databases to a given user.\n>\n> To do this I created a dedicated role for readonly access to the database\n> db1:\n>\n> CREATE ROLE \"dv_read_db1\"\n> GRANT CONNECT ON DATABASE db1 TO dv_read_db1\n>\n\nThis grant is basically pointless since by default all roles can connect\neverywhere via the PUBLIC pseudo-role. You need to revoke that grant, or\neven alter it being given out by default.\n\n\n\n> Trouble is, I can create tables in db1 which is write access.\n\n\nSince in v15 PUBLIC also gets CREATE on the public schema.\n\nI can also connect to db2 (bad),\n\n\nSee my comment regarding the pointless grant in a default setup.\n\nand I can enumerate the tables in db2 (bad),\n>\n\nConnect privilege grants reading all catalog data by design.\n\n\n> I appears the mechanism I am using above has insecure side effects.\n>\n\nIt has, from your expectation, insecure defaults which you never changed.\nWe changed public schema in v16 but the ease-of-use database connecting\nremains.\n\nDavid J.\n\nOn Sun, Feb 4, 2024 at 5:04 PM Graham Leggett <minfrin@sharp.fm> wrote:Hi all,\n\nI have a postgresql 15 instance with two databases in it, and I have a need to grant read-only access to one of those databases to a given user.\n\nTo do this I created a dedicated role for readonly access to the database db1:\n\nCREATE ROLE \"dv_read_db1\"\nGRANT CONNECT ON DATABASE db1 TO dv_read_db1This grant is basically pointless since by default all roles can connect everywhere via the PUBLIC pseudo-role. You need to revoke that grant, or even alter it being given out by default. \nTrouble is, I can create tables in db1 which is write access.Since in v15 PUBLIC also gets CREATE on the public schema. I can also connect to db2 (bad),See my comment regarding the pointless grant in a default setup. and I can enumerate the tables in db2 (bad),Connect privilege grants reading all catalog data by design.\n\nI appears the mechanism I am using above has insecure side effects.It has, from your expectation, insecure defaults which you never changed. We changed public schema in v16 but the ease-of-use database connecting remains.David J.",
"msg_date": "Sun, 4 Feb 2024 17:54:40 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Grant read-only access to exactly one database amongst many"
},
{
"msg_contents": "On 05 Feb 2024, at 00:54, David G. Johnston <david.g.johnston@gmail.com> wrote:\n\n> I have a postgresql 15 instance with two databases in it, and I have a need to grant read-only access to one of those databases to a given user.\n>> \n>> To do this I created a dedicated role for readonly access to the database db1:\n>> \n>> CREATE ROLE \"dv_read_db1\"\n>> GRANT CONNECT ON DATABASE db1 TO dv_read_db1\n> \n> This grant is basically pointless since by default all roles can connect everywhere via the PUBLIC pseudo-role. You need to revoke that grant, or even alter it being given out by default.\n\nMore on this point at the end…\n\n>> Trouble is, I can create tables in db1 which is write access.\n> \n> Since in v15 PUBLIC also gets CREATE on the public schema.\n\n…ouch…\n\n>> I can also connect to db2 (bad),\n> \n> See my comment regarding the pointless grant in a default setup.\n> \n>> and I can enumerate the tables in db2 (bad),\n> \n> Connect privilege grants reading all catalog data by design.\n> \n>> \n>> I appears the mechanism I am using above has insecure side effects.\n> \n> It has, from your expectation, insecure defaults which you never changed. We changed public schema in v16 but the ease-of-use database connecting remains.\n\nIt looks like changing these defaults is likely to be difficult, which is why I posted here.\n\nI want to optionally allow user minfrin to access both databases by doing this:\n\nCREATE USER minfrin LOGIN;\nGRANT dv_read_db1 TO minfrin;\nGRANT dv_read_db2 TO minfrin;\n\nIf I am understanding you correctly to prevent dv_read_db1 from connecting to db2, I need to actively revoke access to db2. Also, to prevent dv_read_db2 from connecting to db1, I need to actively revoke access to db1.\n\nWould the two grants above dv_read_db1 and dv_read_db2 not cause the unintended side effect of revoking access to each other, resulting in no access being allowed at all?\n\nAlso, how do you handle the race condition between the time a database db3 is created, and the the time all readonly users have their access revoked to db3?\n\nRegards,\nGraham\n—\n\n\nOn 05 Feb 2024, at 00:54, David G. Johnston <david.g.johnston@gmail.com> wrote:I have a postgresql 15 instance with two databases in it, and I have a need to grant read-only access to one of those databases to a given user.\n\nTo do this I created a dedicated role for readonly access to the database db1:\n\nCREATE ROLE \"dv_read_db1\"\nGRANT CONNECT ON DATABASE db1 TO dv_read_db1This grant is basically pointless since by default all roles can connect everywhere via the PUBLIC pseudo-role. You need to revoke that grant, or even alter it being given out by default.More on this point at the end…\nTrouble is, I can create tables in db1 which is write access.Since in v15 PUBLIC also gets CREATE on the public schema.…ouch…I can also connect to db2 (bad),See my comment regarding the pointless grant in a default setup. and I can enumerate the tables in db2 (bad),Connect privilege grants reading all catalog data by design.\n\nI appears the mechanism I am using above has insecure side effects.It has, from your expectation, insecure defaults which you never changed. We changed public schema in v16 but the ease-of-use database connecting remains.It looks like changing these defaults is likely to be difficult, which is why I posted here.I want to optionally allow user minfrin to access both databases by doing this:CREATE USER minfrin LOGIN;GRANT dv_read_db1 TO minfrin;GRANT dv_read_db2 TO minfrin;If I am understanding you correctly to prevent dv_read_db1 from connecting to db2, I need to actively revoke access to db2. Also, to prevent dv_read_db2 from connecting to db1, I need to actively revoke access to db1.Would the two grants above dv_read_db1 and dv_read_db2 not cause the unintended side effect of revoking access to each other, resulting in no access being allowed at all?Also, how do you handle the race condition between the time a database db3 is created, and the the time all readonly users have their access revoked to db3?Regards,Graham—",
"msg_date": "Mon, 5 Feb 2024 08:51:50 +0000",
"msg_from": "Graham Leggett <minfrin@sharp.fm>",
"msg_from_op": true,
"msg_subject": "Re: Grant read-only access to exactly one database amongst many"
},
{
"msg_contents": "On Monday, February 5, 2024, Graham Leggett <minfrin@sharp.fm> wrote:\n\n>\n> Also, how do you handle the race condition between the time a database db3\n> is created, and the the time all readonly users have their access revoked\n> to db3?\n>\n>\nYou alter the default privileges for the system so PUBLIC does not get\nconnect privileges on newly created databases.\n\nDavid J.\n\np.s. this mailing list is for discussing patches, discussions Lon how to\nuse the system belong on the -general list.\n\nOn Monday, February 5, 2024, Graham Leggett <minfrin@sharp.fm> wrote:Also, how do you handle the race condition between the time a database db3 is created, and the the time all readonly users have their access revoked to db3?You alter the default privileges for the system so PUBLIC does not get connect privileges on newly created databases.David J.p.s. this mailing list is for discussing patches, discussions Lon how to use the system belong on the -general list.",
"msg_date": "Mon, 5 Feb 2024 07:59:27 -0700",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Grant read-only access to exactly one database amongst many"
}
] |
[
{
"msg_contents": "Hi,\n\ncatalog/syscache_ids.h is referred by utils/syscache.h but\nit's not installed with Meson.\n\nFYI:\n* 9b1a6f50b91dca6610932650c8c81a3c924259f9\n It uses catalog/syscache_ids.h in utils/syscache.h but\n catalog/syscache_ids.h isn't installed.\n* 6eb6086faa3842c2a38a1ee2f97bf9a42ce27610\n It changes a Makefile to install catalog/syscache_ids.h but\n it doesn't change meson.build.\n\n----\ndiff --git a/src/include/catalog/meson.build b/src/include/catalog/meson.build\nindex 6be76dca1d..0bf6e112d5 100644\n--- a/src/include/catalog/meson.build\n+++ b/src/include/catalog/meson.build\n@@ -114,7 +114,7 @@ output_install = [\n dir_data,\n dir_data,\n dir_include_server / 'catalog',\n- false,\n+ dir_include_server / 'catalog',\n dir_include_server / 'catalog',\n dir_include_server / 'catalog',\n ]\n----\n\nThanks,\n-- \nkou\n\n\n",
"msg_date": "Mon, 05 Feb 2024 10:29:32 +0900 (JST)",
"msg_from": "Sutou Kouhei <kou@clear-code.com>",
"msg_from_op": true,
"msg_subject": "meson: catalog/syscache_ids.h isn't installed"
},
{
"msg_contents": "On Mon, Feb 5, 2024 at 10:29 AM Sutou Kouhei <kou@clear-code.com> wrote:\n>\n> Hi,\n>\n> catalog/syscache_ids.h is referred by utils/syscache.h but\n> it's not installed with Meson.\n>\n> FYI:\n> * 9b1a6f50b91dca6610932650c8c81a3c924259f9\n> It uses catalog/syscache_ids.h in utils/syscache.h but\n> catalog/syscache_ids.h isn't installed.\n> * 6eb6086faa3842c2a38a1ee2f97bf9a42ce27610\n> It changes a Makefile to install catalog/syscache_ids.h but\n> it doesn't change meson.build.\n>\n> ----\n> diff --git a/src/include/catalog/meson.build b/src/include/catalog/meson.build\n> index 6be76dca1d..0bf6e112d5 100644\n> --- a/src/include/catalog/meson.build\n> +++ b/src/include/catalog/meson.build\n> @@ -114,7 +114,7 @@ output_install = [\n> dir_data,\n> dir_data,\n> dir_include_server / 'catalog',\n> - false,\n> + dir_include_server / 'catalog',\n> dir_include_server / 'catalog',\n> dir_include_server / 'catalog',\n> ]\n> ----\n>\n\nThank you for reporting the issue and the patch.\n\nI've confirmed this patch fixes the issue. But I don't have enough\nknowledge of meson to assess this fix.\n\nPeter, could you check this fix as it seems the recent commits forgot\nto update the meson.build file?\n\nRegards,\n\n--\nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Mon, 5 Feb 2024 15:55:36 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: meson: catalog/syscache_ids.h isn't installed"
},
{
"msg_contents": "On Mon, Feb 05, 2024 at 03:55:36PM +0900, Masahiko Sawada wrote:\n> I've confirmed this patch fixes the issue. But I don't have enough\n> knowledge of meson to assess this fix.\n> \n> Peter, could you check this fix as it seems the recent commits forgot\n> to update the meson.build file?\n\nThe patched code is telling us that we're forgetting to install\nsyscache_ids.h in the set of headers that should be part of the\nserver-side includes installed. In short, Sutou-san is right, this\nis the right fix, and this is a thinko from 9b1a6f50b91d.\n--\nMichael",
"msg_date": "Mon, 5 Feb 2024 17:00:28 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: meson: catalog/syscache_ids.h isn't installed"
},
{
"msg_contents": "On 2024-Feb-05, Michael Paquier wrote:\n\n> On Mon, Feb 05, 2024 at 03:55:36PM +0900, Masahiko Sawada wrote:\n> > Peter, could you check this fix as it seems the recent commits forgot\n> > to update the meson.build file?\n> \n> The patched code is telling us that we're forgetting to install\n> syscache_ids.h in the set of headers that should be part of the\n> server-side includes installed. In short, Sutou-san is right, this\n> is the right fix, and this is a thinko from 9b1a6f50b91d.\n\nWhat the original rule said was that the file should be installed in\n'false', and now we want it installed in include/catalog. So the\noversight is that the original commit seems to have said that we didn't\nwant the file installed (that's what 'false' means), which is a strange\ndecision.\n\nThe docs here\nhttps://mesonbuild.com/Reference-manual_functions.html#custom_target_install_dir\nseem to explain this well.\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/\n\"But static content is just dynamic content that isn't moving!\"\n http://smylers.hates-software.com/2007/08/15/fe244d0c.html\n\n\n",
"msg_date": "Mon, 5 Feb 2024 11:17:07 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: meson: catalog/syscache_ids.h isn't installed"
},
{
"msg_contents": "On 05.02.24 02:29, Sutou Kouhei wrote:\n> catalog/syscache_ids.h is referred by utils/syscache.h but\n> it's not installed with Meson.\n\nThis has been fixed. (Somebody else reported it in a different thread \nalso.)\n\n\n\n",
"msg_date": "Mon, 5 Feb 2024 17:53:52 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": false,
"msg_subject": "Re: meson: catalog/syscache_ids.h isn't installed"
},
{
"msg_contents": "Hi,\n\nIn <4b60e9bd-426c-4d4b-bbbd-1abd06fa05b9@eisentraut.org>\n \"Re: meson: catalog/syscache_ids.h isn't installed\" on Mon, 5 Feb 2024 17:53:52 +0100,\n Peter Eisentraut <peter@eisentraut.org> wrote:\n\n> On 05.02.24 02:29, Sutou Kouhei wrote:\n>> catalog/syscache_ids.h is referred by utils/syscache.h but\n>> it's not installed with Meson.\n> \n> This has been fixed. (Somebody else reported it in a different thread\n> also.)\n\nThanks!\n\nCommit: 1ae5ace7558ea949d2f94af2fd5eb145d5558659\nThread: https://www.postgresql.org/message-id/CAJ7c6TMDGmAiozDjJQ3%3DP3cd-1BidC_GpitcAuU0aqq-r1eSoQ%40mail.gmail.com\n\n-- \nkou\n\n\n",
"msg_date": "Thu, 08 Feb 2024 15:03:08 +0900 (JST)",
"msg_from": "Sutou Kouhei <kou@clear-code.com>",
"msg_from_op": true,
"msg_subject": "Re: meson: catalog/syscache_ids.h isn't installed"
}
] |
[
{
"msg_contents": "Hi hackers,\n\nCurrently, pgp_sym_decrypt_text and pgp_pub_decrypt_text doesn't\nenforce database encoding validation even when returning text. This\npatch adds validation and dedicated tests to verify its\neffectiveness. Additionally, some existing unit tests were moved to\nthe new tests as they failed in some encoding.\n\nThanks,\nSHihao",
"msg_date": "Sun, 4 Feb 2024 22:15:15 -0500",
"msg_from": "shihao zhong <zhong950419@gmail.com>",
"msg_from_op": true,
"msg_subject": "Encoding protection for pgcrypto"
},
{
"msg_contents": "The following review has been posted through the commitfest application:\nmake installcheck-world: tested, failed\nImplements feature: not tested\nSpec compliant: not tested\nDocumentation: not tested\n\nHello\r\n\r\nI had a look at your patch, which applies fine to PostgreSQL master. I noticed that the new regression tests you have added to test utf-8 encoding fails on my setup (make check) with the following diffs:\r\n\r\n---------------------------------------\r\n@ -13,6 +13,7 @@\r\n =ivrD\r\n -----END PGP MESSAGE-----\r\n '), '0123456789abcdefghij'), 'sha1');\r\n+ERROR: invalid byte sequence for encoding \"UTF8\": 0x91\r\n -- Database encoding protection. Ciphertext source:\r\n -- printf '\\xe0\\xe0\\xbff' | gpg --batch --passphrase mykey --textmode --armor --symmetric\r\n select pgp_sym_decrypt(dearmor('\r\n@@ -23,5 +24,5 @@\r\n =QKy4\r\n -----END PGP MESSAGE-----\r\n '), 'mykey', 'debug=1');\r\n+ERROR: invalid byte sequence for encoding \"UTF8\": 0xe0 0xe0 0xbf\r\n \\quit\r\n-\\endif\r\n---------------------------------------\r\n\r\nI am not sure but it seems that you intentionally provide a text input that would produce a non-utf-8 compliant decrypted output, which triggers the error from within \"pg_verifymbstr()\" call that you have added in pgp-pgsql.c? Are the errors expected in your new test case? If so, then the tests shall pass instead because it has caught a invalid encoding in decrypted output.\r\n\r\nGenerally, I am ok with the extra encoding check after text decryption but do not think if it is a good idea to just error out and abort the transaction when it detects invalid encoding character. text decryption routines may be used quite frequently and users generally do not expect them to abort transaction. It may be ok to just give them a warning about invalid character encoding. \r\n\r\nthanks\r\n--------------------\r\nCary Huang\r\nHighgo Software - Canada\r\nwww.highgo.ca",
"msg_date": "Fri, 09 Feb 2024 22:33:17 +0000",
"msg_from": "cary huang <hcary328@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Encoding protection for pgcrypto"
},
{
"msg_contents": "On Fri, Feb 9, 2024 at 5:34 PM cary huang <hcary328@gmail.com> wrote:\n>\n> The following review has been posted through the commitfest application:\n> make installcheck-world: tested, failed\n> Implements feature: not tested\n> Spec compliant: not tested\n> Documentation: not tested\n>\n> Hello\n>\n> I had a look at your patch, which applies fine to PostgreSQL master. I noticed that the new regression tests you have added to test utf-8 encoding fails on my setup (make check) with the following diffs:\n>\n> ---------------------------------------\n> @ -13,6 +13,7 @@\n> =ivrD\n> -----END PGP MESSAGE-----\n> '), '0123456789abcdefghij'), 'sha1');\n> +ERROR: invalid byte sequence for encoding \"UTF8\": 0x91\n> -- Database encoding protection. Ciphertext source:\n> -- printf '\\xe0\\xe0\\xbff' | gpg --batch --passphrase mykey --textmode --armor --symmetric\n> select pgp_sym_decrypt(dearmor('\n> @@ -23,5 +24,5 @@\n> =QKy4\n> -----END PGP MESSAGE-----\n> '), 'mykey', 'debug=1');\n> +ERROR: invalid byte sequence for encoding \"UTF8\": 0xe0 0xe0 0xbf\n> \\quit\n> -\\endif\n> ---------------------------------------\n>\n> I am not sure but it seems that you intentionally provide a text input that would produce a non-utf-8 compliant decrypted output, which triggers the error from within \"pg_verifymbstr()\" call that you have added in pgp-pgsql.c? Are the errors expected in your new test case? If so, then the tests shall pass instead because it has caught a invalid encoding in decrypted output.\n\nThanks for sharing that, I had updated the pgp-decrypt_utf8.out in the\nv2.patch which will pass the `make -C contrib/pgcrypto check`.\n\n> Generally, I am ok with the extra encoding check after text decryption but do not think if it is a good idea to just error out and abort the transaction when it detects invalid encoding character. text decryption routines may be used quite frequently and users generally do not expect them to abort transaction. It may be ok to just give them a warning about invalid character encoding.\n\nThanks for pointing that out. The goal for this patch is to fix the\nencoding for the TEXT return value because by default the PostgreSQL\nTEXT type should have the same encoding as the database encoding. So I\nonly added mbverify for the pgp_sym_decrypt_text and\npgp_pub_decrypt_text functions. If customers want to use these two\nfunctions without encoding, they should use pgp_pub_decrypt_bytea and\npgp_sym_decrypt_bytea because BYTEA is represented as a binary string\nin PostgreSQL.\n\nPlease let me know if you have more questions or concerns. Thanks!\n\n> thanks\n> --------------------\n> Cary Huang\n> Highgo Software - Canada\n> www.highgo.ca",
"msg_date": "Mon, 12 Feb 2024 23:21:41 -0500",
"msg_from": "shihao zhong <zhong950419@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Encoding protection for pgcrypto"
}
] |
[
{
"msg_contents": "... and the patches in CF #47 (currently open) are listed in 'Next\ncommitfest'. I guess we need to manually create a \"next\" commitfest?\n\nThanks\nRichard\n\n... and the patches in CF #47 (currently open) are listed in 'Nextcommitfest'. I guess we need to manually create a \"next\" commitfest?ThanksRichard",
"msg_date": "Mon, 5 Feb 2024 15:00:03 +0800",
"msg_from": "Richard Guo <guofenglinux@gmail.com>",
"msg_from_op": true,
"msg_subject": "cfbot does not list patches in 'Current commitfest'"
},
{
"msg_contents": "> On 5 Feb 2024, at 08:00, Richard Guo <guofenglinux@gmail.com> wrote:\n> \n> ... and the patches in CF #47 (currently open) are listed in 'Next\n> commitfest'. I guess we need to manually create a \"next\" commitfest?\n\nI've added a years worth of commitfests to the CF app, but I don't know how to\nupdate the CFBot (it might just happen automagically).\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Mon, 5 Feb 2024 08:47:29 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: cfbot does not list patches in 'Current commitfest'"
}
] |
[
{
"msg_contents": "I always found the encoding of the pg_trigger.tgargs field quite weird \nand archaic. (It encodes the trigger argument list into a bytea \ncolumn.) So I tried replacing this with a list of nodes in a \npg_node_tree. This worked out quite nicely. It makes the internal code \nmuch simpler, and it would maybe also allow clients to decode the column \nmore easily.\n\n(Trigger arguments are all strings, so another representation might be \nan array of text, but I think a node representation makes more sense. \nFor example, you could imagine encoding numeric constants more directly, \nbut this is not done here.)\n\nNote that clients shipped with PostgreSQL (such as psql and pg_dump) use\npg_get_triggerdef() and don't access the field directly, so they need no \nchanges. (See also [0].) I don't know about other clients, such as \nthird-party GUIs.\n\nNow, I don't really know if this is worth actually moving forward with, \nunless perhaps someone has additional arguments in favor. But I figured \nit was worth sharing as an idea.\n\n\n[0]: \nhttps://www.postgresql.org/message-id/flat/56c8f5bf-de47-48c1-a592-588fb526e9e6%40eisentraut.org",
"msg_date": "Mon, 5 Feb 2024 11:17:11 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Improve pg_trigger.tgargs representation"
},
{
"msg_contents": "Peter Eisentraut <peter@eisentraut.org> writes:\n> I always found the encoding of the pg_trigger.tgargs field quite weird \n> and archaic. (It encodes the trigger argument list into a bytea \n> column.)\n\nIt is that ...\n\n> So I tried replacing this with a list of nodes in a \n> pg_node_tree. This worked out quite nicely. It makes the internal code \n> much simpler, and it would maybe also allow clients to decode the column \n> more easily.\n\n> (Trigger arguments are all strings, so another representation might be \n> an array of text, but I think a node representation makes more sense. \n> For example, you could imagine encoding numeric constants more directly, \n> but this is not done here.)\n\nI come down on the other side of that: if we change this we should\nchange to array-of-text. I think expecting clients to be able to\ndecode pg_node_tree is an absolutely horrid idea: it's overly complex\nand we change the representation constantly.\n\nAlso, while I see that indeed none of our client-side code looks\ndirectly at pg_trigger.tgargs anymore, there is a lot of backend and\ncontrib code (and therefore likely also 3rd-party extension code) that\ndepends on the representation used in struct Trigger ... which is\narray of C strings. I do not think we dare change that.\n\nOn the whole I'm not sure this is worth messing with. We run at least\nsome risk of breaking somebody's code, and it doesn't seem like we\ngain much unless we're willing to change struct Trigger, which'd\nbreak a *lot* of code.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Mon, 05 Feb 2024 10:49:07 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Improve pg_trigger.tgargs representation"
}
] |
[
{
"msg_contents": "Commit 344d62fb9a9 (2022) introduced unlogged sequences and made it so \nthat identity/serial sequences automatically get the persistence level \nof their owning table. But this works only for CREATE TABLE and not for \nALTER TABLE / ADD COLUMN. This patch fixes that. (should be \nbackpatched to 15, 16)",
"msg_date": "Mon, 5 Feb 2024 16:51:05 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Fix propagation of persistence to sequences in ALTER TABLE / ADD\n COLUMN"
},
{
"msg_contents": "On Mon, Feb 5, 2024 at 9:21 PM Peter Eisentraut <peter@eisentraut.org> wrote:\n>\n> Commit 344d62fb9a9 (2022) introduced unlogged sequences and made it so\n> that identity/serial sequences automatically get the persistence level\n> of their owning table. But this works only for CREATE TABLE and not for\n> ALTER TABLE / ADD COLUMN. This patch fixes that. (should be\n> backpatched to 15, 16)\n\nThe patch looks ok.\n\n+ seqstmt->sequence->relpersistence = cxt->rel ?\ncxt->rel->rd_rel->relpersistence : cxt->relation->relpersistence;\n+\n\nThis condition looks consistent with the other places in the code\naround line 435, 498. But I was worried that cxt->rel may not get\nlatest relpersistence if the ALTER TABLE changes persistence as well.\nAdded a test (0002) which shows that ctx->rel has up-to-date\nrelpersistence. Also added a few other tests. Feel free to\ninclude/reject them while committing.\n\n0001 - same as your patch\n0002 - additional tests\n\n-- \nBest Wishes,\nAshutosh Bapat",
"msg_date": "Thu, 8 Feb 2024 11:34:47 +0530",
"msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix propagation of persistence to sequences in ALTER TABLE / ADD\n COLUMN"
},
{
"msg_contents": "On 08.02.24 07:04, Ashutosh Bapat wrote:\n> The patch looks ok.\n> \n> + seqstmt->sequence->relpersistence = cxt->rel ?\n> cxt->rel->rd_rel->relpersistence : cxt->relation->relpersistence;\n> +\n> \n> This condition looks consistent with the other places in the code\n> around line 435, 498.\n\nAh good, that pattern already existed.\n\n> But I was worried that cxt->rel may not get\n> latest relpersistence if the ALTER TABLE changes persistence as well.\n> Added a test (0002) which shows that ctx->rel has up-to-date\n> relpersistence. Also added a few other tests. Feel free to\n> include/reject them while committing.\n\nYes, this additional coverage seems good. Committed with your additions.\n\n\n\n",
"msg_date": "Fri, 9 Feb 2024 08:19:55 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: Fix propagation of persistence to sequences in ALTER TABLE / ADD\n COLUMN"
}
] |
[
{
"msg_contents": "Hi Hackers,\n\nI just noticed that a couple of places in the docs spell I/O as IO or\neven io when not referring to literal table/view/column names or values\ntherein. Here's a patch to fix them.\n\n- ilmari",
"msg_date": "Mon, 05 Feb 2024 15:59:27 +0000",
"msg_from": "=?utf-8?Q?Dagfinn_Ilmari_Manns=C3=A5ker?= <ilmari@ilmari.org>",
"msg_from_op": true,
"msg_subject": "doc patch: Spell I/O consistently"
},
{
"msg_contents": "On Mon, Feb 05, 2024 at 03:59:27PM +0000, Dagfinn Ilmari Mannsåker wrote:\n> I just noticed that a couple of places in the docs spell I/O as IO or\n> even io when not referring to literal table/view/column names or values\n> therein. Here's a patch to fix them.\n\nMakes sense to me to be consistent in these sections of the docs, so\napplied. Thanks!\n--\nMichael",
"msg_date": "Tue, 6 Feb 2024 13:29:01 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: doc patch: Spell I/O consistently"
},
{
"msg_contents": "Michael Paquier <michael@paquier.xyz> writes:\n\n> On Mon, Feb 05, 2024 at 03:59:27PM +0000, Dagfinn Ilmari Mannsåker wrote:\n>> I just noticed that a couple of places in the docs spell I/O as IO or\n>> even io when not referring to literal table/view/column names or values\n>> therein. Here's a patch to fix them.\n>\n> Makes sense to me to be consistent in these sections of the docs, so\n> applied. Thanks!\n\nThanks!\n\n- ilmari\n\n\n",
"msg_date": "Tue, 06 Feb 2024 10:19:21 +0000",
"msg_from": "=?utf-8?Q?Dagfinn_Ilmari_Manns=C3=A5ker?= <ilmari@ilmari.org>",
"msg_from_op": true,
"msg_subject": "Re: doc patch: Spell I/O consistently"
}
] |
[
{
"msg_contents": "According to the discussion in [1], it's not as safe as we supposed\nto allow different threads to call bindtextdomain() concurrently.\nHere is a patchset to prevent that by acquiring a mutex around\nthe libpq and ecpglib calls that are at risk.\n\nIn libpq, this would've required yet a third copy of the\nWindows-specific ugliness in default_threadlock() and pgtls_init().\nI didn't particularly want to do that, so I stole some ideas\nfrom ecpglib to create a more POSIX-compliant emulation of\npthread_mutex_lock(). 0001 attached is the refactoring needed\nto make that happen, and then 0002 is the actual bug fix.\n\n0001 also gets rid of the possibility that pthread_mutex_init/\npthread_mutex_lock could fail due to malloc failure. This seems\nimportant since default_threadlock() assumes that pthread_mutex_lock\ncannot fail in practice. I observe that ecpglib also assumes that,\nalthough it's using CreateMutex() which has documented failure\nconditions. So I wonder if we ought to copy this implementation\nback into ecpglib; but I've not done that here.\n\n\t\t\tregards, tom lane\n\n[1] https://www.postgresql.org/message-id/flat/18312-bbbabc8113592b78%40postgresql.org",
"msg_date": "Mon, 05 Feb 2024 15:03:36 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": true,
"msg_subject": "Avoiding concurrent calls to bindtextdomain()"
},
{
"msg_contents": "I wrote:\n> 0001 also gets rid of the possibility that pthread_mutex_init/\n> pthread_mutex_lock could fail due to malloc failure. This seems\n> important since default_threadlock() assumes that pthread_mutex_lock\n> cannot fail in practice. I observe that ecpglib also assumes that,\n> although it's using CreateMutex() which has documented failure\n> conditions. So I wonder if we ought to copy this implementation\n> back into ecpglib; but I've not done that here.\n\nThe cfbot seemed happy with v1, so here's a v2 that does copy that\ncode back into ecpglib. (I kind of wonder why this code exists in\nlibpq + ecpglib at all, rather than in src/port/; but that seems\nlike a refactoring exercise for another day.)\n\nI double-checked that all the pthread_mutex_t variables in libpq\nand ecpglib are static, so the change in that struct should not\npose an ABI hazard for back-patching.\n\nBarring objections, I plan to push this pretty soon.\n\n\t\t\tregards, tom lane",
"msg_date": "Thu, 08 Feb 2024 13:08:21 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": true,
"msg_subject": "Re: Avoiding concurrent calls to bindtextdomain()"
}
] |
[
{
"msg_contents": "Hello PostgreSQL Hackers,\n\nThis proposal suggests implementing OCSP Stapling in PostgreSQL as an \nalternative and more efficient method for checking certificate \nrevocation, aligning with the trend shift from Certificate Revocation \nLists (CRL).\n\n\n1. benefits\nOCSP Stapling offers several advantages over traditional CRL checks, \nincluding:\n\n*) enhances user trust and real-time certificate verification without \nrelying on potentially outdated CRLs.\n*) helps address privacy concerns associated with traditional OCSP \nchecks, where the client contacts the OCSP responder directly.\n*) reduces latency by eliminating the need for the client to perform an \nadditional round-trip to the OCSP responder.\n*) efficient resource utilization by allowing the server to cache and \nreuse OCSP responses.\n\n\n\n2. a POC patch with below changes:\n*) a new configuration option 'ssl_ocsp_file' to enable/disable OCSP \nStapling and specify OCSP responses for PostgreSQL servers. For \ninstance, ssl_ocsp_file = '_server.resp'\n\n*) a server-side callback function responsible for generating OCSP \nstapling responses. This function comes into play only when a client \nrequests the server's certificate status during the SSL/TLS handshake.\n\n*) a new connection parameter 'ssl_ocsp_stapling' on the client side. \nFor example, when 'ssl_ocsp_stapling=1', the psql client will send a \ncertificate status request to the PostgreSQL server.\n\n*) a client-side callback function within the libpq interface to \nvalidate and check the stapled OCSP response received from the server. \nIf the server's certificate status is valid, the TLS handshake \ncontinues; otherwise, the connection is rejected.\n\n\n\n3. test cases for 'make check' are not yet ready as they could be \ncomplicated, but basic tests can be performed as demonstrated below:\nTo run the tests, OpenSSL tools are required to simulate the OCSP \nresponder for generating OCSP responses. Additionally, initial \ncertificate generation, including a self-signed root CA, OCSP response \nsigning certificate, and PostgreSQL server certificate, is needed.\n\n*) add ocsp atrributes to openssl.cnf\n$ openssl version\nOpenSSL 3.0.2 15 Mar 2022 (Library: OpenSSL 3.0.2 15 Mar 2022)\n\n$ diff openssl-ocsp.cnf /etc/ssl/openssl.cnf\n204d203\n< authorityInfoAccess = OCSP;URI:http://127.0.0.1:6655\n232,235d230\n< [ v3_ocsp ]\n< basicConstraints = CA:FALSE\n< keyUsage = nonRepudiation, digitalSignature, keyEncipherment\n< extendedKeyUsage = OCSPSigning\n255c250\n< keyUsage = critical, cRLSign, digitalSignature, keyCertSign\n---\n >\n\n\n*) prepare OCSP responder for generating OCSP response\n$ mkdir -p demoCA/newcerts\n$ touch demoCA/index.txt\n$ echo '01' > demoCA/serial\n\n# create a self-signed root CA\n$ openssl req -new -nodes -out rootCA.csr -keyout rootCA.key -subj \n\"/C=CA/ST=BC/L=VAN/O=IDO/OU=DEV/CN=rootCA\"\n$ openssl x509 -req -in rootCA.csr -days 3650 -extfile openssl-ocsp.cnf \n-extensions v3_ca -signkey rootCA.key -out rootCA.crt\n\n# create a certificate for OCSP responder\n$ openssl req -new -nodes -out ocspSigning.csr -keyout ocspSigning.key \n-subj \"/C=CA/ST=BC/L=VAN/O=IDO/OU=DEV/CN=ocspSigner\"\n$ openssl ca -keyfile rootCA.key -cert rootCA.crt -in ocspSigning.csr \n-out ocspSigning.crt -config openssl-ocsp.cnf -extensions v3_ocsp\n Sign the certificate? [y/n]:y\n 1 out of 1 certificate requests certified, commit? [y/n]y\n\n# create a certificate for PostgreSQL server\n$ openssl req -new -nodes -out server.csr -keyout server.key -subj \n\"/C=CA/ST=BC/L=VAN/O=IDO/OU=DEV/CN=server\"\n$ openssl ca -batch -days 365 -keyfile rootCA.key -cert rootCA.crt \n-config openssl-ocsp.cnf -out server.crt -infiles server.csr\n\n\n# start OCSP responder\n$ openssl ocsp -index demoCA/index.txt -port 6655 -rsigner \nocspSigning.crt -rkey ocspSigning.key -CA rootCA.crt -text\n\n# make sure PostgreSQL server's certificate is 'good'\n$ openssl ocsp -issuer rootCA.crt -url http://127.0.0.1:6655 -resp_text \n-noverify -cert server.crt\n\n# generate OCSP response when certificate status is 'good' and save as \n_server.resp-good:\n$ openssl ocsp -issuer rootCA.crt -cert server.crt -url \nhttp://127.0.0.1:6655 -respout _server.resp-good\n\n\n# revoke PostgreSQL server's certificate\n$ openssl ca -keyfile rootCA.key -cert rootCA.crt -revoke server.crt\n\n# make sure PostgreSQL server's certificate is 'revoked'\n$ openssl ocsp -issuer rootCA.crt -url http://127.0.0.1:6655 -resp_text \n-noverify -cert server.crt\n\n### generate OCSP response when certificate status is 'revoked' and save \nas _server.resp-revoked:\n$ openssl ocsp -issuer rootCA.crt -cert server.crt -url \nhttp://127.0.0.1:6655 -respout _server.resp-revoked\n\n\n*) setup OCSP stapling on PostgreSQL server side\ncopy 'rootCA.crt, server.key, server.crt, _server.resp-good, and \n_server.resp-revoked' to pgdata folder and update PostgreSQL server \nconfiguration by specifying ssl_ocsp_file = '_server.resp', where \n'_server.resp' is either a copy of '_server.resp-good' or \n'_server.resp-revoked' depending on the test case, for example:\n\nlisten_addresses = '*'\nssl = on\nssl_ca_file = 'rootCA.crt'\nssl_cert_file = 'server.crt'\nssl_key_file = 'server.key'\nssl_ocsp_file = '_server.resp'\n\n\n\n*) test with psql client\n3.1) PostgreSQL server's certificate status is 'good'\n$ cp -pr _server.resp-good _server.resp\n$ psql -d \"sslmode=verify-ca sslrootcert=rootCA.crt user=david \ndbname=postgres ssl_ocsp_stapling=1\" -h 127.0.0.1 -p 5432\npsql (17devel)\nSSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, \ncompression: off)\nType \"help\" for help.\n\npostgres=#\n\n\n3.2) PostgreSQL server's certificate status is 'revoked'\n$ cp -pr _server.resp-revoked _server.resp\n$ psql -d \"sslmode=verify-ca sslrootcert=rootCA.crt user=david \ndbname=postgres ssl_ocsp_stapling=1\" -h 127.0.0.1 -p 5432\npsql: error: connection to server at \"127.0.0.1\", port 5432 failed: SSL \nerror: ocsp callback failure\n\n\n3.3) PostgreSQL server's certificate status is 'revoked' but OCSP \nstapling is not required by psql client:\n$ psql -d \"sslmode=verify-ca sslrootcert=rootCA.crt user=david \ndbname=postgres ssl_ocsp_stapling=0\" -h 127.0.0.1 -p 5432\npsql (17devel)\nSSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, \ncompression: off)\nType \"help\" for help.\n\npostgres=#\n\n\nThis is a highly experimental proof of concept, and any comments or \nfeedback would be greatly appreciated!\n\n\nBest regards,\nDavid Zhang\n\n===============\nHighgo Software Canada\nwww.highgo.ca",
"msg_date": "Mon, 5 Feb 2024 15:51:03 -0800",
"msg_from": "David Zhang <david.zhang@highgo.ca>",
"msg_from_op": true,
"msg_subject": "Proposal for implementing OCSP Stapling in PostgreSQL"
},
{
"msg_contents": "Hi Hackers,\n\nThis is the 2nd version patch with following updates:\n\n1) Changed the frontend SSL parameter from `ssl_ocsp_stapling` to \n`sslocspstapling` to align with other SSL parameters.\n\n2) Documented both the backend parameter `ssl_ocsp_file` and the \nfrontend parameter `sslocspstapling`.\n\n3) Implemented a check for the `nextUpdate` field in the OCSP response. \nIf it is present but expired, the TLS connection will fail.\"\n\nTo add the test cases for OCSP Stapling, I think I should 1) add one \nsection to conf/cas.config to generate `ocsp_ca.crt`; 2) use this \n`ocsp_ca` to sign some OCSP responses for server side certificates with \n`good`, `revoked` and `unknown`, and then 3) add some test cases to \nt/001_ssltests.pl.\n\nAny comments or feedback would be greatly appreciated!\n\nThank you,\n\nDavid\n\n\nOn 2024-02-05 3:51 p.m., David Zhang wrote:\n> Hello PostgreSQL Hackers,\n>\n> This proposal suggests implementing OCSP Stapling in PostgreSQL as an \n> alternative and more efficient method for checking certificate \n> revocation, aligning with the trend shift from Certificate Revocation \n> Lists (CRL).\n>\n>\n> 1. benefits\n> OCSP Stapling offers several advantages over traditional CRL checks, \n> including:\n>\n> *) enhances user trust and real-time certificate verification without \n> relying on potentially outdated CRLs.\n> *) helps address privacy concerns associated with traditional OCSP \n> checks, where the client contacts the OCSP responder directly.\n> *) reduces latency by eliminating the need for the client to perform \n> an additional round-trip to the OCSP responder.\n> *) efficient resource utilization by allowing the server to cache and \n> reuse OCSP responses.\n>\n>\n>\n> 2. a POC patch with below changes:\n> *) a new configuration option 'ssl_ocsp_file' to enable/disable OCSP \n> Stapling and specify OCSP responses for PostgreSQL servers. For \n> instance, ssl_ocsp_file = '_server.resp'\n>\n> *) a server-side callback function responsible for generating OCSP \n> stapling responses. This function comes into play only when a client \n> requests the server's certificate status during the SSL/TLS handshake.\n>\n> *) a new connection parameter 'ssl_ocsp_stapling' on the client side. \n> For example, when 'ssl_ocsp_stapling=1', the psql client will send a \n> certificate status request to the PostgreSQL server.\n>\n> *) a client-side callback function within the libpq interface to \n> validate and check the stapled OCSP response received from the server. \n> If the server's certificate status is valid, the TLS handshake \n> continues; otherwise, the connection is rejected.\n>\n>\n>\n> 3. test cases for 'make check' are not yet ready as they could be \n> complicated, but basic tests can be performed as demonstrated below:\n> To run the tests, OpenSSL tools are required to simulate the OCSP \n> responder for generating OCSP responses. Additionally, initial \n> certificate generation, including a self-signed root CA, OCSP response \n> signing certificate, and PostgreSQL server certificate, is needed.\n>\n> *) add ocsp atrributes to openssl.cnf\n> $ openssl version\n> OpenSSL 3.0.2 15 Mar 2022 (Library: OpenSSL 3.0.2 15 Mar 2022)\n>\n> $ diff openssl-ocsp.cnf /etc/ssl/openssl.cnf\n> 204d203\n> < authorityInfoAccess = OCSP;URI:http://127.0.0.1:6655\n> 232,235d230\n> < [ v3_ocsp ]\n> < basicConstraints = CA:FALSE\n> < keyUsage = nonRepudiation, digitalSignature, keyEncipherment\n> < extendedKeyUsage = OCSPSigning\n> 255c250\n> < keyUsage = critical, cRLSign, digitalSignature, keyCertSign\n> ---\n> >\n>\n>\n> *) prepare OCSP responder for generating OCSP response\n> $ mkdir -p demoCA/newcerts\n> $ touch demoCA/index.txt\n> $ echo '01' > demoCA/serial\n>\n> # create a self-signed root CA\n> $ openssl req -new -nodes -out rootCA.csr -keyout rootCA.key -subj \n> \"/C=CA/ST=BC/L=VAN/O=IDO/OU=DEV/CN=rootCA\"\n> $ openssl x509 -req -in rootCA.csr -days 3650 -extfile \n> openssl-ocsp.cnf -extensions v3_ca -signkey rootCA.key -out rootCA.crt\n>\n> # create a certificate for OCSP responder\n> $ openssl req -new -nodes -out ocspSigning.csr -keyout ocspSigning.key \n> -subj \"/C=CA/ST=BC/L=VAN/O=IDO/OU=DEV/CN=ocspSigner\"\n> $ openssl ca -keyfile rootCA.key -cert rootCA.crt -in ocspSigning.csr \n> -out ocspSigning.crt -config openssl-ocsp.cnf -extensions v3_ocsp\n> Sign the certificate? [y/n]:y\n> 1 out of 1 certificate requests certified, commit? [y/n]y\n>\n> # create a certificate for PostgreSQL server\n> $ openssl req -new -nodes -out server.csr -keyout server.key -subj \n> \"/C=CA/ST=BC/L=VAN/O=IDO/OU=DEV/CN=server\"\n> $ openssl ca -batch -days 365 -keyfile rootCA.key -cert rootCA.crt \n> -config openssl-ocsp.cnf -out server.crt -infiles server.csr\n>\n>\n> # start OCSP responder\n> $ openssl ocsp -index demoCA/index.txt -port 6655 -rsigner \n> ocspSigning.crt -rkey ocspSigning.key -CA rootCA.crt -text\n>\n> # make sure PostgreSQL server's certificate is 'good'\n> $ openssl ocsp -issuer rootCA.crt -url http://127.0.0.1:6655 \n> -resp_text -noverify -cert server.crt\n>\n> # generate OCSP response when certificate status is 'good' and save as \n> _server.resp-good:\n> $ openssl ocsp -issuer rootCA.crt -cert server.crt -url \n> http://127.0.0.1:6655 -respout _server.resp-good\n>\n>\n> # revoke PostgreSQL server's certificate\n> $ openssl ca -keyfile rootCA.key -cert rootCA.crt -revoke server.crt\n>\n> # make sure PostgreSQL server's certificate is 'revoked'\n> $ openssl ocsp -issuer rootCA.crt -url http://127.0.0.1:6655 \n> -resp_text -noverify -cert server.crt\n>\n> ### generate OCSP response when certificate status is 'revoked' and \n> save as _server.resp-revoked:\n> $ openssl ocsp -issuer rootCA.crt -cert server.crt -url \n> http://127.0.0.1:6655 -respout _server.resp-revoked\n>\n>\n> *) setup OCSP stapling on PostgreSQL server side\n> copy 'rootCA.crt, server.key, server.crt, _server.resp-good, and \n> _server.resp-revoked' to pgdata folder and update PostgreSQL server \n> configuration by specifying ssl_ocsp_file = '_server.resp', where \n> '_server.resp' is either a copy of '_server.resp-good' or \n> '_server.resp-revoked' depending on the test case, for example:\n>\n> listen_addresses = '*'\n> ssl = on\n> ssl_ca_file = 'rootCA.crt'\n> ssl_cert_file = 'server.crt'\n> ssl_key_file = 'server.key'\n> ssl_ocsp_file = '_server.resp'\n>\n>\n>\n> *) test with psql client\n> 3.1) PostgreSQL server's certificate status is 'good'\n> $ cp -pr _server.resp-good _server.resp\n> $ psql -d \"sslmode=verify-ca sslrootcert=rootCA.crt user=david \n> dbname=postgres ssl_ocsp_stapling=1\" -h 127.0.0.1 -p 5432\n> psql (17devel)\n> SSL connection (protocol: TLSv1.2, cipher: \n> ECDHE-RSA-AES256-GCM-SHA384, compression: off)\n> Type \"help\" for help.\n>\n> postgres=#\n>\n>\n> 3.2) PostgreSQL server's certificate status is 'revoked'\n> $ cp -pr _server.resp-revoked _server.resp\n> $ psql -d \"sslmode=verify-ca sslrootcert=rootCA.crt user=david \n> dbname=postgres ssl_ocsp_stapling=1\" -h 127.0.0.1 -p 5432\n> psql: error: connection to server at \"127.0.0.1\", port 5432 failed: \n> SSL error: ocsp callback failure\n>\n>\n> 3.3) PostgreSQL server's certificate status is 'revoked' but OCSP \n> stapling is not required by psql client:\n> $ psql -d \"sslmode=verify-ca sslrootcert=rootCA.crt user=david \n> dbname=postgres ssl_ocsp_stapling=0\" -h 127.0.0.1 -p 5432\n> psql (17devel)\n> SSL connection (protocol: TLSv1.2, cipher: \n> ECDHE-RSA-AES256-GCM-SHA384, compression: off)\n> Type \"help\" for help.\n>\n> postgres=#\n>\n>\n> This is a highly experimental proof of concept, and any comments or \n> feedback would be greatly appreciated!\n>\n>\n> Best regards,\n> David Zhang\n>\n> ===============\n> Highgo Software Canada\n> www.highgo.ca\n>",
"msg_date": "Fri, 23 Feb 2024 16:10:47 -0800",
"msg_from": "David Zhang <david.zhang@highgo.ca>",
"msg_from_op": true,
"msg_subject": "Re: Proposal for implementing OCSP Stapling in PostgreSQL"
},
{
"msg_contents": "Hi Hackers,\n\nThis is the third version patch for \"Certificate status check using OCSP \nStapling\" with ssl regression test cases added.\n\nHere is how I run the ssl regression test:\n ./configure --enable-tap-tests --with-openssl\n make -j\n cd src/test/ssl\n make sslfiles\n make check PG_TEST_EXTRA=ssl\n\nexpected results:\n # +++ tap check in src/test/ssl +++\n t/001_ssltests.pl .. ok\n t/002_scram.pl ..... ok\n t/003_sslinfo.pl ... ok\n All tests successful.\n Files=3, Tests=279, 17 wallclock secs ( 0.05 usr 0.01 sys + 2.32 \ncusr 2.16 csys = 4.54 CPU)\n\n Result: PASS\n\nNotes, before executing the SSL regression tests with the command `make \ncheck PG_TEST_EXTRA=ssl`, it is necessary to wait for 1 minute after \nrunning `make sslfiles`. This delay is required because the newly \ngenerated OCSP responses for the 'expired' test cases need 1 minute to \npass the nextUpdate period. Once the stapled OCSP response files for the \ntests are committed as test input, there is no need to wait, similar to \ncertificate files.\n\nAny comments or feedback would be greatly appreciated!\n\nThank you,\n\nDavid",
"msg_date": "Tue, 5 Mar 2024 16:12:06 -0800",
"msg_from": "David Zhang <david.zhang@highgo.ca>",
"msg_from_op": true,
"msg_subject": "Re: Proposal for implementing OCSP Stapling in PostgreSQL"
},
{
"msg_contents": "On Tue, Mar 5, 2024 at 4:12 PM David Zhang <david.zhang@highgo.ca> wrote:\n> Any comments or feedback would be greatly appreciated!\n\nHi David -- I haven't had time to get to this for the 17 release\ncycle, but I'm interested in this feature and I intend to review it at\nsome point for 18. I think OCSP will be especially helpful for anyone\nrelying on sslrootcert=system. Thanks for working on it!\n\n--Jacob\n\n\n",
"msg_date": "Fri, 22 Mar 2024 10:49:40 -0700",
"msg_from": "Jacob Champion <jacob.champion@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: Proposal for implementing OCSP Stapling in PostgreSQL"
},
{
"msg_contents": "On Tue, Mar 5, 2024 at 4:12 PM David Zhang <david.zhang@highgo.ca> wrote:\n> This is the third version patch for \"Certificate status check using OCSP\n> Stapling\" with ssl regression test cases added.\n\nHi David,\n\nThanks again for working on this! So far I've taken a look at the\ndesign and tests. I've only skimmed the callback implementations; I\nplan to review those in more detail once the architecture is nailed\ndown.\n\n= Design =\n\nIt looks like this design relies on the DBA to manually prefetch OCSP\nresponses for their cert chain, and cache them in the local\nssl_ocsp_file. This is similar to Nginx's ssl_stapling_file directive\n[1]. I think this may make sense for a v1 (much less code!), but it's\ngoing to take a lot of good documentation on what, exactly, an admin\nhas to do to make sure their response file is fresh. IIUC it will\ndepend on the CA's policy and how they operate their responder.\n\nWe should probably be prepared for complaints that we don't run the\nclient ourselves. A v2 could maybe include an extension for running\nthe OCSP client in a background worker? Or maybe that's overkill, and\nan existing job scheduler extension could do it, but having a custom\nworker that could periodically check the response file and provide\nwarnings when it gets close to expiring might be helpful for admins.\n\nI am worried about the multi-stapling that is being done in the tests,\nfor example the server-ca-ocsp-good response file. I think those tests\nare cheating a bit. Yes, for this particular case, we can issue a\nsingle signed response for both the intermediate and the leaf -- but\nthat's only because we issued both of them. What if your intermediate\nand your root use different responders [2]? What if your issuer's\nresponder doesn't even support multiple certs per request [3]?\n\n(Note that OpenSSL still doesn't support multi-stapling [4], even in\nTLS 1.3 where we were supposed to get it \"for free\".)\n\nI think it would be good for the sslocspstapling directive to 1) maybe\nhave a shorter name (cue bikeshed!) and 2) support more than a binary\non/off. For example, the current implementation could use\n\"disable/require\" options, and then a v2 could add \"prefer\" which\nsimply sends the status request and honors must-staple extensions on\nthe certificate. (That should be safe to default to, I think, and it\nwould let DBAs control the stapling rollout more easily.)\n\nA question from ignorance: how does the client decide that the\nsignature on the OCSP response is actually valid for the specific\nchain in use?\n\n= Tests =\n\nI think the tests should record the expected_stderr messages for\nfailures (see the Code section below for why).\n\nIf it turns out that multi-stapling is safe, then IMO the tests should\nexplicitly test both TLSv1.2 and v1.3, since those protocols differ in\nhow they handle per-certificate status.\n\nIf it's okay with you, I'd like to volunteer to refactor out the\nduplicated recipes in sslfiles.mk. I have some particular ideas in\nmind and don't want to make you play fetch-a-rock. (No pressure to use\nwhat I come up with, if you don't like it.)\n\nBecause a CRL is a valid fallback for OCSP in practice, I think there\nshould be some tests for their interaction. (For v1, maybe that's as\nsimple as \"you're not allowed to use both yet\", but it should be\nexplicit.)\n\n= Code =\n\n(this is a very shallow review)\n\n+#define OCSP_CERT_STATUS_OK 1\n+#define OCSP_CERT_STATUS_NOK (-1)\n\nReturning f -1 from the callback indicates an internal error, so we're\ncurrently sending the wrong alerts for OCSP failures (\"internal error\"\nrather than \"bad certificate status response\") and getting unhelpful\nerror messages from libpq. For cases where the handshake proceeds\ncorrectly but we don't accept the OCSP response status, I think we\nshould be returning zero.\n\nAlso, we should not stomp on the OCSP_ namespace (I thought these\nmacros were part of the official <openssl/ocsp.h> API at first).\n\n+ /* set up OCSP stapling callback */\n+ SSL_CTX_set_tlsext_status_cb(SSL_context, ocsp_stapling_cb);\n\nIt seems like this should only be done if ssl_ocsp_file is set?\n\nThanks again!\n--Jacob\n\n[1] https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_stapling_file\n[2] as appears to be the case for postgresql.org\n[3] https://community.letsencrypt.org/t/bulk-ocsp-requests/168156/2\n[4] https://github.com/openssl/openssl/pull/20945\n\n\n",
"msg_date": "Mon, 15 Jul 2024 16:59:24 -0700",
"msg_from": "Jacob Champion <jacob.champion@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: Proposal for implementing OCSP Stapling in PostgreSQL"
},
{
"msg_contents": "> = Design =\n>\n> It looks like this design relies on the DBA to manually prefetch OCSP\n> responses for their cert chain, and cache them in the local\n> ssl_ocsp_file. This is similar to Nginx's ssl_stapling_file directive\n> [1]. I think this may make sense for a v1 (much less code!), but it's\n> going to take a lot of good documentation on what, exactly, an admin\n> has to do to make sure their response file is fresh. IIUC it will\n> depend on the CA's policy and how they operate their responder.\n>\n> We should probably be prepared for complaints that we don't run the\n> client ourselves. A v2 could maybe include an extension for running\n> the OCSP client in a background worker? Or maybe that's overkill, and\n> an existing job scheduler extension could do it, but having a custom\n> worker that could periodically check the response file and provide\n> warnings when it gets close to expiring might be helpful for admins.\nTotally agree. Either Implementing OCSP requests over HTTP, then parsing \nthe response and then saving the results to a file, or using an OpenSSL \nclient with a cron job to periodically update the file should work. \nUsing a cron job would likely have less impact on PostgreSQL.\n> I am worried about the multi-stapling that is being done in the tests,\n> for example the server-ca-ocsp-good response file. I think those tests\n> are cheating a bit. Yes, for this particular case, we can issue a\n> single signed response for both the intermediate and the leaf -- but\n> that's only because we issued both of them. What if your intermediate\n> and your root use different responders [2]? What if your issuer's\n> responder doesn't even support multiple certs per request [3]?\n>\n> (Note that OpenSSL still doesn't support multi-stapling [4], even in\n> TLS 1.3 where we were supposed to get it \"for free\".)\n\nTotally agree, then we should limit OCSP stapling check for the \nleaf/PostgreSQL server certificate only in v1.\n\n> I think it would be good for the sslocspstapling directive to 1) maybe\n> have a shorter name (cue bikeshed!) and 2) support more than a binary\n> on/off. For example, the current implementation could use\n> \"disable/require\" options, and then a v2 could add \"prefer\" which\n> simply sends the status request and honors must-staple extensions on\n> the certificate. (That should be safe to default to, I think, and it\n> would let DBAs control the stapling rollout more easily.)\n\nThis will definitely give end users more options, especially during the \ntransition period.\n\n> A question from ignorance: how does the client decide that the\n> signature on the OCSP response is actually valid for the specific\n> chain in use?\n\nIf I understand correctly, the certificate used by the OCSP responder to \nsign the OCSP response must be valid for the specific chain in use, or \nthe admins allow to load a new chain to validate the certificate used to \nsign the OCSP response. I think it would be better to make this part to \nbe more open.\n\n>\n> = Tests =\n>\n> I think the tests should record the expected_stderr messages for\n> failures (see the Code section below for why).\n+1\n> If it turns out that multi-stapling is safe, then IMO the tests should\n> explicitly test both TLSv1.2 and v1.3, since those protocols differ in\n> how they handle per-certificate status.\n>\n> If it's okay with you, I'd like to volunteer to refactor out the\n> duplicated recipes in sslfiles.mk. I have some particular ideas in\n> mind and don't want to make you play fetch-a-rock. (No pressure to use\n> what I come up with, if you don't like it.)\nThat would be great, thanks a lot in advance!\n> Because a CRL is a valid fallback for OCSP in practice, I think there\n> should be some tests for their interaction. (For v1, maybe that's as\n> simple as \"you're not allowed to use both yet\", but it should be\n> explicit.)\n+1\n> = Code =\n>\n> (this is a very shallow review)\n>\n> +#define OCSP_CERT_STATUS_OK 1\n> +#define OCSP_CERT_STATUS_NOK (-1)\n>\n> Returning f -1 from the callback indicates an internal error, so we're\n> currently sending the wrong alerts for OCSP failures (\"internal error\"\n> rather than \"bad certificate status response\") and getting unhelpful\n> error messages from libpq. For cases where the handshake proceeds\n> correctly but we don't accept the OCSP response status, I think we\n> should be returning zero.\n+1\n> Also, we should not stomp on the OCSP_ namespace (I thought these\n> macros were part of the official <openssl/ocsp.h> API at first).\n+1\n> + /* set up OCSP stapling callback */\n> + SSL_CTX_set_tlsext_status_cb(SSL_context, ocsp_stapling_cb);\n>\n> It seems like this should only be done if ssl_ocsp_file is set?\n\n+1\n\nThanks a lot for reviewing and providing all your feedback!\n\n\nBest regards,\n\nDavid Zhang\n\n\n\n",
"msg_date": "Wed, 17 Jul 2024 15:41:55 -0700",
"msg_from": "David Zhang <idrawone@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Proposal for implementing OCSP Stapling in PostgreSQL"
},
{
"msg_contents": "On Wed, Jul 17, 2024 at 3:42 PM David Zhang <idrawone@gmail.com> wrote:\n> Totally agree. Either Implementing OCSP requests over HTTP, then parsing\n> the response and then saving the results to a file, or using an OpenSSL\n> client with a cron job to periodically update the file should work.\n> Using a cron job would likely have less impact on PostgreSQL.\n\nYeah, my preference would be to farm this job out to OpenSSL entirely.\nImplementing OCSP-over-HTTP ourselves seems unlikely to buy us much,\nfor all the work it would give us.\n\n> Totally agree, then we should limit OCSP stapling check for the\n> leaf/PostgreSQL server certificate only in v1.\n\nSounds good. Maybe a future version can implement a check of the full\nchain, but I imagine we'll have to follow someone else's lead.\n\n> > A question from ignorance: how does the client decide that the\n> > signature on the OCSP response is actually valid for the specific\n> > chain in use?\n>\n> If I understand correctly, the certificate used by the OCSP responder to\n> sign the OCSP response must be valid for the specific chain in use, or\n> the admins allow to load a new chain to validate the certificate used to\n> sign the OCSP response. I think it would be better to make this part to\n> be more open.\n\nOkay. That part needs more design work IMO, and solid testing.\n\n> > If it's okay with you, I'd like to volunteer to refactor out the\n> > duplicated recipes in sslfiles.mk. I have some particular ideas in\n> > mind and don't want to make you play fetch-a-rock. (No pressure to use\n> > what I come up with, if you don't like it.)\n> That would be great, thanks a lot in advance!\n\nNo problem! I've attached two patches that can be optionally applied\non top of yours:\n- 0001 simplifies the response generation into a single recipe.\n- 0002 is a bigger change that uses `openssl ca` to generate index\nfiles, as opposed to constructing them manually ourselves.\n\n(The makefile will get even smaller without multi-stapling support,\nbut I didn't want to combine that with the refactor.)\n\nFor 0002, I'm wiping the new CA index for each recipe and rebuilding\nit from scratch, then copying it into place (this relies on the\n.NOTPARALLEL setting up top for correctness). I think there's probably\nan even simpler approach, which would be to generate a single index\nthat can produce all of our desired responses. I can give that a try\nonce multi-stapling support is pulled out.\n\n> Thanks a lot for reviewing and providing all your feedback!\n\nYou're very welcome, thanks for working on this feature!\n\n--Jacob",
"msg_date": "Thu, 18 Jul 2024 10:18:20 -0700",
"msg_from": "Jacob Champion <jacob.champion@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: Proposal for implementing OCSP Stapling in PostgreSQL"
},
{
"msg_contents": "Thanks a lot Jacob for helping update the tests and sorry for the late \nreply.\n\nBased on previous discussion, I remove the document patch, and start to \nfocus on the v1 simple OCSP logic by checking the leaf/Postgres server \ncertificate's status only \n(0001-v1-WIP-OCSP-support-certificate-status-check.patch). I also merge \nyour changes and simplify the test by testing the Postgres server \ncertificate's status only \n(0002-v1-WIP-OCSP-simplify-.res-generation-and-regress-tes.patch).\n\nOn 2024-07-18 10:18 a.m., Jacob Champion wrote:\n>>> A question from ignorance: how does the client decide that the\n>>> signature on the OCSP response is actually valid for the specific\n>>> chain in use?\n>> If I understand correctly, the certificate used by the OCSP responder to\n>> sign the OCSP response must be valid for the specific chain in use, or\n>> the admins allow to load a new chain to validate the certificate used to\n>> sign the OCSP response. I think it would be better to make this part to\n>> be more open.\n> Okay. That part needs more design work IMO, and solid testing.\nBased on the RFC here, \nhttps://datatracker.ietf.org/doc/html/rfc6960#section-4.2.2.2. My \nunderstanding is that the OCSP responder's certificate should be \ndirectly signed by the same CA which signed the Postgres Server's \ncertificate. It looks the openssl 3.0.14 implements in this way. In \nother words, it the OCSP responder's certificate is signed by a \ndifferent branch of the chain, then openssl will report some errors. \nUnless the end user explicitly provides the OCSP responder's certificate \nwith trust_other option. In this case it will skip the some certificate \nverification. I think it should be simple enough for v1 by set \n`OCSP_basic_verify(basic_resp, NULL, trusted_store, 0)`. The key \nfunction OCSP_basic_verify is documented at here, \nhttps://docs.openssl.org/3.0/man3/OCSP_resp_find_status/\n\n\n\nThank you,\nDavid",
"msg_date": "Tue, 6 Aug 2024 16:33:21 -0700",
"msg_from": "David Zhang <idrawone@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Proposal for implementing OCSP Stapling in PostgreSQL"
},
{
"msg_contents": "While I have only skimmed the patch so far and need more review before I can\ncomment on it, I do have a question on the expected use of OCSP support in\npostgres. With OCSP becoming optional [0], and big providers like Let's\nEncrypt deprecating OCSP [1], is this mainly targeting organizations running\ntheir own CA with in-house OCSP?\n\n--\nDaniel Gustafsson\n\n[0] https://lists.cabforum.org/pipermail/servercert-wg/2023-September/003998.html\n[1] https://letsencrypt.org/2024/07/23/replacing-ocsp-with-crls.html\n\n\n\n",
"msg_date": "Wed, 7 Aug 2024 09:20:01 +0200",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: Proposal for implementing OCSP Stapling in PostgreSQL"
},
{
"msg_contents": "Hi Daniel,\n\nThank you for all the information.\n\nOn 2024-08-07 12:20 a.m., Daniel Gustafsson wrote:\n> While I have only skimmed the patch so far and need more review before I can\n> comment on it, I do have a question on the expected use of OCSP support in\n> postgres. With OCSP becoming optional [0], and big providers like Let's\n> Encrypt deprecating OCSP [1], is this mainly targeting organizations running\n> their own CA with in-house OCSP?\n>\n> --\n> Daniel Gustafsson\n>\n> [0] https://lists.cabforum.org/pipermail/servercert-wg/2023-September/003998.html\n> [1] https://letsencrypt.org/2024/07/23/replacing-ocsp-with-crls.html\nRegarding the privacy concert, the OCSP Stapling works in a very similar \nway as CRL but provide a more \"real-time\" certificate status checking. \nWhen the Client/psql needs to check the Certificate Status using OCSP \nStapling, it doesn't connect to any 3rd party server, such as CA or OCSP \nResponder. It only requires the Server/Postgres to provide one extra \npiece of information about the status of Server's certificate. OCSP \nStapling was designed to avoid the privacy concern and a single point of \nfailure issues.\n\nWhen the Client/psql needs to check the certificate revocation status:\noption 1 using CRL: CA generates the CRL and then upload it to somewhere \nor distribute it to each Client/psql. I think Postgres only support the \npreloaded CRL.\noption 2 using OCSP Stapling: Postgres server retrieves the certificate \nstatus periodically from OCSP responder, the Client/psql will do the \ncertificate status check during each handshake.\n\nI think it is still necessary to provide the 2nd option/flexibility to \nend users if they are allowed to check the Postgres server's certificate \nrevocation status through CRL.\n\nThank you,\nDavid\n\n\n",
"msg_date": "Wed, 7 Aug 2024 11:07:51 -0700",
"msg_from": "David Zhang <idrawone@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Proposal for implementing OCSP Stapling in PostgreSQL"
},
{
"msg_contents": "On Wed, Aug 7, 2024 at 12:20 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n>\n> While I have only skimmed the patch so far and need more review before I can\n> comment on it, I do have a question on the expected use of OCSP support in\n> postgres. With OCSP becoming optional [0], and big providers like Let's\n> Encrypt deprecating OCSP [1], is this mainly targeting organizations running\n> their own CA with in-house OCSP?\n\nThat announcement took me by surprise (and, it looks like, a number of\nother people [1, 2]). I get that OCSP is expensive and painful for\nLet's Encrypt, based on previous outages and blog posts, but I also\nfigured that Must-Staple was basically the best you could do without\nbeing a browser. It already seemed pretty clear that we shouldn't\nbuild a client-side OCSP check. Throwing server-side stapling under\nthe bus with it was unexpected.\n\nSome of the LE quotes on the matter are giving me cart-before-horse vibes:\n\n> But it is clear to me OCSP is an ineffective technical dead-end, and we are all better served by moving on to figure out what else we can do.\n>\n> We may keep OCSP running for some time for certificates that have the must-staple extension, to help smooth the transition, but at this time we don’t have a plan for how to actually deprecate OCSP: just an intent, publicized to ensure we can all begin to plan for a future without it.\n\nIt's pretty frustrating to hear about a \"transition\" when there is\nnothing to transition to.\n\nI honestly wonder if they're going to end up walking some of this\nback. The messaging reminds me of \"that one project\" that every\ncompany seems to have, where it's expensive and buggy as heck, all the\nmaintainers want to see it deleted, and they unilaterally declare over\nclients' objections that they will, only to find at the last second\nthat the cure is worse than the disease and then finally resign\nthemselves to supporting it. Tears are shed, bridges burned.\n\nAnyways, I look forward to seeing how broken my crystal ball is this\ntime. The timing is awful for this patchset in particular.\n\n--Jacob\n\n[1] https://community.letsencrypt.org/t/sunsetting-of-ocsp-in-favor-of-older-technology/222589\n[2] https://community.letsencrypt.org/t/what-will-happen-to-must-staple/222397\n\n\n",
"msg_date": "Wed, 14 Aug 2024 15:42:51 -0700",
"msg_from": "Jacob Champion <jacob.champion@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: Proposal for implementing OCSP Stapling in PostgreSQL"
},
{
"msg_contents": "> On 15 Aug 2024, at 00:42, Jacob Champion <jacob.champion@enterprisedb.com> wrote:\n\n> It's pretty frustrating to hear about a \"transition\" when there is\n> nothing to transition to.\n\nI guess they prefer that orgs transition back to just using CRL's.\n\n> Anyways, I look forward to seeing how broken my crystal ball is this\n> time. The timing is awful for this patchset in particular.\n\nIt is indeed, if it ends up deprecated server-side among the big providers then\nsupport for it risks being very hard to use. Not sure what is the best course\nof action here is.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Mon, 2 Sep 2024 14:54:59 +0200",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: Proposal for implementing OCSP Stapling in PostgreSQL"
},
{
"msg_contents": "On Mon, Sep 2, 2024 at 5:55 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n> I guess they prefer that orgs transition back to just using CRL's.\n\n From a practical perspective, I don't think anyone but browsers can do\nthat right now. Best I can tell, there's no CRLite client other than\nFirefox, and Google's CRLSets look like a manual emergency system\nrather than a general-purpose tool.\n\nI don't think we could do it manually even if we wanted to (and we\ndon't want to, IMHO, for a whole host of reasons). As one specific\nexample, take the certificate for postgresql.org. There's no CRL\ndistribution point listed, and an LE blog post [1] from a couple years\nback implies that they have no plans to make those available to us:\n\n Although we will be producing CRLs which cover all certificates that we\n issue, we will not be including those URLs in the CRL Distribution Point\n extension of our certificates. [...] Our new CRL URLs will be disclosed\n only in CCADB, so that the Apple and Mozilla root programs can consume\n them without exposing them to potentially large download traffic from\n the rest of the internet at large.\n\nFrankly, it looks like they have no plan for non-browser clients. It's\nfeeling like one of those \"Web\" vs. \"Internet\" splits.\n\n--Jacob\n\n[1] https://letsencrypt.org/2022/09/07/new-life-for-crls.html\n\n\n",
"msg_date": "Tue, 3 Sep 2024 10:20:31 -0700",
"msg_from": "Jacob Champion <jacob.champion@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: Proposal for implementing OCSP Stapling in PostgreSQL"
}
] |
[
{
"msg_contents": "Hi,\n\nLooking at the profiles in [1], and similar profiles locally, made me wonder\nwhy a basic COPY TO shows pg_server_to_any() and the strlen() to compute the\nlength of the to-be-converted string so heavily in profiles. Example\nprofile, for [2]:\n\n- 88.11% 12.02% postgres postgres [.] CopyOneRowTo\n - 76.09% CopyOneRowTo\n - 37.24% CopyAttributeOutText\n + 14.25% __strlen_evex\n + 2.76% pg_server_to_any\n + 0.03% 0xffffffff82a00c86\n + 31.82% OutputFunctionCall\n + 2.98% CopySendEndOfRow\n + 2.75% appendBinaryStringInfo\n + 0.58% MemoryContextReset\n + 0.02% 0xffffffff82a00c86\n + 12.01% standard_ExecutorRun\n + 0.02% PostgresMain\n\nIn the basic cases the client and server encoding should be the same after\nall, so why do we need to do any conversion?\n\nThe code has a comment about this:\n\n\t/*\n\t * Set up encoding conversion info. Even if the file and server encodings\n\t * are the same, we must apply pg_any_to_server() to validate data in\n\t * multibyte encodings.\n\t */\n\tcstate->need_transcoding =\n\t\t(cstate->file_encoding != GetDatabaseEncoding() ||\n\t\t pg_database_encoding_max_length() > 1);\n\nI don't really understand why we need to validate anything during COPY TO?\nWhich is good, because it turns out that we don't actually validate anything,\nas pg_server_to_any() returns without doing anything if the encoding matches:\n\n\tif (encoding == DatabaseEncoding->encoding ||\n\t\tencoding == PG_SQL_ASCII)\n\t\treturn unconstify(char *, s);\t/* assume data is valid */\n\nThis means that the strlen() we do in the call do pg_server_to_any(), which on\nits own takes 14.25% of the cycles, computes something that will never be\nused.\n\n\nUnsurprisingly, only doing transcoding when encodings differ yields a sizable\nimprovement, about 18% for [2].\n\n\nI haven't yet dug into the code history. One guess is that this should only\nhave been set this way for COPY FROM.\n\nGreetings,\n\nAndres Freund\n\n[1] https://www.postgresql.org/message-id/ZcGE8LrjGW8pmtOf%40paquier.xyz\n[2] COPY (SELECT 1::int2,2::int2,3::int2,4::int2,5::int2,6::int2,7::int2,8::int2,9::int2,10::int2,11::int2,12::int2,13::int2,14::int2,15::int2,16::int2,17::int2,18::int2,19::int2,20::int2, generate_series(1, 1000000::int4)) TO '/dev/null';\n\n\n",
"msg_date": "Mon, 5 Feb 2024 18:05:04 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": true,
"msg_subject": "confusing / inefficient \"need_transcoding\" handling in copy"
},
{
"msg_contents": "On Mon, Feb 05, 2024 at 06:05:04PM -0800, Andres Freund wrote:\n> I don't really understand why we need to validate anything during COPY TO?\n> Which is good, because it turns out that we don't actually validate anything,\n> as pg_server_to_any() returns without doing anything if the encoding matches:\n> \n> \tif (encoding == DatabaseEncoding->encoding ||\n> \t\tencoding == PG_SQL_ASCII)\n> \t\treturn unconstify(char *, s);\t/* assume data is valid */\n> \n> This means that the strlen() we do in the call do pg_server_to_any(), which on\n> its own takes 14.25% of the cycles, computes something that will never be\n> used.\n\nIndeed, that's wasting cycles for nothing when the client and server\nencoding match.\n\n> Unsurprisingly, only doing transcoding when encodings differ yields a sizable\n> improvement, about 18% for [2].\n> \n> I haven't yet dug into the code history. One guess is that this should only\n> have been set this way for COPY FROM.\n\nLooking the git history, this looks like an oversight of c61a2f58418e\nthat has added the condition on pg_database_encoding_max_length(), no?\nAdding Tom and Ishii-san, even if this comes from 2005.\n--\nMichael",
"msg_date": "Tue, 6 Feb 2024 13:49:38 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: confusing / inefficient \"need_transcoding\" handling in copy"
},
{
"msg_contents": "Michael Paquier <michael@paquier.xyz> writes:\n> On Mon, Feb 05, 2024 at 06:05:04PM -0800, Andres Freund wrote:\n>> I haven't yet dug into the code history. One guess is that this should only\n>> have been set this way for COPY FROM.\n\n> Looking the git history, this looks like an oversight of c61a2f58418e\n> that has added the condition on pg_database_encoding_max_length(), no?\n> Adding Tom and Ishii-san, even if this comes from 2005.\n\nYeah, back in 8.1 that code was applied for both directions, but\nprobably it should have enforced validation for same-encoding\ncases only for COPY FROM.\n\nIt looks like now we have a mess, because the condition was copied\nverbatim into copyto.c but not copyfrom.c. Aren't we failing to\nvalidate encoding in this case in COPY FROM, which is where we\nactually need to?\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Tue, 06 Feb 2024 12:51:48 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: confusing / inefficient \"need_transcoding\" handling in copy"
},
{
"msg_contents": "Hi,\n\nOn 2024-02-06 12:51:48 -0500, Tom Lane wrote:\n> Michael Paquier <michael@paquier.xyz> writes:\n> > On Mon, Feb 05, 2024 at 06:05:04PM -0800, Andres Freund wrote:\n> >> I haven't yet dug into the code history. One guess is that this should only\n> >> have been set this way for COPY FROM.\n>\n> > Looking the git history, this looks like an oversight of c61a2f58418e\n> > that has added the condition on pg_database_encoding_max_length(), no?\n> > Adding Tom and Ishii-san, even if this comes from 2005.\n>\n> Yeah, back in 8.1 that code was applied for both directions, but\n> probably it should have enforced validation for same-encoding\n> cases only for COPY FROM.\n>\n> It looks like now we have a mess, because the condition was copied\n> verbatim into copyto.c but not copyfrom.c. Aren't we failing to\n> validate encoding in this case in COPY FROM, which is where we\n> actually need to?\n\nI think the code is just very confusing - there actually *is* verification of\nthe encoding, it just happens at a different, earlier, layer, namely in\ncopyfromparse.c: CopyConvertBuf() which says:\n\t/*\n\t * If the file and server encoding are the same, no encoding conversion is\n\t * required. However, we still need to verify that the input is valid for\n\t * the encoding.\n\t */\n\nAnd does indeed verify that.\n\n\nOne unfortunate issue: We don't have any tests verifying that COPY FROM\ncatches encoding issues.\n\nRegards,\n\nAndres\n\n\n",
"msg_date": "Tue, 6 Feb 2024 14:24:45 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": true,
"msg_subject": "Re: confusing / inefficient \"need_transcoding\" handling in copy"
},
{
"msg_contents": "On Tue, Feb 06, 2024 at 02:24:45PM -0800, Andres Freund wrote:\n> I think the code is just very confusing - there actually *is* verification of\n> the encoding, it just happens at a different, earlier, layer, namely in\n> copyfromparse.c: CopyConvertBuf() which says:\n> \t/*\n> \t * If the file and server encoding are the same, no encoding conversion is\n> \t * required. However, we still need to verify that the input is valid for\n> \t * the encoding.\n> \t */\n>\n> And does indeed verify that.\n\nThis has been switched by Heikki in f82de5c46bdf, in 2021, that has\nremoved pg_database_encoding_max_length() in the COPY FROM case.\n(Adding him now in CC, in case he has any comments).\n\n> One unfortunate issue: We don't have any tests verifying that COPY FROM\n> catches encoding issues.\n\nOops.\n\nAnyway, I was looking at the copyto.c code because I need to get\nsomething on this thread to be able to do something about the\npluggable APIs in COPY, and echoing with what you mentioned upthread,\nwhat we only need to do is to set need_transcoding only when the\nclient and the server encodings are not the same? Am I missing\nsomething?\n\nRuntime gets much better in average, around 1260ms on HEAD vs 1023ms\nwith the attached for the example of upthread on a single process.\nSome profile data from CopyOneRowTo(), if relevant:\n* HEAD:\n- 82.78% 10.96% postgres postgres [.] CopyOneRowTo\n - 71.82% CopyOneRowTo\n + 30.87% OutputFunctionCall\n - 13.21% CopyAttributeOutText\n pg_server_to_any\n - 9.48% appendBinaryStringInfo\n 4.93% enlargeStringInfo\n 3.33% 0xffffa4e1e234\n + 3.20% CopySendEndOfRow\n 2.66% 0xffffa4e1e214\n 1.02% pgstat_progress_update_param\n 0.86% memcpy@plt\n 0.74% 0xffffa4e1cba4\n 0.72% MemoryContextReset\n 0.72% 0xffffa4e1cba8\n 0.59% enlargeStringInfo\n 0.55% 0xffffa4e1cb40\n 0.54% 0xffffa4e1cb74\n 0.52% 0xffffa4e1cb8c\n + 10.96% _start\n* patch:\n- 80.82% 12.25% postgres postgres [.] CopyOneRowTo\n - 68.57% CopyOneRowTo\n + 36.55% OutputFunctionCall\n 11.44% CopyAttributeOutText\n + 8.87% appendBinaryStringInfo\n + 3.79% CopySendEndOfRow\n 1.01% pgstat_progress_update_param\n 0.79% int2out\n 0.66% MemoryContextReset\n 0.63% 0xffffaa624ba8\n 0.60% memcpy@plt\n 0.60% enlargeStringInfo\n 0.53% 0xffffaa624ba4\n + 12.25% _start\n\nThat's a performance-only change, but there may be a good argument for\nbackpatching something, perhaps?\n--\nMichael",
"msg_date": "Thu, 8 Feb 2024 16:05:39 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: confusing / inefficient \"need_transcoding\" handling in copy"
},
{
"msg_contents": "Hi,\n\nIn <20240206222445.hzq22pb2nye7rm67@awork3.anarazel.de>\n \"Re: confusing / inefficient \"need_transcoding\" handling in copy\" on Tue, 6 Feb 2024 14:24:45 -0800,\n Andres Freund <andres@anarazel.de> wrote:\n\n> One unfortunate issue: We don't have any tests verifying that COPY FROM\n> catches encoding issues.\n\nHow about the attached patch for it?\n\n\nHow about the following to avoid needless transcoding?\n\n----\ndiff --git a/src/backend/commands/copyto.c b/src/backend/commands/copyto.c\nindex bd4710a79b..80ec26cafe 100644\n--- a/src/backend/commands/copyto.c\n+++ b/src/backend/commands/copyto.c\n@@ -612,13 +612,14 @@ BeginCopyTo(ParseState *pstate,\n \t\tcstate->file_encoding = cstate->opts.file_encoding;\n \n \t/*\n-\t * Set up encoding conversion info. Even if the file and server encodings\n-\t * are the same, we must apply pg_any_to_server() to validate data in\n-\t * multibyte encodings.\n+\t * Set up encoding conversion info. We use pg_server_to_any() for the\n+\t * conversion. pg_server_to_any() does nothing with an encoding that\n+\t * equals to GetDatabaseEncoding() and PG_SQL_ASCII. If\n+\t * cstate->file_encoding equals to GetDatabaseEncoding() and PG_SQL_ASCII,\n+\t * we don't need to transcode.\n \t */\n-\tcstate->need_transcoding =\n-\t\t(cstate->file_encoding != GetDatabaseEncoding() ||\n-\t\t pg_database_encoding_max_length() > 1);\n+\tcstate->need_transcoding = !(cstate->file_encoding == GetDatabaseEncoding() ||\n+\t\t\t\t\t\t\t\t cstate->file_encoding == PG_SQL_ASCII);\n \t/* See Multibyte encoding comment above */\n \tcstate->encoding_embeds_ascii = PG_ENCODING_IS_CLIENT_ONLY(cstate->file_encoding);\n \n----\n\nNumbers on my environment:\n\nmaster: 861.646ms\npatched: 697.547ms\n\nSQL:\nCOPY (SELECT 1::int2,2::int2,3::int2,4::int2,5::int2,6::int2,7::int2,8::int2,9::int2,10::int2,11::int2,12::int2,13::int2,14::int2,15::int2,16::int2,17::int2,18::int2,19::int2,20::int2, generate_series(1, 1000000::int4)) TO '/dev/null' \\watch c=5\n\n\nThanks,\n-- \nkou",
"msg_date": "Thu, 08 Feb 2024 17:25:01 +0900 (JST)",
"msg_from": "Sutou Kouhei <kou@clear-code.com>",
"msg_from_op": false,
"msg_subject": "Re: confusing / inefficient \"need_transcoding\" handling in copy"
},
{
"msg_contents": "On 08/02/2024 09:05, Michael Paquier wrote:\n> On Tue, Feb 06, 2024 at 02:24:45PM -0800, Andres Freund wrote:\n>> I think the code is just very confusing - there actually *is* verification of\n>> the encoding, it just happens at a different, earlier, layer, namely in\n>> copyfromparse.c: CopyConvertBuf() which says:\n>> \t/*\n>> \t * If the file and server encoding are the same, no encoding conversion is\n>> \t * required. However, we still need to verify that the input is valid for\n>> \t * the encoding.\n>> \t */\n>>\n>> And does indeed verify that.\n> \n> This has been switched by Heikki in f82de5c46bdf, in 2021, that has\n> removed pg_database_encoding_max_length() in the COPY FROM case.\n> (Adding him now in CC, in case he has any comments).\n\nYeah, I agree the \"pg_database_encoding_max_length() > 1\" check in COPY \nTO is unnecessary. It's always been like that, but now that the COPY TO \nand COPY FROM cases don't share the code, it's more obvious. Let's \nremove it.\n\nOn your patch:\n\n> +\t * Set up encoding conversion info, validating data if server and\n> +\t * client encodings are not the same (see also pg_server_to_any).\n\nThere's no validation, just conversion. I'd suggest:\n\n\"Set up encoding conversion info if the file and server encodings differ \n(see also pg_server_to_any).\"\n\nOther than that, +1\n\n> That's a performance-only change, but there may be a good argument for\n> backpatching something, perhaps?\n\n-1 for backpatching, out of principle. This is not a regression, it's \nalways been like that. Seems innocent, but why is this different from \nany other performance improvement we make.\n\n\nBTW, I can see an optimization opportunity even if the encodings differ: \nCurrently, CopyAttributeOutText() calls pg_server_to_any(), and then \ngrovels through the string to find any characters that need to be \nquoted. You could do it the other way round and handle quoting before \nthe conversion. That has two benefits:\n\n1. You don't need the strlen() call, because you just scanned through \nthe string so you already know its length.\n2. You don't need to worry about 'encoding_embeds_ascii' when you \noperate on the server encoding.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Thu, 8 Feb 2024 10:25:07 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: confusing / inefficient \"need_transcoding\" handling in copy"
},
{
"msg_contents": "Hi,\n\nIn <20240208.172501.2177371292839763981.kou@clear-code.com>\n \"Re: confusing / inefficient \"need_transcoding\" handling in copy\" on Thu, 08 Feb 2024 17:25:01 +0900 (JST),\n Sutou Kouhei <kou@clear-code.com> wrote:\n\n> How about the following to avoid needless transcoding?\n\nOh, sorry. I missed the Michael's patch:\nhttps://www.postgresql.org/message-id/flat/ZcR9Q9hJ8GedFSCd%40paquier.xyz#e73272b042a22befac7a95f7bcb4fb9a\n\nI withdraw my change.\n\n\nThanks,\n-- \nkou\n\n\n",
"msg_date": "Thu, 08 Feb 2024 17:29:46 +0900 (JST)",
"msg_from": "Sutou Kouhei <kou@clear-code.com>",
"msg_from_op": false,
"msg_subject": "Re: confusing / inefficient \"need_transcoding\" handling in copy"
},
{
"msg_contents": "On Thu, Feb 08, 2024 at 05:29:46PM +0900, Sutou Kouhei wrote:\n> Oh, sorry. I missed the Michael's patch:\n> https://www.postgresql.org/message-id/flat/ZcR9Q9hJ8GedFSCd%40paquier.xyz#e73272b042a22befac7a95f7bcb4fb9a\n> \n> I withdraw my change.\n\nNo problem. Thanks for caring about that.\n--\nMichael",
"msg_date": "Fri, 9 Feb 2024 08:33:52 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: confusing / inefficient \"need_transcoding\" handling in copy"
},
{
"msg_contents": "On Thu, Feb 08, 2024 at 10:25:07AM +0200, Heikki Linnakangas wrote:\n> There's no validation, just conversion. I'd suggest:\n> \n> \"Set up encoding conversion info if the file and server encodings differ\n> (see also pg_server_to_any).\"\n> \n> Other than that, +1\n\nCool. I've used your wording and applied that on HEAD.\n\n> BTW, I can see an optimization opportunity even if the encodings differ:\n> Currently, CopyAttributeOutText() calls pg_server_to_any(), and then grovels\n> through the string to find any characters that need to be quoted. You could\n> do it the other way round and handle quoting before the conversion. That has\n> two benefits:\n> \n> 1. You don't need the strlen() call, because you just scanned through the\n> string so you already know its length.\n> 2. You don't need to worry about 'encoding_embeds_ascii' when you operate on\n> the server encoding.\n\nThat sounds right, still it looks like there would be cases where\nyou'd need the strlen() call if !encoding_embeds_ascii.\n--\nMichael",
"msg_date": "Fri, 9 Feb 2024 09:36:28 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: confusing / inefficient \"need_transcoding\" handling in copy"
},
{
"msg_contents": "Hi,\n\nOn 2024-02-09 09:36:28 +0900, Michael Paquier wrote:\n> On Thu, Feb 08, 2024 at 10:25:07AM +0200, Heikki Linnakangas wrote:\n> > There's no validation, just conversion. I'd suggest:\n> > \n> > \"Set up encoding conversion info if the file and server encodings differ\n> > (see also pg_server_to_any).\"\n> > \n> > Other than that, +1\n> \n> Cool. I've used your wording and applied that on HEAD.\n\nThanks. LGTM.\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Thu, 8 Feb 2024 16:43:07 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": true,
"msg_subject": "Re: confusing / inefficient \"need_transcoding\" handling in copy"
},
{
"msg_contents": "On Thu, Feb 08, 2024 at 05:25:01PM +0900, Sutou Kouhei wrote:\n> In <20240206222445.hzq22pb2nye7rm67@awork3.anarazel.de>\n> \"Re: confusing / inefficient \"need_transcoding\" handling in copy\" on Tue, 6 Feb 2024 14:24:45 -0800,\n> Andres Freund <andres@anarazel.de> wrote:\n> \n>> One unfortunate issue: We don't have any tests verifying that COPY FROM\n>> catches encoding issues.\n> \n> How about the attached patch for it?\n>\n> +CREATE TABLE test (t text);\n> +COPY test FROM stdin WITH (ENCODING 'EUC_JP');\n> +こんにちは\n> +\\.\n> +\n> +DROP TABLE test;\n\nWe have a couple of non-ASCII characters in the tests, but I suspect\nthat this one will not be digested correctly everywhere, even if\nEUC_JP should be OK to use for the check. How about writing an\narbitrary sequence of bytes into a temporary file that gets used for \nthe COPY FROM instead? See for example how we do that with\nabs_builddir in copy.sql.\n--\nMichael",
"msg_date": "Wed, 14 Feb 2024 06:56:16 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: confusing / inefficient \"need_transcoding\" handling in copy"
},
{
"msg_contents": "Hi,\n\nIn <ZcvlgMEjt3qY8eiL@paquier.xyz>\n \"Re: confusing / inefficient \"need_transcoding\" handling in copy\" on Wed, 14 Feb 2024 06:56:16 +0900,\n Michael Paquier <michael@paquier.xyz> wrote:\n\n> We have a couple of non-ASCII characters in the tests, but I suspect\n> that this one will not be digested correctly everywhere, even if\n> EUC_JP should be OK to use for the check. How about writing an\n> arbitrary sequence of bytes into a temporary file that gets used for \n> the COPY FROM instead? See for example how we do that with\n> abs_builddir in copy.sql.\n\nIt makes sense. How about the attached patch?\n\n\nThanks,\n-- \nkou",
"msg_date": "Wed, 14 Feb 2024 11:46:08 +0900 (JST)",
"msg_from": "Sutou Kouhei <kou@clear-code.com>",
"msg_from_op": false,
"msg_subject": "Re: confusing / inefficient \"need_transcoding\" handling in copy"
}
] |
[
{
"msg_contents": "Hi.\nthis commit [0] changes immutability of jsonb_path_query,\njsonb_path_query_first?\nIf so, it may change other functions also.\n\ndemo:\n\nbegin;\nSET LOCAL TIME ZONE 10.5;\nwith cte(s) as (select jsonb '\"2023-08-15 12:34:56 +05:30\"')\n\nselect jsonb_path_query(s,\n'$.timestamp_tz()')::text,'+10.5'::text,'timestamp_tz'::text from cte\nunion all\nselect jsonb_path_query(s, '$.time()')::text,'+10.5'::text, 'time'::text\nfrom cte\nunion all\nselect jsonb_path_query(s,\n'$.timestamp()')::text,'+10.5'::text,'timestamp'::text from cte\nunion all\nselect jsonb_path_query(s, '$.date()')::text,'+10.5'::text, 'date'::text\nfrom cte\nunion all\nselect jsonb_path_query(s, '$.time_tz()')::text,'+10.5'::text,\n'time_tz'::text from cte;\n\nSET LOCAL TIME ZONE -8;\nwith cte(s) as (select jsonb '\"2023-08-15 12:34:56 +05:30\"')\nselect jsonb_path_query(s,\n'$.timestamp_tz()')::text,'-8'::text,'timestamp_tz'::text from cte\nunion all\nselect jsonb_path_query(s, '$.time()')::text,'-8'::text, 'time'::text from\ncte\nunion all\nselect jsonb_path_query(s,\n'$.timestamp()')::text,'-8'::text,'timestamp'::text from cte\nunion all\nselect jsonb_path_query(s, '$.date()')::text,'-8'::text, 'date'::text from\ncte\nunion all\nselect jsonb_path_query(s, '$.time_tz()')::text,'-8'::text, 'time_tz'::text\nfrom cte;\ncommit;\n\n\n[0]\nhttps://git.postgresql.org/cgit/postgresql.git/commit/?id=66ea94e8e606529bb334515f388c62314956739e\n\nHi.this commit [0] changes immutability of jsonb_path_query, jsonb_path_query_first? If so, it may change other functions also.demo:begin;SET LOCAL TIME ZONE 10.5;with cte(s) as (select jsonb '\"2023-08-15 12:34:56 +05:30\"')select jsonb_path_query(s, '$.timestamp_tz()')::text,'+10.5'::text,'timestamp_tz'::text from cteunion allselect jsonb_path_query(s, '$.time()')::text,'+10.5'::text, 'time'::text from cteunion allselect jsonb_path_query(s, '$.timestamp()')::text,'+10.5'::text,'timestamp'::text from cteunion allselect jsonb_path_query(s, '$.date()')::text,'+10.5'::text, 'date'::text from cteunion allselect jsonb_path_query(s, '$.time_tz()')::text,'+10.5'::text, 'time_tz'::text from cte;SET LOCAL TIME ZONE -8;with cte(s) as (select jsonb '\"2023-08-15 12:34:56 +05:30\"')select jsonb_path_query(s, '$.timestamp_tz()')::text,'-8'::text,'timestamp_tz'::text from cteunion allselect jsonb_path_query(s, '$.time()')::text,'-8'::text, 'time'::text from cteunion allselect jsonb_path_query(s, '$.timestamp()')::text,'-8'::text,'timestamp'::text from cteunion allselect jsonb_path_query(s, '$.date()')::text,'-8'::text, 'date'::text from cteunion allselect jsonb_path_query(s, '$.time_tz()')::text,'-8'::text, 'time_tz'::text from cte;commit;[0] https://git.postgresql.org/cgit/postgresql.git/commit/?id=66ea94e8e606529bb334515f388c62314956739e",
"msg_date": "Tue, 6 Feb 2024 11:06:32 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": true,
"msg_subject": "recently added jsonpath method change jsonb_path_query,\n jsonb_path_query_first immutability"
},
{
"msg_contents": "On 2024-02-05 Mo 22:06, jian he wrote:\n>\n> Hi.\n> this commit [0] changes immutability of jsonb_path_query, \n> jsonb_path_query_first? If so, it may change other functions also.\n>\n> demo:\n>\n> begin;\n> SET LOCAL TIME ZONE 10.5;\n> with cte(s) as (select jsonb '\"2023-08-15 12:34:56 +05:30\"')\n>\n> select jsonb_path_query(s, \n> '$.timestamp_tz()')::text,'+10.5'::text,'timestamp_tz'::text from cte\n> union all\n> select jsonb_path_query(s, '$.time()')::text,'+10.5'::text, \n> 'time'::text from cte\n> union all\n> select jsonb_path_query(s, \n> '$.timestamp()')::text,'+10.5'::text,'timestamp'::text from cte\n> union all\n> select jsonb_path_query(s, '$.date()')::text,'+10.5'::text, \n> 'date'::text from cte\n> union all\n> select jsonb_path_query(s, '$.time_tz()')::text,'+10.5'::text, \n> 'time_tz'::text from cte;\n>\n> SET LOCAL TIME ZONE -8;\n> with cte(s) as (select jsonb '\"2023-08-15 12:34:56 +05:30\"')\n> select jsonb_path_query(s, \n> '$.timestamp_tz()')::text,'-8'::text,'timestamp_tz'::text from cte\n> union all\n> select jsonb_path_query(s, '$.time()')::text,'-8'::text, 'time'::text \n> from cte\n> union all\n> select jsonb_path_query(s, \n> '$.timestamp()')::text,'-8'::text,'timestamp'::text from cte\n> union all\n> select jsonb_path_query(s, '$.date()')::text,'-8'::text, 'date'::text \n> from cte\n> union all\n> select jsonb_path_query(s, '$.time_tz()')::text,'-8'::text, \n> 'time_tz'::text from cte;\n> commit;\n>\n>\n> [0] \n> https://git.postgresql.org/cgit/postgresql.git/commit/?id=66ea94e8e606529bb334515f388c62314956739e\n\n\nouch. Good catch. Clearly we need to filter these like we do for the \n.datetime() method.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB:https://www.enterprisedb.com\n\n\n\n\n\n\n\n\nOn 2024-02-05 Mo 22:06, jian he wrote:\n\n\n\n\n Hi.\n this commit [0] changes immutability of\n jsonb_path_query,\n jsonb_path_query_first?\n If so, it may change other functions also.\n \n demo:\n\n begin;\n SET LOCAL TIME ZONE 10.5;\n with cte(s) as (select jsonb '\"2023-08-15 12:34:56 +05:30\"')\n\n select jsonb_path_query(s,\n '$.timestamp_tz()')::text,'+10.5'::text,'timestamp_tz'::text\n from cte\n union all\n select jsonb_path_query(s, '$.time()')::text,'+10.5'::text,\n 'time'::text from cte\n union all\n select jsonb_path_query(s,\n '$.timestamp()')::text,'+10.5'::text,'timestamp'::text from\n cte\n union all\n select jsonb_path_query(s, '$.date()')::text,'+10.5'::text,\n 'date'::text from cte\n union all\n select jsonb_path_query(s, '$.time_tz()')::text,'+10.5'::text,\n 'time_tz'::text from cte;\n\n SET LOCAL TIME ZONE -8;\n with cte(s) as (select jsonb '\"2023-08-15 12:34:56 +05:30\"')\n select jsonb_path_query(s,\n '$.timestamp_tz()')::text,'-8'::text,'timestamp_tz'::text from\n cte\n union all\n select jsonb_path_query(s, '$.time()')::text,'-8'::text,\n 'time'::text from cte\n union all\n select jsonb_path_query(s,\n '$.timestamp()')::text,'-8'::text,'timestamp'::text from cte\n union all\n select jsonb_path_query(s, '$.date()')::text,'-8'::text,\n 'date'::text from cte\n union all\n select jsonb_path_query(s, '$.time_tz()')::text,'-8'::text,\n 'time_tz'::text from cte;\n commit;\n\n\n\n\n\n[0] https://git.postgresql.org/cgit/postgresql.git/commit/?id=66ea94e8e606529bb334515f388c62314956739e\n\n\n\n\n\nouch. Good catch. Clearly we need to filter these like we do for\n the .datetime() method.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com",
"msg_date": "Tue, 6 Feb 2024 06:55:36 -0500",
"msg_from": "Andrew Dunstan <andrew@dunslane.net>",
"msg_from_op": false,
"msg_subject": "Re: recently added jsonpath method change jsonb_path_query,\n jsonb_path_query_first immutability"
},
{
"msg_contents": "On Tue, Feb 6, 2024 at 5:25 PM Andrew Dunstan <andrew@dunslane.net> wrote:\n\n>\n> On 2024-02-05 Mo 22:06, jian he wrote:\n>\n>\n> Hi.\n> this commit [0] changes immutability of jsonb_path_query, jsonb_path_query_first?\n> If so, it may change other functions also.\n>\n>\nThanks for reporting Jian.\n\nAdded checkTimezoneIsUsedForCast() check where ever we are casting\ntimezoned to non-timezoned types and vice-versa.\n\nThanks\n\n\n>\n> demo:\n>\n> begin;\n> SET LOCAL TIME ZONE 10.5;\n> with cte(s) as (select jsonb '\"2023-08-15 12:34:56 +05:30\"')\n>\n> select jsonb_path_query(s,\n> '$.timestamp_tz()')::text,'+10.5'::text,'timestamp_tz'::text from cte\n> union all\n> select jsonb_path_query(s, '$.time()')::text,'+10.5'::text, 'time'::text\n> from cte\n> union all\n> select jsonb_path_query(s,\n> '$.timestamp()')::text,'+10.5'::text,'timestamp'::text from cte\n> union all\n> select jsonb_path_query(s, '$.date()')::text,'+10.5'::text, 'date'::text\n> from cte\n> union all\n> select jsonb_path_query(s, '$.time_tz()')::text,'+10.5'::text,\n> 'time_tz'::text from cte;\n>\n> SET LOCAL TIME ZONE -8;\n> with cte(s) as (select jsonb '\"2023-08-15 12:34:56 +05:30\"')\n> select jsonb_path_query(s,\n> '$.timestamp_tz()')::text,'-8'::text,'timestamp_tz'::text from cte\n> union all\n> select jsonb_path_query(s, '$.time()')::text,'-8'::text, 'time'::text from\n> cte\n> union all\n> select jsonb_path_query(s,\n> '$.timestamp()')::text,'-8'::text,'timestamp'::text from cte\n> union all\n> select jsonb_path_query(s, '$.date()')::text,'-8'::text, 'date'::text from\n> cte\n> union all\n> select jsonb_path_query(s, '$.time_tz()')::text,'-8'::text,\n> 'time_tz'::text from cte;\n> commit;\n>\n>\n> [0]\n> https://git.postgresql.org/cgit/postgresql.git/commit/?id=66ea94e8e606529bb334515f388c62314956739e\n>\n>\n> ouch. Good catch. Clearly we need to filter these like we do for the\n> .datetime() method.\n>\n>\n> cheers\n>\n>\n> andrew\n>\n> --\n> Andrew Dunstan\n> EDB: https://www.enterprisedb.com\n>\n>\n\n-- \nJeevan Chalke\n\n*Principal, ManagerProduct Development*\n\n\n\nedbpostgres.com",
"msg_date": "Wed, 7 Feb 2024 17:06:08 +0530",
"msg_from": "Jeevan Chalke <jeevan.chalke@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: recently added jsonpath method change jsonb_path_query,\n jsonb_path_query_first immutability"
},
{
"msg_contents": "On Wed, Feb 7, 2024 at 7:36 PM Jeevan Chalke\n<jeevan.chalke@enterprisedb.com> wrote:\n> Added checkTimezoneIsUsedForCast() check where ever we are casting timezoned to non-timezoned types and vice-versa.\n\nhttps://www.postgresql.org/docs/devel/functions-json.html\nabove Table 9.51. jsonpath Filter Expression Elements, the Note\nsection, do we also need to rephrase it?\n\n\n",
"msg_date": "Wed, 7 Feb 2024 23:43:16 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: recently added jsonpath method change jsonb_path_query,\n jsonb_path_query_first immutability"
},
{
"msg_contents": "On Wed, Feb 7, 2024 at 9:13 PM jian he <jian.universality@gmail.com> wrote:\n\n> On Wed, Feb 7, 2024 at 7:36 PM Jeevan Chalke\n> <jeevan.chalke@enterprisedb.com> wrote:\n> > Added checkTimezoneIsUsedForCast() check where ever we are casting\n> timezoned to non-timezoned types and vice-versa.\n>\n> https://www.postgresql.org/docs/devel/functions-json.html\n> above Table 9.51. jsonpath Filter Expression Elements, the Note\n> section, do we also need to rephrase it?\n>\n\nOK. Added a line for the same.\n\nThanks\n\n-- \nJeevan Chalke\n\n*Principal, ManagerProduct Development*\n\n\n\nedbpostgres.com",
"msg_date": "Thu, 8 Feb 2024 10:57:04 +0530",
"msg_from": "Jeevan Chalke <jeevan.chalke@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: recently added jsonpath method change jsonb_path_query,\n jsonb_path_query_first immutability"
},
{
"msg_contents": "On Thu, Feb 8, 2024 at 1:27 PM Jeevan Chalke\n<jeevan.chalke@enterprisedb.com> wrote:\n>\n>\n>\n> On Wed, Feb 7, 2024 at 9:13 PM jian he <jian.universality@gmail.com> wrote:\n>>\n>> On Wed, Feb 7, 2024 at 7:36 PM Jeevan Chalke\n>> <jeevan.chalke@enterprisedb.com> wrote:\n>> > Added checkTimezoneIsUsedForCast() check where ever we are casting timezoned to non-timezoned types and vice-versa.\n>>\n>> https://www.postgresql.org/docs/devel/functions-json.html\n>> above Table 9.51. jsonpath Filter Expression Elements, the Note\n>> section, do we also need to rephrase it?\n>\n>\n> OK. Added a line for the same.\n>\n\ndiff --git a/doc/src/sgml/func.sgml b/doc/src/sgml/func.sgml\nindex 6788ba8..37ae2d1 100644\n--- a/doc/src/sgml/func.sgml\n+++ b/doc/src/sgml/func.sgml\n@@ -18240,7 +18240,11 @@ ERROR: jsonpath member accessor can only be\napplied to an object\n <type>timestamptz</type>, and <type>time</type> to <type>timetz</type>.\n However, all but the first of these conversions depend on the current\n <xref linkend=\"guc-timezone\"/> setting, and thus can only be performed\n- within timezone-aware <type>jsonpath</type> functions.\n+ within timezone-aware <type>jsonpath</type> functions. Similarly, other\n+ date/time-related methods that convert string to the date/time types\n+ also do the casting and may involve the current\n+ <xref linkend=\"guc-timezone\"/>. To preserve the immutability, those can\n+ only be performed within timezone-aware <type>jsonpath</type> functions.\n </para>\n </note>\n\nmy proposed minor changes:\n- within timezone-aware <type>jsonpath</type> functions.\n+ within timezone-aware <type>jsonpath</type> functions. Similarly, other\n+ date/time-related methods that convert string to the date/time types\n+ also do the casting and may involve the current\n+ <xref linkend=\"guc-timezone\"/> setting. Those conversions can\n+ only be performed within timezone-aware <type>jsonpath</type> functions.\nI don't have a strong opinion, though.\n\n\n",
"msg_date": "Thu, 8 Feb 2024 16:52:00 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: recently added jsonpath method change jsonb_path_query,\n jsonb_path_query_first immutability"
},
{
"msg_contents": "On Thu, Feb 8, 2024 at 2:22 PM jian he <jian.universality@gmail.com> wrote:\n\n> On Thu, Feb 8, 2024 at 1:27 PM Jeevan Chalke\n> <jeevan.chalke@enterprisedb.com> wrote:\n> >\n> >\n> >\n> > On Wed, Feb 7, 2024 at 9:13 PM jian he <jian.universality@gmail.com>\n> wrote:\n> >>\n> >> On Wed, Feb 7, 2024 at 7:36 PM Jeevan Chalke\n> >> <jeevan.chalke@enterprisedb.com> wrote:\n> >> > Added checkTimezoneIsUsedForCast() check where ever we are casting\n> timezoned to non-timezoned types and vice-versa.\n> >>\n> >> https://www.postgresql.org/docs/devel/functions-json.html\n> >> above Table 9.51. jsonpath Filter Expression Elements, the Note\n> >> section, do we also need to rephrase it?\n> >\n> >\n> > OK. Added a line for the same.\n> >\n>\n> diff --git a/doc/src/sgml/func.sgml b/doc/src/sgml/func.sgml\n> index 6788ba8..37ae2d1 100644\n> --- a/doc/src/sgml/func.sgml\n> +++ b/doc/src/sgml/func.sgml\n> @@ -18240,7 +18240,11 @@ ERROR: jsonpath member accessor can only be\n> applied to an object\n> <type>timestamptz</type>, and <type>time</type> to\n> <type>timetz</type>.\n> However, all but the first of these conversions depend on the\n> current\n> <xref linkend=\"guc-timezone\"/> setting, and thus can only be\n> performed\n> - within timezone-aware <type>jsonpath</type> functions.\n> + within timezone-aware <type>jsonpath</type> functions. Similarly,\n> other\n> + date/time-related methods that convert string to the date/time types\n> + also do the casting and may involve the current\n> + <xref linkend=\"guc-timezone\"/>. To preserve the immutability,\n> those can\n> + only be performed within timezone-aware <type>jsonpath</type>\n> functions.\n> </para>\n> </note>\n>\n> my proposed minor changes:\n> - within timezone-aware <type>jsonpath</type> functions.\n> + within timezone-aware <type>jsonpath</type> functions. Similarly,\n> other\n> + date/time-related methods that convert string to the date/time types\n> + also do the casting and may involve the current\n> + <xref linkend=\"guc-timezone\"/> setting. Those conversions can\n> + only be performed within timezone-aware <type>jsonpath</type>\n> functions.\n> I don't have a strong opinion, though.\n>\n\nThat seems fine as well. Let's leave that to the committer.\n\n\nThanks\n-- \nJeevan Chalke\n\n*Principal, ManagerProduct Development*\n\n\n\nedbpostgres.com\n\nOn Thu, Feb 8, 2024 at 2:22 PM jian he <jian.universality@gmail.com> wrote:On Thu, Feb 8, 2024 at 1:27 PM Jeevan Chalke\n<jeevan.chalke@enterprisedb.com> wrote:\n>\n>\n>\n> On Wed, Feb 7, 2024 at 9:13 PM jian he <jian.universality@gmail.com> wrote:\n>>\n>> On Wed, Feb 7, 2024 at 7:36 PM Jeevan Chalke\n>> <jeevan.chalke@enterprisedb.com> wrote:\n>> > Added checkTimezoneIsUsedForCast() check where ever we are casting timezoned to non-timezoned types and vice-versa.\n>>\n>> https://www.postgresql.org/docs/devel/functions-json.html\n>> above Table 9.51. jsonpath Filter Expression Elements, the Note\n>> section, do we also need to rephrase it?\n>\n>\n> OK. Added a line for the same.\n>\n\ndiff --git a/doc/src/sgml/func.sgml b/doc/src/sgml/func.sgml\nindex 6788ba8..37ae2d1 100644\n--- a/doc/src/sgml/func.sgml\n+++ b/doc/src/sgml/func.sgml\n@@ -18240,7 +18240,11 @@ ERROR: jsonpath member accessor can only be\napplied to an object\n <type>timestamptz</type>, and <type>time</type> to <type>timetz</type>.\n However, all but the first of these conversions depend on the current\n <xref linkend=\"guc-timezone\"/> setting, and thus can only be performed\n- within timezone-aware <type>jsonpath</type> functions.\n+ within timezone-aware <type>jsonpath</type> functions. Similarly, other\n+ date/time-related methods that convert string to the date/time types\n+ also do the casting and may involve the current\n+ <xref linkend=\"guc-timezone\"/>. To preserve the immutability, those can\n+ only be performed within timezone-aware <type>jsonpath</type> functions.\n </para>\n </note>\n\nmy proposed minor changes:\n- within timezone-aware <type>jsonpath</type> functions.\n+ within timezone-aware <type>jsonpath</type> functions. Similarly, other\n+ date/time-related methods that convert string to the date/time types\n+ also do the casting and may involve the current\n+ <xref linkend=\"guc-timezone\"/> setting. Those conversions can\n+ only be performed within timezone-aware <type>jsonpath</type> functions.\nI don't have a strong opinion, though.\nThat seems fine as well. Let's leave that to the committer.Thanks-- Jeevan ChalkePrincipal, ManagerProduct Developmentedbpostgres.com",
"msg_date": "Fri, 9 Feb 2024 07:32:50 +0530",
"msg_from": "Jeevan Chalke <jeevan.chalke@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: recently added jsonpath method change jsonb_path_query,\n jsonb_path_query_first immutability"
},
{
"msg_contents": "On 2024-02-08 Th 21:02, Jeevan Chalke wrote:\n>\n>\n> On Thu, Feb 8, 2024 at 2:22 PM jian he <jian.universality@gmail.com> \n> wrote:\n>\n> On Thu, Feb 8, 2024 at 1:27 PM Jeevan Chalke\n> <jeevan.chalke@enterprisedb.com> wrote:\n> >\n> >\n> >\n> > On Wed, Feb 7, 2024 at 9:13 PM jian he\n> <jian.universality@gmail.com> wrote:\n> >>\n> >> On Wed, Feb 7, 2024 at 7:36 PM Jeevan Chalke\n> >> <jeevan.chalke@enterprisedb.com> wrote:\n> >> > Added checkTimezoneIsUsedForCast() check where ever we are\n> casting timezoned to non-timezoned types and vice-versa.\n> >>\n> >> https://www.postgresql.org/docs/devel/functions-json.html\n> >> above Table 9.51. jsonpath Filter Expression Elements, the Note\n> >> section, do we also need to rephrase it?\n> >\n> >\n> > OK. Added a line for the same.\n> >\n>\n> diff --git a/doc/src/sgml/func.sgml b/doc/src/sgml/func.sgml\n> index 6788ba8..37ae2d1 100644\n> --- a/doc/src/sgml/func.sgml\n> +++ b/doc/src/sgml/func.sgml\n> @@ -18240,7 +18240,11 @@ ERROR: jsonpath member accessor can only be\n> applied to an object\n> <type>timestamptz</type>, and <type>time</type> to\n> <type>timetz</type>.\n> However, all but the first of these conversions depend on\n> the current\n> <xref linkend=\"guc-timezone\"/> setting, and thus can only\n> be performed\n> - within timezone-aware <type>jsonpath</type> functions.\n> + within timezone-aware <type>jsonpath</type> functions. \n> Similarly, other\n> + date/time-related methods that convert string to the\n> date/time types\n> + also do the casting and may involve the current\n> + <xref linkend=\"guc-timezone\"/>. To preserve the\n> immutability, those can\n> + only be performed within timezone-aware\n> <type>jsonpath</type> functions.\n> </para>\n> </note>\n>\n> my proposed minor changes:\n> - within timezone-aware <type>jsonpath</type> functions.\n> + within timezone-aware <type>jsonpath</type> functions.\n> Similarly, other\n> + date/time-related methods that convert string to the\n> date/time types\n> + also do the casting and may involve the current\n> + <xref linkend=\"guc-timezone\"/> setting. Those conversions can\n> + only be performed within timezone-aware\n> <type>jsonpath</type> functions.\n> I don't have a strong opinion, though.\n>\n>\n> That seems fine as well. Let's leave that to the committer.\n>\nI edited slightly to my taste, and committed the patch. Thanks.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB:https://www.enterprisedb.com\n\n\n\n\n\n\n\n\nOn 2024-02-08 Th 21:02, Jeevan Chalke\n wrote:\n\n\n\n\n\n\n\n\nOn Thu, Feb 8, 2024 at\n 2:22 PM jian he <jian.universality@gmail.com>\n wrote:\n\nOn Thu, Feb 8, 2024 at\n 1:27 PM Jeevan Chalke\n <jeevan.chalke@enterprisedb.com>\n wrote:\n >\n >\n >\n > On Wed, Feb 7, 2024 at 9:13 PM jian he <jian.universality@gmail.com>\n wrote:\n >>\n >> On Wed, Feb 7, 2024 at 7:36 PM Jeevan Chalke\n >> <jeevan.chalke@enterprisedb.com>\n wrote:\n >> > Added checkTimezoneIsUsedForCast() check where\n ever we are casting timezoned to non-timezoned types and\n vice-versa.\n >>\n >> https://www.postgresql.org/docs/devel/functions-json.html\n >> above Table 9.51. jsonpath Filter Expression\n Elements, the Note\n >> section, do we also need to rephrase it?\n >\n >\n > OK. Added a line for the same.\n >\n\n diff --git a/doc/src/sgml/func.sgml b/doc/src/sgml/func.sgml\n index 6788ba8..37ae2d1 100644\n --- a/doc/src/sgml/func.sgml\n +++ b/doc/src/sgml/func.sgml\n @@ -18240,7 +18240,11 @@ ERROR: jsonpath member accessor\n can only be\n applied to an object\n <type>timestamptz</type>, and\n <type>time</type> to\n <type>timetz</type>.\n However, all but the first of these conversions\n depend on the current\n <xref linkend=\"guc-timezone\"/> setting, and\n thus can only be performed\n - within timezone-aware\n <type>jsonpath</type> functions.\n + within timezone-aware\n <type>jsonpath</type> functions. Similarly,\n other\n + date/time-related methods that convert string to the\n date/time types\n + also do the casting and may involve the current\n + <xref linkend=\"guc-timezone\"/>. To preserve\n the immutability, those can\n + only be performed within timezone-aware\n <type>jsonpath</type> functions.\n </para>\n </note>\n\n my proposed minor changes:\n - within timezone-aware\n <type>jsonpath</type> functions.\n + within timezone-aware\n <type>jsonpath</type> functions. Similarly,\n other\n + date/time-related methods that convert string to the\n date/time types\n + also do the casting and may involve the current\n + <xref linkend=\"guc-timezone\"/> setting. Those\n conversions can\n + only be performed within timezone-aware\n <type>jsonpath</type> functions.\n I don't have a strong opinion, though.\n\n\n\n\nThat seems fine as well. Let's leave that to the committer.\n\n\n\n\n\n\n\nI edited slightly to my taste, and committed the patch. Thanks.\n\n cheers\n\n andrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com",
"msg_date": "Sat, 10 Feb 2024 12:24:58 -0500",
"msg_from": "Andrew Dunstan <andrew@dunslane.net>",
"msg_from_op": false,
"msg_subject": "Re: recently added jsonpath method change jsonb_path_query,\n jsonb_path_query_first immutability"
},
{
"msg_contents": "On Sat, Feb 10, 2024 at 10:55 PM Andrew Dunstan <andrew@dunslane.net> wrote:\n\n>\n> On 2024-02-08 Th 21:02, Jeevan Chalke wrote:\n>\n>\n>\n> On Thu, Feb 8, 2024 at 2:22 PM jian he <jian.universality@gmail.com>\n> wrote:\n>\n>> On Thu, Feb 8, 2024 at 1:27 PM Jeevan Chalke\n>> <jeevan.chalke@enterprisedb.com> wrote:\n>> >\n>> >\n>> >\n>> > On Wed, Feb 7, 2024 at 9:13 PM jian he <jian.universality@gmail.com>\n>> wrote:\n>> >>\n>> >> On Wed, Feb 7, 2024 at 7:36 PM Jeevan Chalke\n>> >> <jeevan.chalke@enterprisedb.com> wrote:\n>> >> > Added checkTimezoneIsUsedForCast() check where ever we are casting\n>> timezoned to non-timezoned types and vice-versa.\n>> >>\n>> >> https://www.postgresql.org/docs/devel/functions-json.html\n>> >> above Table 9.51. jsonpath Filter Expression Elements, the Note\n>> >> section, do we also need to rephrase it?\n>> >\n>> >\n>> > OK. Added a line for the same.\n>> >\n>>\n>> diff --git a/doc/src/sgml/func.sgml b/doc/src/sgml/func.sgml\n>> index 6788ba8..37ae2d1 100644\n>> --- a/doc/src/sgml/func.sgml\n>> +++ b/doc/src/sgml/func.sgml\n>> @@ -18240,7 +18240,11 @@ ERROR: jsonpath member accessor can only be\n>> applied to an object\n>> <type>timestamptz</type>, and <type>time</type> to\n>> <type>timetz</type>.\n>> However, all but the first of these conversions depend on the\n>> current\n>> <xref linkend=\"guc-timezone\"/> setting, and thus can only be\n>> performed\n>> - within timezone-aware <type>jsonpath</type> functions.\n>> + within timezone-aware <type>jsonpath</type> functions. Similarly,\n>> other\n>> + date/time-related methods that convert string to the date/time\n>> types\n>> + also do the casting and may involve the current\n>> + <xref linkend=\"guc-timezone\"/>. To preserve the immutability,\n>> those can\n>> + only be performed within timezone-aware <type>jsonpath</type>\n>> functions.\n>> </para>\n>> </note>\n>>\n>> my proposed minor changes:\n>> - within timezone-aware <type>jsonpath</type> functions.\n>> + within timezone-aware <type>jsonpath</type> functions. Similarly,\n>> other\n>> + date/time-related methods that convert string to the date/time\n>> types\n>> + also do the casting and may involve the current\n>> + <xref linkend=\"guc-timezone\"/> setting. Those conversions can\n>> + only be performed within timezone-aware <type>jsonpath</type>\n>> functions.\n>> I don't have a strong opinion, though.\n>>\n>\n> That seems fine as well. Let's leave that to the committer.\n>\n> I edited slightly to my taste, and committed the patch. Thanks.\n>\n\nThank you, Andrew and Jian.\n\n\n>\n> cheers\n>\n>\n> andrew\n>\n> --\n> Andrew Dunstan\n> EDB: https://www.enterprisedb.com\n>\n>\n\n-- \nJeevan Chalke\n\n*Principal, ManagerProduct Development*\n\n\n\nedbpostgres.com\n\nOn Sat, Feb 10, 2024 at 10:55 PM Andrew Dunstan <andrew@dunslane.net> wrote:\n\n\n\nOn 2024-02-08 Th 21:02, Jeevan Chalke\n wrote:\n\n\n\n\n\n\n\nOn Thu, Feb 8, 2024 at\n 2:22 PM jian he <jian.universality@gmail.com>\n wrote:\n\nOn Thu, Feb 8, 2024 at\n 1:27 PM Jeevan Chalke\n <jeevan.chalke@enterprisedb.com>\n wrote:\n >\n >\n >\n > On Wed, Feb 7, 2024 at 9:13 PM jian he <jian.universality@gmail.com>\n wrote:\n >>\n >> On Wed, Feb 7, 2024 at 7:36 PM Jeevan Chalke\n >> <jeevan.chalke@enterprisedb.com>\n wrote:\n >> > Added checkTimezoneIsUsedForCast() check where\n ever we are casting timezoned to non-timezoned types and\n vice-versa.\n >>\n >> https://www.postgresql.org/docs/devel/functions-json.html\n >> above Table 9.51. jsonpath Filter Expression\n Elements, the Note\n >> section, do we also need to rephrase it?\n >\n >\n > OK. Added a line for the same.\n >\n\n diff --git a/doc/src/sgml/func.sgml b/doc/src/sgml/func.sgml\n index 6788ba8..37ae2d1 100644\n --- a/doc/src/sgml/func.sgml\n +++ b/doc/src/sgml/func.sgml\n @@ -18240,7 +18240,11 @@ ERROR: jsonpath member accessor\n can only be\n applied to an object\n <type>timestamptz</type>, and\n <type>time</type> to\n <type>timetz</type>.\n However, all but the first of these conversions\n depend on the current\n <xref linkend=\"guc-timezone\"/> setting, and\n thus can only be performed\n - within timezone-aware\n <type>jsonpath</type> functions.\n + within timezone-aware\n <type>jsonpath</type> functions. Similarly,\n other\n + date/time-related methods that convert string to the\n date/time types\n + also do the casting and may involve the current\n + <xref linkend=\"guc-timezone\"/>. To preserve\n the immutability, those can\n + only be performed within timezone-aware\n <type>jsonpath</type> functions.\n </para>\n </note>\n\n my proposed minor changes:\n - within timezone-aware\n <type>jsonpath</type> functions.\n + within timezone-aware\n <type>jsonpath</type> functions. Similarly,\n other\n + date/time-related methods that convert string to the\n date/time types\n + also do the casting and may involve the current\n + <xref linkend=\"guc-timezone\"/> setting. Those\n conversions can\n + only be performed within timezone-aware\n <type>jsonpath</type> functions.\n I don't have a strong opinion, though.\n\n\n\n\nThat seems fine as well. Let's leave that to the committer.\n\n\n\n\n\n\nI edited slightly to my taste, and committed the patch. Thanks.Thank you, Andrew and Jian. \n\n cheers\n\n andrew\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n-- Jeevan ChalkePrincipal, ManagerProduct Developmentedbpostgres.com",
"msg_date": "Tue, 13 Feb 2024 18:34:27 +0530",
"msg_from": "Jeevan Chalke <jeevan.chalke@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: recently added jsonpath method change jsonb_path_query,\n jsonb_path_query_first immutability"
}
] |
[
{
"msg_contents": "Hi,\r\n\r\nAttached is a draft of the 2024-02-08 release announcement. Please \r\nreview for accuracy and notable omissions.\r\n\r\nPlease provide any feedback no later than 2024-02-08 12:00 UTC (and \r\npreferably sooner).\r\n\r\nThanks,\r\n\r\nJonathan",
"msg_date": "Mon, 5 Feb 2024 23:43:39 -0500",
"msg_from": "\"Jonathan S. Katz\" <jkatz@postgresql.org>",
"msg_from_op": true,
"msg_subject": "2024-02-08 release announcement draft"
},
{
"msg_contents": "On Tue, Feb 6, 2024 at 12:43 PM Jonathan S. Katz <jkatz@postgresql.org> wrote:\n>\n> Hi,\n>\n> Attached is a draft of the 2024-02-08 release announcement. Please\n> review for accuracy and notable omissions.\n>\n> Please provide any feedback no later than 2024-02-08 12:00 UTC (and\n> preferably sooner).\n>\n\n* In PL/pgSQL, support SQL commands that are `CREATE FUNCTION`/`CREATE\nPROCEDURE`\nwith SQL-standard bodies.\n\nhttps://git.postgresql.org/cgit/postgresql.git/commit/?id=57b440ec115f57ff6e6a3f0df26063822e3123d2\nsays only for plpgsql routine or DO block.\n\n* Ensure initdb always uncomments `postgresql.conf` entries for the\n`lc_` family of parameters.\n\nmaybe `initdb`\n\n\n",
"msg_date": "Tue, 6 Feb 2024 16:19:56 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: 2024-02-08 release announcement draft"
},
{
"msg_contents": "On 2/6/24 3:19 AM, jian he wrote:\r\n> On Tue, Feb 6, 2024 at 12:43 PM Jonathan S. Katz <jkatz@postgresql.org> wrote:\r\n>>\r\n>> Hi,\r\n>>\r\n>> Attached is a draft of the 2024-02-08 release announcement. Please\r\n>> review for accuracy and notable omissions.\r\n>>\r\n>> Please provide any feedback no later than 2024-02-08 12:00 UTC (and\r\n>> preferably sooner).\r\n>>\r\n> \r\n> * In PL/pgSQL, support SQL commands that are `CREATE FUNCTION`/`CREATE\r\n> PROCEDURE`\r\n> with SQL-standard bodies.\r\n> \r\n> https://git.postgresql.org/cgit/postgresql.git/commit/?id=57b440ec115f57ff6e6a3f0df26063822e3123d2\r\n> says only for plpgsql routine or DO block.\r\n\r\nI had some trouble wordsmithing this, but the commit title is pretty \r\nclear to me so I opted for that.\r\n\r\n> * Ensure initdb always uncomments `postgresql.conf` entries for the\r\n> `lc_` family of parameters.\r\n> \r\n> maybe `initdb`\r\n\r\nI applied this change -- thanks!\r\n\r\nJonathan",
"msg_date": "Wed, 7 Feb 2024 23:53:52 -0500",
"msg_from": "\"Jonathan S. Katz\" <jkatz@postgresql.org>",
"msg_from_op": true,
"msg_subject": "Re: 2024-02-08 release announcement draft"
},
{
"msg_contents": "\"Jonathan S. Katz\" <jkatz@postgresql.org> writes:\n> On 2/6/24 3:19 AM, jian he wrote:\n>> On Tue, Feb 6, 2024 at 12:43 PM Jonathan S. Katz <jkatz@postgresql.org> wrote:\n>>> * In PL/pgSQL, support SQL commands that are `CREATE FUNCTION`/`CREATE\n>>> PROCEDURE` with SQL-standard bodies.\n\n>> https://git.postgresql.org/cgit/postgresql.git/commit/?id=57b440ec115f57ff6e6a3f0df26063822e3123d2\n>> says only for plpgsql routine or DO block.\n\n> I had some trouble wordsmithing this, but the commit title is pretty \n> clear to me so I opted for that.\n\nYour text seems fine to me. I'm confused about the objection here:\nexactly what uses of plpgsql aren't in a routine or DO block?\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Thu, 08 Feb 2024 00:17:59 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: 2024-02-08 release announcement draft"
},
{
"msg_contents": "On Thu, Feb 8, 2024 at 1:17 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> \"Jonathan S. Katz\" <jkatz@postgresql.org> writes:\n> > On 2/6/24 3:19 AM, jian he wrote:\n> >> On Tue, Feb 6, 2024 at 12:43 PM Jonathan S. Katz <jkatz@postgresql.org> wrote:\n> >>> * In PL/pgSQL, support SQL commands that are `CREATE FUNCTION`/`CREATE\n> >>> PROCEDURE` with SQL-standard bodies.\n>\n> >> https://git.postgresql.org/cgit/postgresql.git/commit/?id=57b440ec115f57ff6e6a3f0df26063822e3123d2\n> >> says only for plpgsql routine or DO block.\n>\n> > I had some trouble wordsmithing this, but the commit title is pretty\n> > clear to me so I opted for that.\n>\n> Your text seems fine to me. I'm confused about the objection here:\n> exactly what uses of plpgsql aren't in a routine or DO block?\n>\n> regards, tom lane\n\nI guess I was confused with cases like this\n`\ncreate function test1() returns int language plpgsql\nbegin atomic\nselect unique1 from tenk1 limit 1;\nend ;\n`\nlooking back, the original text seems fine.\n\n\n",
"msg_date": "Thu, 8 Feb 2024 20:34:56 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: 2024-02-08 release announcement draft"
},
{
"msg_contents": "jian he <jian.universality@gmail.com> writes:\n\n> On Thu, Feb 8, 2024 at 1:17 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>>\n>> \"Jonathan S. Katz\" <jkatz@postgresql.org> writes:\n>> > On 2/6/24 3:19 AM, jian he wrote:\n>> >> On Tue, Feb 6, 2024 at 12:43 PM Jonathan S. Katz <jkatz@postgresql.org> wrote:\n>> >>> * In PL/pgSQL, support SQL commands that are `CREATE FUNCTION`/`CREATE\n>> >>> PROCEDURE` with SQL-standard bodies.\n>>\n>> >> https://git.postgresql.org/cgit/postgresql.git/commit/?id=57b440ec115f57ff6e6a3f0df26063822e3123d2\n>> >> says only for plpgsql routine or DO block.\n>>\n>> > I had some trouble wordsmithing this, but the commit title is pretty\n>> > clear to me so I opted for that.\n>>\n>> Your text seems fine to me. I'm confused about the objection here:\n>> exactly what uses of plpgsql aren't in a routine or DO block?\n>>\n>> regards, tom lane\n>\n> I guess I was confused with cases like this\n> `\n> create function test1() returns int language plpgsql\n> begin atomic\n> select unique1 from tenk1 limit 1;\n> end ;\n> `\n> looking back, the original text seems fine.\n\nThe word \"routine\" is the SQL standard's common term for both functions\nand procedures.\n\n- ilmari\n\n\n",
"msg_date": "Thu, 08 Feb 2024 13:58:36 +0000",
"msg_from": "=?utf-8?Q?Dagfinn_Ilmari_Manns=C3=A5ker?= <ilmari@ilmari.org>",
"msg_from_op": false,
"msg_subject": "Re: 2024-02-08 release announcement draft"
}
] |
[
{
"msg_contents": "Hello hackers,\r\n\r\nJust like some of my colleagues I've been using Svace*\r\nand I think I've found a bug in src/common/rmtree.c .\r\n\r\nIn 64th line function returns false in case it couldn't open a directory,\r\nbut the memory, that have been allocated for char** dirnames is\r\nnot freed.\r\n\r\nThe patch that has a fix of this is attached and is based on the latest\r\nmaster code.\r\n\r\n* - https://svace.pages.ispras.ru/svace-website/en/\r\n\r\nKind regards,\r\nIan Ilyasov.",
"msg_date": "Tue, 6 Feb 2024 09:34:42 +0000",
"msg_from": "=?utf-8?B?0JjQu9GM0Y/RgdC+0LIg0K/QvQ==?= <ianilyasov@outlook.com>",
"msg_from_op": true,
"msg_subject": "Memory leak fix in rmtree.c"
},
{
"msg_contents": "> On 6 Feb 2024, at 10:34, Ильясов Ян <ianilyasov@outlook.com> wrote:\n\n> Just like some of my colleagues I've been using Svace*\n> and I think I've found a bug in src/common/rmtree.c .\n> \n> In 64th line function returns false in case it couldn't open a directory,\n> but the memory, that have been allocated for char** dirnames is\n> not freed.\n\ndirnames isn't allocated at this point, it's palloc'd after this return\nstatement on line 67.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Tue, 6 Feb 2024 10:40:27 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: Memory leak fix in rmtree.c"
},
{
"msg_contents": "> dirnames isn't allocated at this point, it's palloc'd after this return\n> statement on line 67.\n>\n> --\n> Daniel Gustafsson\n\nI am sorry, I pointed on the wrong branch. I see that in master\nit is really in line 67th , and the allocation goes well. But in\nREL_16_STABLE the allocation is in line 58th and my patch is for this branch only.\n\nKind regards,\nIan Ilyasov.\n\n\n\n\n\n\n\n\n\n\n\n\n> dirnames isn't allocated at this point, it's palloc'd after this return\n> statement on line 67.\n> \n> --\n> Daniel Gustafsson\n\n\n\nI am sorry, I pointed on the wrong branch. I see that in master\n\nit is really in line 67th , and the allocation goes well. But in\n\nREL_16_STABLE the allocation is in line 58th and my patch is for this branch only.\n\n\n\n\nKind regards,\nIan Ilyasov.",
"msg_date": "Tue, 6 Feb 2024 10:21:53 +0000",
"msg_from": "=?koi8-r?B?6czY0dPP1yDxzg==?= <ianilyasov@outlook.com>",
"msg_from_op": false,
"msg_subject": "RE: Memory leak fix in rmtree.c"
},
{
"msg_contents": "> On 6 Feb 2024, at 11:21, Ильясов Ян <ianilyasov@outlook.com> wrote:\n> \n> > dirnames isn't allocated at this point, it's palloc'd after this return\n> > statement on line 67.\n> \n> I am sorry, I pointed on the wrong branch. I see that in master\n> it is really in line 67th , and the allocation goes well. But in\n> REL_16_STABLE the allocation is in line 58th and my patch is for this branch only.\n\nOk, that makes more sense. That was changed in commit f1e9f6bbfa53, and in the\ndiscussion for that patch it was deemed that no callers actually suffered from\nthe leak as they were exiting (or erroring out) on error, so it was never back-\npatched.\n\n https://www.postgresql.org/message-id/flat/CAEudQAoN3-2ZKBALThnEk_q2hu8En5A0WG9O%2B5siJTQKVZzoWQ%40mail.gmail.com\n\nThat still holds true today, so I don't see a big incentive to spend energy on\nbackpatching that since it mainly serves to silence analyzers. Grepping for\nthe pattern of allocating in the declaration doesn't reveal any other codepaths\nwhere the allocation leaks like this.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Tue, 6 Feb 2024 11:46:40 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: Memory leak fix in rmtree.c"
},
{
"msg_contents": "I agree with your argument.\nThank you for your time.\n\n\nKind regards,\nIan Ilyasov\n\nJuniour Software Developer at Postgres Professional\n\n\n\n\n\n\n\n\n\nI agree with your argument.\nThank you for your time.\n\n\n\n\n\n\n\nKind regards,\n\nIan Ilyasov\n\n\n\n\nJuniour Software Developer at Postgres Professional",
"msg_date": "Tue, 6 Feb 2024 11:45:31 +0000",
"msg_from": "=?koi8-r?B?6czY0dPP1yDxzg==?= <ianilyasov@outlook.com>",
"msg_from_op": false,
"msg_subject": "RE: Memory leak fix in rmtree.c"
},
{
"msg_contents": "> On 6 Feb 2024, at 12:45, Ильясов Ян <ianilyasov@outlook.com> wrote:\n> \n> I agree with your argument.\n> Thank you for your time.\n\nThank you for your report!\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Tue, 6 Feb 2024 12:58:50 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: Memory leak fix in rmtree.c"
}
] |
[
{
"msg_contents": "I'm proposing here a way to pass extra options to initdb when run \ninternally during test setup in pg_regress or \nPostgreSQL::Test::Cluster's init (which covers just about all test \nsuites other than initdb's own tests).\n\nFor example:\n\n make check PG_TEST_INITDB_EXTRA_OPTS='-k -c work_mem=50MB'\n\nWe currently document at [0] a way to pass custom server settings to the \ntests via PGOPTIONS. But this only works for pg_regress and only for \noptions that can be changed at run time. My proposal can set initdb \noptions, and since initdb has the -c option now, it can set any GUC \nparameter as well.\n\nI think this can be useful for a wide variety of uses, like running all \ntests with checksums enabled, or with JIT enabled, or with different GUC \nsettings, or with different locale settings. (The existing pg_regress \n--no-locale option is essentially a special case of this, but it only \nprovides one particular locale setting, not things like changing the \ndefault provider etc.)\n\nOf course, not all tests are going to pass with arbitrary options, but \nit is useful to run this against specific test suites.\n\nThis patch also updates the documentation at [0] to explain the new \nmethod and distinguish it from the previously documented methods.\n\n\n[0]: \nhttps://www.postgresql.org/docs/devel/regress-run.html#REGRESS-RUN-CUSTOM-SETTINGS",
"msg_date": "Tue, 6 Feb 2024 11:54:39 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Allow passing extra options to initdb for tests"
},
{
"msg_contents": "2024年2月6日(火) 19:54 Peter Eisentraut <peter@eisentraut.org>:\n>\n> I'm proposing here a way to pass extra options to initdb when run\n> internally during test setup in pg_regress or\n> PostgreSQL::Test::Cluster's init (which covers just about all test\n> suites other than initdb's own tests).\n>\n> For example:\n>\n> make check PG_TEST_INITDB_EXTRA_OPTS='-k -c work_mem=50MB'\n>\n> We currently document at [0] a way to pass custom server settings to the\n> tests via PGOPTIONS. But this only works for pg_regress and only for\n> options that can be changed at run time. My proposal can set initdb\n> options, and since initdb has the -c option now, it can set any GUC\n> parameter as well.\n>\n> I think this can be useful for a wide variety of uses, like running all\n> tests with checksums enabled, or with JIT enabled, or with different GUC\n> settings, or with different locale settings. (The existing pg_regress\n> --no-locale option is essentially a special case of this, but it only\n> provides one particular locale setting, not things like changing the\n> default provider etc.)\n>\n> Of course, not all tests are going to pass with arbitrary options, but\n> it is useful to run this against specific test suites.\n>\n> This patch also updates the documentation at [0] to explain the new\n> method and distinguish it from the previously documented methods.\n\n+1 for this, I recently ran into an issue with the regression tests for an\nextension where it would have been very useful to provide some initdb\noptions.\n\nPatch works as expected after a quick initial test.\n\nRegards\n\nIan Barwick\n\n\n",
"msg_date": "Wed, 7 Feb 2024 12:51:06 +0900",
"msg_from": "Ian Lawrence Barwick <barwick@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Allow passing extra options to initdb for tests"
},
{
"msg_contents": "2024年2月7日(水) 12:51 Ian Lawrence Barwick <barwick@gmail.com>:\n>\n> 2024年2月6日(火) 19:54 Peter Eisentraut <peter@eisentraut.org>:\n> >\n> > I'm proposing here a way to pass extra options to initdb when run\n> > internally during test setup in pg_regress or\n> > PostgreSQL::Test::Cluster's init (which covers just about all test\n> > suites other than initdb's own tests).\n> >\n> > For example:\n> >\n> > make check PG_TEST_INITDB_EXTRA_OPTS='-k -c work_mem=50MB'\n> >\n> > We currently document at [0] a way to pass custom server settings to the\n> > tests via PGOPTIONS. But this only works for pg_regress and only for\n> > options that can be changed at run time. My proposal can set initdb\n> > options, and since initdb has the -c option now, it can set any GUC\n> > parameter as well.\n> >\n> > I think this can be useful for a wide variety of uses, like running all\n> > tests with checksums enabled, or with JIT enabled, or with different GUC\n> > settings, or with different locale settings. (The existing pg_regress\n> > --no-locale option is essentially a special case of this, but it only\n> > provides one particular locale setting, not things like changing the\n> > default provider etc.)\n> >\n> > Of course, not all tests are going to pass with arbitrary options, but\n> > it is useful to run this against specific test suites.\n> >\n> > This patch also updates the documentation at [0] to explain the new\n> > method and distinguish it from the previously documented methods.\n>\n> +1 for this, I recently ran into an issue with the regression tests for an\n> extension where it would have been very useful to provide some initdb\n> options.\n>\n> Patch works as expected after a quick initial test.\n\nI had a longer look at this and can't find any issues with the code or\ndocumentation changes.\n\nI did wonder whether it would be worth mentioning that any initdb\noptions set in \"PG_TEST_INITDB_EXTRA_OPTS\" will override those\nwhich can be set by pg_regress, but of the four (\"--no-clean\", \"--no-sync\",\n\"--debug\" and \"--no-locale\"), only the optional \"--no-locale\" can actually\nbe overridden, so it doesn't seem important.\n\nRegards\n\nIan Barwick\n\n\n",
"msg_date": "Wed, 14 Feb 2024 14:22:10 +0900",
"msg_from": "Ian Lawrence Barwick <barwick@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Allow passing extra options to initdb for tests"
},
{
"msg_contents": "On Tue, Feb 6, 2024 at 4:24 PM Peter Eisentraut <peter@eisentraut.org> wrote:\n> I think this can be useful for a wide variety of uses, like running all\n> tests with checksums enabled, or with JIT enabled, or with different GUC\n> settings, or with different locale settings. (The existing pg_regress\n> --no-locale option is essentially a special case of this, but it only\n> provides one particular locale setting, not things like changing the\n> default provider etc.)\n>\n> Of course, not all tests are going to pass with arbitrary options, but\n> it is useful to run this against specific test suites.\n\n+1.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n",
"msg_date": "Wed, 14 Feb 2024 13:20:19 +0530",
"msg_from": "Robert Haas <robertmhaas@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Allow passing extra options to initdb for tests"
},
{
"msg_contents": "On 14.02.24 06:22, Ian Lawrence Barwick wrote:\n> I had a longer look at this and can't find any issues with the code or\n> documentation changes.\n\nThanks, committed.\n\n> I did wonder whether it would be worth mentioning that any initdb\n> options set in \"PG_TEST_INITDB_EXTRA_OPTS\" will override those\n> which can be set by pg_regress, but of the four (\"--no-clean\", \"--no-sync\",\n> \"--debug\" and \"--no-locale\"), only the optional \"--no-locale\" can actually\n> be overridden, so it doesn't seem important.\n\nI thought about this. We don't have a man page for pg_regress, so there \nis no place to comprehensively document all the options and their \ninteractions. The documentation in regress.sgml works on a makefile \nlevel. AFAICT, the --debug option is not exposed via the makefiles at \nall, while --no-locale can be requested by the environment variable \nNOLOCALE, but that is not documented, and also not ported to meson. I \nthink if you want tweaks on this level, there is some expectations right \nnow that you might need to study the source code a bit.\n\nOne thing that might be interesting would be to allow running initdb \nwithout the --no-sync option, to exercise fsync a bit. But there is no \n\"--yes-sync\" option to override --no-sync, otherwise you could do it \nwith the just-committed feature.\n\n\n\n",
"msg_date": "Thu, 15 Feb 2024 11:38:54 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: Allow passing extra options to initdb for tests"
},
{
"msg_contents": "> On 15 Feb 2024, at 11:38, Peter Eisentraut <peter@eisentraut.org> wrote:\n\n> We don't have a man page for pg_regress, so there is no place to comprehensively document all the options and their interactions.\n\nThis comes up every now and again, just yesterday there was a question on\n-general [0] about alternate output files which also are undocumented. Maybe\nit's time to add documentation for pg_regress?\n\n--\nDaniel Gustafsson\n\n[0] CACX+KaPOzzRHEt4w_=iqKbTpMKjyrUGVng1C749yP3r6dprtcg@mail.gmail.com\n\n",
"msg_date": "Thu, 15 Feb 2024 11:45:15 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: Allow passing extra options to initdb for tests"
},
{
"msg_contents": "Daniel Gustafsson <daniel@yesql.se> writes:\n> On 15 Feb 2024, at 11:38, Peter Eisentraut <peter@eisentraut.org> wrote:\n>> We don't have a man page for pg_regress, so there is no place to comprehensively document all the options and their interactions.\n\n> This comes up every now and again, just yesterday there was a question on\n> -general [0] about alternate output files which also are\n> undocumented.\n\nReally?\n\nhttps://www.postgresql.org/docs/devel/regress-variant.html\n\n> Maybe it's time to add documentation for pg_regress?\n\nI'm inclined to think that a formal man page wouldn't be that useful,\nsince nobody ever invokes pg_regress directly; as Peter says, what\nis of interest is the \"make check\" targets and the corresponding meson\nbehaviors. I think 32.1 is already reasonably thorough about the\nmake targets; but the complete lack of equivalent info about what\nto do in a meson build clearly needs to be rectified.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Thu, 15 Feb 2024 10:21:35 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Allow passing extra options to initdb for tests"
},
{
"msg_contents": "> On 15 Feb 2024, at 16:21, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Daniel Gustafsson <daniel@yesql.se> writes:\n>> On 15 Feb 2024, at 11:38, Peter Eisentraut <peter@eisentraut.org> wrote:\n>>> We don't have a man page for pg_regress, so there is no place to comprehensively document all the options and their interactions.\n> \n>> This comes up every now and again, just yesterday there was a question on\n>> -general [0] about alternate output files which also are\n>> undocumented.\n> \n> Really?\n> \n> https://www.postgresql.org/docs/devel/regress-variant.html\n\nDoh, I missed that when looking.\n\n>> Maybe it's time to add documentation for pg_regress?\n> \n> I'm inclined to think that a formal man page wouldn't be that useful,\n> since nobody ever invokes pg_regress directly;\n\nRight, I was mostly thinking of a chapter along the lines of \"I am an extension\nauthor, what features does this tool have to help me write good tests\".\n\n> the complete lack of equivalent info about what\n> to do in a meson build clearly needs to be rectified.\n\nIndeed.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Fri, 16 Feb 2024 10:25:25 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: Allow passing extra options to initdb for tests"
}
] |
[
{
"msg_contents": "In a recent patch thread it was discussed[0] which fields should be \ncompared by equalTupleDescs() and whether it is ok to remove a field \nfrom tuple descriptors and how that should affect their equality \n(attstattarget in that case).\n\nAfter analyzing all the callers, I have noticed that there are two \nclasses of callers of equalTupleDescs():\n\nThe first want to compare what I call row-type equality, which means \nthey want to check specifically for equal number of attributes, and the \nsame attribute names, types, and typmods for each attribute. Most \ncallers actually want that behavior. The remaining callers just want to \ncompare the tuple descriptors as they are, they don't care why the \nfields are in there, they just want to compare all of them.\n\nIn the attached patch, I add a new function equalRowTypes() that is \neffectively a subset of equalTupleDescs() and switch most callers to that.\n\nThe purpose of this patch is to make the semantics less uncertain. \nQuestions like the one in [0] about attstattarget now have a clear \nanswer for both functions. I think this would be useful to have, as we \nare thinking about more changes in pg_attribute and tuple descriptors.\n\n\n[0]: \nhttps://www.postgresql.org/message-id/202401101316.k4s3fomwjx52@alvherre.pgsql",
"msg_date": "Tue, 6 Feb 2024 13:59:18 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "clarify equalTupleDescs()"
},
{
"msg_contents": "Peter Eisentraut <peter@eisentraut.org> writes:\n> The first want to compare what I call row-type equality, which means \n> they want to check specifically for equal number of attributes, and the \n> same attribute names, types, and typmods for each attribute. Most \n> callers actually want that behavior.\n\nShould compare attcollation too, no?\n\n+1 for the general idea, but it seems like \"row type equality\"\nmight still be a slightly fuzzy concept.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Tue, 06 Feb 2024 10:14:45 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: clarify equalTupleDescs()"
},
{
"msg_contents": "On Tue, Feb 6, 2024 at 8:59 PM Peter Eisentraut <peter@eisentraut.org> wrote:\n>\n> In a recent patch thread it was discussed[0] which fields should be\n> compared by equalTupleDescs() and whether it is ok to remove a field\n> from tuple descriptors and how that should affect their equality\n> (attstattarget in that case).\n>\n> After analyzing all the callers, I have noticed that there are two\n> classes of callers of equalTupleDescs():\n>\n> The first want to compare what I call row-type equality, which means\n> they want to check specifically for equal number of attributes, and the\n> same attribute names, types, and typmods for each attribute. Most\n> callers actually want that behavior. The remaining callers just want to\n> compare the tuple descriptors as they are, they don't care why the\n> fields are in there, they just want to compare all of them.\n>\n> In the attached patch, I add a new function equalRowTypes() that is\n> effectively a subset of equalTupleDescs() and switch most callers to that.\n>\n> The purpose of this patch is to make the semantics less uncertain.\n> Questions like the one in [0] about attstattarget now have a clear\n> answer for both functions. I think this would be useful to have, as we\n> are thinking about more changes in pg_attribute and tuple descriptors.\n>\n>\n> [0]:\n> https://www.postgresql.org/message-id/202401101316.k4s3fomwjx52@alvherre.pgsql\n\nfunction name record_type_typmod_hash imply that\nhashRowType should also hash atttypmod field?\n\nalso:\n\nbool\nequalRowTypes(TupleDesc tupdesc1, TupleDesc tupdesc2)\n{\nif (tupdesc1->natts != tupdesc2->natts)\nreturn false;\nif (tupdesc1->tdtypeid != tupdesc2->tdtypeid)\nreturn false;\n\nfor (int i = 0; i < tupdesc1->natts; i++)\n{\nForm_pg_attribute attr1 = TupleDescAttr(tupdesc1, i);\nForm_pg_attribute attr2 = TupleDescAttr(tupdesc2, i);\n\nif (strcmp(NameStr(attr1->attname), NameStr(attr2->attname)) != 0)\nreturn false;\nif (attr1->atttypid != attr2->atttypid)\nreturn false;\nif (attr1->atttypmod != attr2->atttypmod)\nreturn false;\n}\n\nreturn true;\n}\n\n/*\n * hashRowType\n *\n * If two tuple descriptors would be considered equal by equalRowTypes()\n * then their hash value will be equal according to this function.\n */\nuint32\nhashRowType(TupleDesc desc)\n{\nuint32 s;\nint i;\n\ns = hash_combine(0, hash_uint32(desc->natts));\ns = hash_combine(s, hash_uint32(desc->tdtypeid));\nfor (i = 0; i < desc->natts; ++i)\ns = hash_combine(s, hash_uint32(TupleDescAttr(desc, i)->atttypid));\n\nreturn s;\n}\n\nfrom the hashRowType comment, should we also hash attname and atttypmod?\n\n\n",
"msg_date": "Wed, 7 Feb 2024 11:06:57 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: clarify equalTupleDescs()"
},
{
"msg_contents": "On 07.02.24 04:06, jian he wrote:\n> /*\n> * hashRowType\n> *\n> * If two tuple descriptors would be considered equal by equalRowTypes()\n> * then their hash value will be equal according to this function.\n> */\n> uint32\n> hashRowType(TupleDesc desc)\n> {\n> uint32 s;\n> int i;\n> \n> s = hash_combine(0, hash_uint32(desc->natts));\n> s = hash_combine(s, hash_uint32(desc->tdtypeid));\n> for (i = 0; i < desc->natts; ++i)\n> s = hash_combine(s, hash_uint32(TupleDescAttr(desc, i)->atttypid));\n> \n> return s;\n> }\n> \n> from the hashRowType comment, should we also hash attname and atttypmod?\n\nIn principle, hashRowType() could process all the fields that \nequalRowTypes() does. But since it's only a hash function, it doesn't \nhave to be perfect. (This is also the case for the current \nhashTupleDesc().) I'm not sure where the best tradeoff is.\n\n\n",
"msg_date": "Mon, 12 Feb 2024 12:46:57 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: clarify equalTupleDescs()"
},
{
"msg_contents": "On 06.02.24 16:14, Tom Lane wrote:\n> Peter Eisentraut <peter@eisentraut.org> writes:\n>> The first want to compare what I call row-type equality, which means\n>> they want to check specifically for equal number of attributes, and the\n>> same attribute names, types, and typmods for each attribute. Most\n>> callers actually want that behavior.\n> \n> Should compare attcollation too, no?\n> \n> +1 for the general idea, but it seems like \"row type equality\"\n> might still be a slightly fuzzy concept.\n\nI did another pass across the callers to check what pg_attribute fields \nmight be relevant.\n\nCollation definitely needs to be added, certainly for plancache.c, maybe \nfor typcache.c, the other callers don't care.\n\nRecord types can have attisdropped fields, so it's probably good to \ncheck those.\n\nI'm suspicious about attndims. Maybe one could create a test case where \nrecord types differ only in that. Support for attndims throughout the \nsystem is weak, but maybe there is something to check there.\n\nOn a conceptual level, I figured pg_attribute rows can be divided up \ninto three categories:\n\n1. \"row type\" stuff: attname, atttypid, atttypmod, attndims, \nattisdropped, attcollation\n\n2. physical layout stuff: attlen, attcacheoff, attbyval, attalign\n\n3. table metadata stuff (everything else)\n\nIt's not perfect, and sometimes it's not clear whether these categories \ninform the implementation or the other way around, but I think it helps \nconceptualize it.",
"msg_date": "Mon, 12 Feb 2024 13:49:46 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: clarify equalTupleDescs()"
},
{
"msg_contents": "Peter Eisentraut <peter@eisentraut.org> writes:\n> On 06.02.24 16:14, Tom Lane wrote:\n>> +1 for the general idea, but it seems like \"row type equality\"\n>> might still be a slightly fuzzy concept.\n\n> I did another pass across the callers to check what pg_attribute fields \n> might be relevant.\n\n> Collation definitely needs to be added, certainly for plancache.c, maybe \n> for typcache.c, the other callers don't care.\n\n+1\n\n> Record types can have attisdropped fields, so it's probably good to \n> check those.\n\nYeah, good idea. (In most cases the attname comparison would catch\nthat, but we shouldn't rely on it.) In a perfect world maybe a\ndropped column should be invisible to this comparison, but we're\na very long way from being able to treat it that way.\n\n> I'm suspicious about attndims. Maybe one could create a test case where \n> record types differ only in that. Support for attndims throughout the \n> system is weak, but maybe there is something to check there.\n\nThere was a discussion last year[1] about removing attndims\naltogether, which still seems to me like possibly a good idea.\nSo I doubt we want to consider it as a core semantic field.\n\n> On a conceptual level, I figured pg_attribute rows can be divided up \n> into three categories:\n\n> 1. \"row type\" stuff: attname, atttypid, atttypmod, attndims, \n> attisdropped, attcollation\n\n> 2. physical layout stuff: attlen, attcacheoff, attbyval, attalign\n\nI recall some discussion about taking attcacheoff out of this data\nstructure too ...\n\n> 3. table metadata stuff (everything else)\n\n> It's not perfect, and sometimes it's not clear whether these categories \n> inform the implementation or the other way around, but I think it helps \n> conceptualize it.\n\nSure.\n\n\t\t\tregards, tom lane\n\n[1] https://www.postgresql.org/message-id/flat/ZD%2B14YZ4IUue8Rhi%40gendo.asyd.net\n\n\n",
"msg_date": "Mon, 12 Feb 2024 10:59:58 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: clarify equalTupleDescs()"
},
{
"msg_contents": "On Mon, Feb 12, 2024 at 7:47 PM Peter Eisentraut <peter@eisentraut.org> wrote:\n>\n>\n> In principle, hashRowType() could process all the fields that\n> equalRowTypes() does. But since it's only a hash function, it doesn't\n> have to be perfect. (This is also the case for the current\n> hashTupleDesc().) I'm not sure where the best tradeoff is.\n\nThat's where my confusion comes from.\nhashRowType is used in record_type_typmod_hash.\nrecord_type_typmod_hash is within assign_record_type_typmod.\n\nin assign_record_type_typmod:\n------------------------------------------------\nif (RecordCacheHash == NULL)\n{\n/* First time through: initialize the hash table */\nHASHCTL ctl;\nctl.keysize = sizeof(TupleDesc); /* just the pointer */\nctl.entrysize = sizeof(RecordCacheEntry);\nctl.hash = record_type_typmod_hash;\nctl.match = record_type_typmod_compare;\nRecordCacheHash = hash_create(\"Record information cache\", 64,\n &ctl,\n HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);\n/* Also make sure CacheMemoryContext exists */\nif (!CacheMemoryContext)\nCreateCacheMemoryContext();\n}\n/*\n* Find a hashtable entry for this tuple descriptor. We don't use\n* HASH_ENTER yet, because if it's missing, we need to make sure that all\n* the allocations succeed before we create the new entry.\n*/\nrecentry = (RecordCacheEntry *) hash_search(RecordCacheHash,\n&tupDesc,\nHASH_FIND, &found);\n------------------------------------------------\nbased on the comments in hash_create. The above hash_search function\nwould first use\nrecord_type_typmod_hash to find out candidate entries in a hash table\nthen use record_type_typmod_compare to compare the given tupDesc with\ncandidate entries.\n\nIs this how the hash_search in assign_record_type_typmod works?\n\nequalRowTypes processed more fields than hashRowType,\nhashRowType comments mentioned equalRowTypes,\nmaybe we should have some comments in hashRowType explaining why only\nhashing natts, tdtypeid, atttypid will be fine.\n\n\n",
"msg_date": "Tue, 27 Feb 2024 19:13:29 +0800",
"msg_from": "jian he <jian.universality@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: clarify equalTupleDescs()"
},
{
"msg_contents": "Hi,\n\nI looked at this patch today. I went through all the calls switched to\nequalRowTypes, and AFAIK all of them are correct - all the places\nswitched to equalRowTypes() only need the weaker checks.\n\nThere's only two places still calling equalTupleDescs() - relcache\ncertainly needs that, and so does the assert in execReplication().\n\n\nAs for attndims, I agree equalRowTypes() should not check that. We're\nnot really checking that anywhere, it'd be quite weird to start with it\nhere. Especially if the plan is to remove it entirely.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n",
"msg_date": "Wed, 13 Mar 2024 19:43:12 +0100",
"msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: clarify equalTupleDescs()"
},
{
"msg_contents": "\n\nOn 2/27/24 12:13, jian he wrote:\n> On Mon, Feb 12, 2024 at 7:47 PM Peter Eisentraut <peter@eisentraut.org> wrote:\n>>\n>>\n>> In principle, hashRowType() could process all the fields that\n>> equalRowTypes() does. But since it's only a hash function, it doesn't\n>> have to be perfect. (This is also the case for the current\n>> hashTupleDesc().) I'm not sure where the best tradeoff is.\n> \n> That's where my confusion comes from.\n> hashRowType is used in record_type_typmod_hash.\n> record_type_typmod_hash is within assign_record_type_typmod.\n>> in assign_record_type_typmod:\n> ------------------------------------------------\n> if (RecordCacheHash == NULL)\n> {\n> /* First time through: initialize the hash table */\n> HASHCTL ctl;\n> ctl.keysize = sizeof(TupleDesc); /* just the pointer */\n> ctl.entrysize = sizeof(RecordCacheEntry);\n> ctl.hash = record_type_typmod_hash;\n> ctl.match = record_type_typmod_compare;\n> RecordCacheHash = hash_create(\"Record information cache\", 64,\n> &ctl,\n> HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);\n> /* Also make sure CacheMemoryContext exists */\n> if (!CacheMemoryContext)\n> CreateCacheMemoryContext();\n> }\n> /*\n> * Find a hashtable entry for this tuple descriptor. We don't use\n> * HASH_ENTER yet, because if it's missing, we need to make sure that all\n> * the allocations succeed before we create the new entry.\n> */\n> recentry = (RecordCacheEntry *) hash_search(RecordCacheHash,\n> &tupDesc,\n> HASH_FIND, &found);\n> ------------------------------------------------\n> based on the comments in hash_create. The above hash_search function\n> would first use\n> record_type_typmod_hash to find out candidate entries in a hash table\n> then use record_type_typmod_compare to compare the given tupDesc with\n> candidate entries.\n> \n> Is this how the hash_search in assign_record_type_typmod works?\n> \n\nYes.\n\n> equalRowTypes processed more fields than hashRowType,\n> hashRowType comments mentioned equalRowTypes,\n> maybe we should have some comments in hashRowType explaining why only\n> hashing natts, tdtypeid, atttypid will be fine.\n> \n\nNot sure I understand what the confusion is - omitting fields with\nlittle entropy is not uncommon, and collisions are inherent to hash\ntables, and need to be handled anyway.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n",
"msg_date": "Wed, 13 Mar 2024 20:01:54 +0100",
"msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: clarify equalTupleDescs()"
},
{
"msg_contents": "On 13.03.24 19:43, Tomas Vondra wrote:\n> I looked at this patch today. I went through all the calls switched to\n> equalRowTypes, and AFAIK all of them are correct - all the places\n> switched to equalRowTypes() only need the weaker checks.\n> \n> There's only two places still calling equalTupleDescs() - relcache\n> certainly needs that, and so does the assert in execReplication().\n> \n> As for attndims, I agree equalRowTypes() should not check that. We're\n> not really checking that anywhere, it'd be quite weird to start with it\n> here. Especially if the plan is to remove it entirely.\n\nThanks for checking this again. I have committed the patch as it was \npresented then.\n\n\n\n",
"msg_date": "Sun, 17 Mar 2024 07:12:19 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: clarify equalTupleDescs()"
}
] |
[
{
"msg_contents": "Hi hackers,\n\nThere is a bug in glibc's qsort() algorithm that runs the risk of creating\nan out-of-bounds error if the comparison function is not transitive, for\nexample, if subtraction is used so that it can create an overflow.\n\nSee\nhttps://packetstormsecurity.com/files/176931/glibc-qsort-Out-Of-Bounds-Read-Write.html\n\nI checked the existing functions in the latest version of Postgres source\ncode and most are safe, but there were a few ones that could lead to\noverflow. I do not know if these can actually lead to problems, but better\nsafe than sorry, so I created a patch to fix those few cases and add a\ncomment to one case that was not clear that it could not overflow.\n\nBest wishes,\nMats Kindahl, Timescale",
"msg_date": "Tue, 6 Feb 2024 15:06:26 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "glibc qsort() vulnerability"
},
{
"msg_contents": "Mats Kindahl <mats@timescale.com> writes:\n> There is a bug in glibc's qsort() algorithm that runs the risk of creating\n> an out-of-bounds error if the comparison function is not transitive, for\n> example, if subtraction is used so that it can create an overflow.\n\nWe don't use glibc's qsort. Have you checked whether there's a\nproblem with the code we do use?\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Tue, 06 Feb 2024 10:11:16 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Tue, Feb 06, 2024 at 10:11:16AM -0500, Tom Lane wrote:\n> Mats Kindahl <mats@timescale.com> writes:\n>> There is a bug in glibc's qsort() algorithm that runs the risk of creating\n>> an out-of-bounds error if the comparison function is not transitive, for\n>> example, if subtraction is used so that it can create an overflow.\n> \n> We don't use glibc's qsort. Have you checked whether there's a\n> problem with the code we do use?\n\nOh, interesting. I didn't know that! As of commit 6edd2b4, we've used an\nin-tree qsort() for everything. port.h has the following line:\n\n\t#define qsort(a,b,c,d) pg_qsort(a,b,c,d)\n\nI see a handful of callers that use pg_qsort() directly, which IMO is odd.\nI would've expected that to be something different if I didn't know about\nthat macro. Maybe we should change those to qsort()...\n\nEven if the glibc issue doesn't apply to Postgres, I'm tempted to suggest\nthat we make it project policy that comparison functions must be\ntransitive. There might be no real issues today, but if we write all\ncomparison functions the way Mats is suggesting, it should be easier to\nreason about overflow risks.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 6 Feb 2024 14:53:05 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "Nathan Bossart <nathandbossart@gmail.com> writes:\n> Even if the glibc issue doesn't apply to Postgres, I'm tempted to suggest\n> that we make it project policy that comparison functions must be\n> transitive. There might be no real issues today, but if we write all\n> comparison functions the way Mats is suggesting, it should be easier to\n> reason about overflow risks.\n\nA comparison routine that is not is probably broken, agreed.\nI didn't look through the details of the patch --- I was more\ncurious whether we had a version of the qsort bug, because\nif we do, we should fix that too.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Tue, 06 Feb 2024 15:55:58 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Tue, Feb 06, 2024 at 03:55:58PM -0500, Tom Lane wrote:\n> A comparison routine that is not is probably broken, agreed.\n> I didn't look through the details of the patch --- I was more\n> curious whether we had a version of the qsort bug, because\n> if we do, we should fix that too.\n\n+1\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 6 Feb 2024 14:57:38 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Tue, Feb 6, 2024 at 4:11 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Mats Kindahl <mats@timescale.com> writes:\n> > There is a bug in glibc's qsort() algorithm that runs the risk of\n> creating\n> > an out-of-bounds error if the comparison function is not transitive, for\n> > example, if subtraction is used so that it can create an overflow.\n>\n> We don't use glibc's qsort. Have you checked whether there's a\n> problem with the code we do use?\n>\n\nInteresting. No, haven't checked. Will do that.\n\nBest wishes,\nMats Kindahl\n\n>\n> regards, tom lane\n>\n\nOn Tue, Feb 6, 2024 at 4:11 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:Mats Kindahl <mats@timescale.com> writes:\n> There is a bug in glibc's qsort() algorithm that runs the risk of creating\n> an out-of-bounds error if the comparison function is not transitive, for\n> example, if subtraction is used so that it can create an overflow.\n\nWe don't use glibc's qsort. Have you checked whether there's a\nproblem with the code we do use?Interesting. No, haven't checked. Will do that.Best wishes,Mats Kindahl \n\n regards, tom lane",
"msg_date": "Wed, 7 Feb 2024 10:01:58 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Tue, Feb 6, 2024 at 9:56 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Nathan Bossart <nathandbossart@gmail.com> writes:\n> > Even if the glibc issue doesn't apply to Postgres, I'm tempted to suggest\n> > that we make it project policy that comparison functions must be\n> > transitive. There might be no real issues today, but if we write all\n> > comparison functions the way Mats is suggesting, it should be easier to\n> > reason about overflow risks.\n>\n> A comparison routine that is not is probably broken, agreed.\n> I didn't look through the details of the patch --- I was more\n> curious whether we had a version of the qsort bug, because\n> if we do, we should fix that too.\n>\n\nThe patch basically removes the risk of overflow in three routines and just\nreturns -1, 0, or 1, and adds a comment in one.\n\nThe routines modified do a subtraction of int:s and return that, which can\ncause an overflow. This method is used for some int16 as well but since\nstandard conversions in C will perform the arithmetics in \"int\" precision,\nthis cannot overflow, so added a comment there. It might still be a good\nidea to follow the same pattern for the int16 routines, but since there is\nno bug there, I did not add them to the patch.\n\nBest wishes,\nMats Kindahl\n\n\n\n>\n> regards, tom lane\n>\n\nOn Tue, Feb 6, 2024 at 9:56 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:Nathan Bossart <nathandbossart@gmail.com> writes:\n> Even if the glibc issue doesn't apply to Postgres, I'm tempted to suggest\n> that we make it project policy that comparison functions must be\n> transitive. There might be no real issues today, but if we write all\n> comparison functions the way Mats is suggesting, it should be easier to\n> reason about overflow risks.\n\nA comparison routine that is not is probably broken, agreed.\nI didn't look through the details of the patch --- I was more\ncurious whether we had a version of the qsort bug, because\nif we do, we should fix that too.The patch basically removes the risk of overflow in three routines and just returns -1, 0, or 1, and adds a comment in one.The routines modified do a subtraction of int:s and return that, which can cause an overflow. This method is used for some int16 as well but since standard conversions in C will perform the arithmetics in \"int\" precision, this cannot overflow, so added a comment there. It might still be a good idea to follow the same pattern for the int16 routines, but since there is no bug there, I did not add them to the patch.Best wishes,Mats Kindahl \n\n regards, tom lane",
"msg_date": "Wed, 7 Feb 2024 10:09:58 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On 07/02/2024 11:09, Mats Kindahl wrote:\n> On Tue, Feb 6, 2024 at 9:56 PM Tom Lane <tgl@sss.pgh.pa.us \n> <mailto:tgl@sss.pgh.pa.us>> wrote:\n> \n> Nathan Bossart <nathandbossart@gmail.com\n> <mailto:nathandbossart@gmail.com>> writes:\n> > Even if the glibc issue doesn't apply to Postgres, I'm tempted to\n> suggest\n> > that we make it project policy that comparison functions must be\n> > transitive. There might be no real issues today, but if we write all\n> > comparison functions the way Mats is suggesting, it should be\n> easier to\n> > reason about overflow risks.\n> \n> A comparison routine that is not is probably broken, agreed.\n> I didn't look through the details of the patch --- I was more\n> curious whether we had a version of the qsort bug, because\n> if we do, we should fix that too.\n> \n> The patch basically removes the risk of overflow in three routines and \n> just returns -1, 0, or 1, and adds a comment in one.\n> \n> The routines modified do a subtraction of int:s and return that, which \n> can cause an overflow. This method is used for some int16 as well but \n> since standard conversions in C will perform the arithmetics in \"int\" \n> precision, this cannot overflow, so added a comment there. It might \n> still be a good idea to follow the same pattern for the int16 routines, \n> but since there is no bug there, I did not add them to the patch.\n\nDoesn't hurt to fix the comparison functions, and +1 on using the same \npattern everywhere.\n\nHowever, we use our qsort() with user-defined comparison functions, and \nwe cannot make any guarantees about what they might do. So we must \nensure that our qsort() doesn't overflow, no matter what the comparison \nfunction does.\n\nLooking at our ST_SORT(), it seems safe to me.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Wed, 7 Feb 2024 20:46:56 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Wed, Feb 07, 2024 at 08:46:56PM +0200, Heikki Linnakangas wrote:\n> Doesn't hurt to fix the comparison functions, and +1 on using the same\n> pattern everywhere.\n\nI attached a new version of the patch with some small adjustments. I\nhaven't looked through all in-tree qsort() comparators to see if any others\nneed to be adjusted, but we should definitely do so as part of this thread.\nMats, are you able to do this?\n\n> However, we use our qsort() with user-defined comparison functions, and we\n> cannot make any guarantees about what they might do. So we must ensure that\n> our qsort() doesn't overflow, no matter what the comparison function does.\n> \n> Looking at our ST_SORT(), it seems safe to me.\n\nCool.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Wed, 7 Feb 2024 14:56:00 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "Hi,\n\nOn 2024-02-07 20:46:56 +0200, Heikki Linnakangas wrote:\n> > The routines modified do a subtraction of int:s and return that, which\n> > can cause an overflow. This method is used for some int16 as well but\n> > since standard conversions in C will perform the arithmetics in \"int\"\n> > precision, this cannot overflow, so added a comment there. It might\n> > still be a good idea to follow the same pattern for the int16 routines,\n> > but since there is no bug there, I did not add them to the patch.\n>\n> Doesn't hurt to fix the comparison functions, and +1 on using the same\n> pattern everywhere.\n\nIt actually can hurt - the generated code will often be slower.\n\nE.g.\n#include <stdint.h>\n\nint cmp_sub(int16_t a, int16_t b) {\n return (int32_t) a - (int32_t) b;\n}\n\nint cmp_if(int16_t a, int16_t b) {\n if (a < b)\n return -1;\n if (a > b)\n return 1;\n return 0;\n}\n\nyields\n\ncmp_sub:\n movsx eax, di\n movsx esi, si\n sub eax, esi\n ret\ncmp_if:\n xor eax, eax\n cmp di, si\n mov edx, -1\n setg al\n cmovl eax, edx\n ret\n\nwith gcc -O3. With other compilers, e.g. msvc, the difference is considerably\nbigger, due to msvc for some reason not using cmov.\n\nSee https://godbolt.org/z/34qerPaPE for a few more details.\n\n\nNow, in most cases this won't matter, the sorting isn't performance\ncritical. But I don't think it's a good idea to standardize on a generally\nslower pattern.\n\nNot that that's a good test, but I did quickly benchmark [1] this with\nintarray. There's about a 10% difference in performance between using the\nexisting compASC() and one using\n\treturn (int64) *(const int32 *) a - (int64) *(const int32 *) b;\n\n\nPerhaps we could have a central helper for this somewhere?\n\nGreetings,\n\nAndres Freund\n\n\n[1]\n-- prep\nCREATE EXTENSION IF NOT EXISTS intarray;\nDROP TABLE IF EXISTS arrays_to_sort;\nCREATE TABLE arrays_to_sort AS SELECT array_shuffle(a) arr FROM (SELECT ARRAY(SELECT generate_series(1, 1000000)) a), generate_series(1, 10);\n-- bench\nSELECT (sort(arr))[1] FROM arrays_to_sort;\n\n\n",
"msg_date": "Wed, 7 Feb 2024 13:48:57 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Wed, Feb 07, 2024 at 01:48:57PM -0800, Andres Freund wrote:\n> Now, in most cases this won't matter, the sorting isn't performance\n> critical. But I don't think it's a good idea to standardize on a generally\n> slower pattern.\n> \n> Not that that's a good test, but I did quickly benchmark [1] this with\n> intarray. There's about a 10% difference in performance between using the\n> existing compASC() and one using\n> \treturn (int64) *(const int32 *) a - (int64) *(const int32 *) b;\n> \n> \n> Perhaps we could have a central helper for this somewhere?\n\nMaybe said helper could use __builtin_sub_overflow() and fall back to the\nslow \"if\" version only if absolutely necessary. The assembly for that\nlooks encouraging, but I still need to actually test it...\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Wed, 7 Feb 2024 16:21:24 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "Hi,\n\nOn 2024-02-07 16:21:24 -0600, Nathan Bossart wrote:\n> On Wed, Feb 07, 2024 at 01:48:57PM -0800, Andres Freund wrote:\n> > Now, in most cases this won't matter, the sorting isn't performance\n> > critical. But I don't think it's a good idea to standardize on a generally\n> > slower pattern.\n> > \n> > Not that that's a good test, but I did quickly benchmark [1] this with\n> > intarray. There's about a 10% difference in performance between using the\n> > existing compASC() and one using\n> > \treturn (int64) *(const int32 *) a - (int64) *(const int32 *) b;\n> > \n> > \n> > Perhaps we could have a central helper for this somewhere?\n> \n> Maybe said helper could use __builtin_sub_overflow() and fall back to the\n> slow \"if\" version only if absolutely necessary.\n\nI suspect that'll be worse code in the common case, given the cmov generated\nby gcc & clang for the typical branch-y formulation. But it's worth testing.\n\n\n> The assembly for that looks encouraging, but I still need to actually test\n> it...\n\nPossible. For 16bit upcasting to 32bit is clearly the best way. For 32 bit\nthat doesn't work, given the 32bit return, so we need something more.\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Wed, 7 Feb 2024 16:42:07 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Wed, Feb 07, 2024 at 04:42:07PM -0800, Andres Freund wrote:\n> On 2024-02-07 16:21:24 -0600, Nathan Bossart wrote:\n>> The assembly for that looks encouraging, but I still need to actually test\n>> it...\n> \n> Possible. For 16bit upcasting to 32bit is clearly the best way. For 32 bit\n> that doesn't work, given the 32bit return, so we need something more.\n\nFor the same compASC() test, I see an ~8.4% improvement with your int64\ncode and a ~3.4% improvement with this:\n\n int\n compASC(const void *a, const void *b)\n {\n int result;\n\n if (unlikely(pg_sub_s32_overflow(*(const int32 *) a,\n *(const int32 *) b,\n &result)))\n {\n if (*(const int32 *) a > *(const int32 *) b)\n return 1;\n if (*(const int32 *) a < *(const int32 *) b)\n return -1;\n return 0;\n }\n\n return result;\n }\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Wed, 7 Feb 2024 19:52:11 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "Hi,\n\nOn 2024-02-07 19:52:11 -0600, Nathan Bossart wrote:\n> On Wed, Feb 07, 2024 at 04:42:07PM -0800, Andres Freund wrote:\n> > On 2024-02-07 16:21:24 -0600, Nathan Bossart wrote:\n> >> The assembly for that looks encouraging, but I still need to actually test\n> >> it...\n> > \n> > Possible. For 16bit upcasting to 32bit is clearly the best way. For 32 bit\n> > that doesn't work, given the 32bit return, so we need something more.\n> \n> For the same compASC() test, I see an ~8.4% improvement with your int64\n> code\n\nJust to be clear, that code unfortuntely isn't correct, the return value is a\n32 bit integer, so the 64bit difference doesn't help. In contrast to the 16bit\ncase.\n\n\n> and a ~3.4% improvement with this:\n\nI guess that's still something.\n\nAnother branchless variant is (a > b) - (a < b). It seems to get a similar\nimprovement as the overflow-checking version.\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Wed, 7 Feb 2024 18:06:37 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Thu, Feb 8, 2024 at 3:06 PM Andres Freund <andres@anarazel.de> wrote:\n> On 2024-02-07 19:52:11 -0600, Nathan Bossart wrote:\n> > On Wed, Feb 07, 2024 at 04:42:07PM -0800, Andres Freund wrote:\n> > > On 2024-02-07 16:21:24 -0600, Nathan Bossart wrote:\n> > >> The assembly for that looks encouraging, but I still need to actually test\n> > >> it...\n> > >\n> > > Possible. For 16bit upcasting to 32bit is clearly the best way. For 32 bit\n> > > that doesn't work, given the 32bit return, so we need something more.\n> >\n> > For the same compASC() test, I see an ~8.4% improvement with your int64\n> > code\n>\n> Just to be clear, that code unfortuntely isn't correct, the return value is a\n> 32 bit integer, so the 64bit difference doesn't help. In contrast to the 16bit\n> case.\n\nPerhaps you could wrap it in a branch-free sign() function so you get\na narrow answer?\n\nhttps://stackoverflow.com/questions/14579920/fast-sign-of-integer-in-c\n\n\n",
"msg_date": "Thu, 8 Feb 2024 15:38:10 +1300",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Wed, Feb 07, 2024 at 06:06:37PM -0800, Andres Freund wrote:\n> Another branchless variant is (a > b) - (a < b). It seems to get a similar\n> improvement as the overflow-checking version.\n\nWell, that's certainly more elegant. I updated the patch to that approach\nfor now.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Wed, 7 Feb 2024 20:45:58 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Thu, Feb 8, 2024 at 3:38 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> Perhaps you could wrap it in a branch-free sign() function so you get\n> a narrow answer?\n>\n> https://stackoverflow.com/questions/14579920/fast-sign-of-integer-in-c\n\nAh, strike that, it is much like the suggested (a > b) - (a < b) but\nwith extra steps...\n\n\n",
"msg_date": "Thu, 8 Feb 2024 15:49:03 +1300",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Thu, Feb 08, 2024 at 03:49:03PM +1300, Thomas Munro wrote:\n> On Thu, Feb 8, 2024 at 3:38 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n>> Perhaps you could wrap it in a branch-free sign() function so you get\n>> a narrow answer?\n>>\n>> https://stackoverflow.com/questions/14579920/fast-sign-of-integer-in-c\n> \n> Ah, strike that, it is much like the suggested (a > b) - (a < b) but\n> with extra steps...\n\nYeah, https://godbolt.org/ indicates that the sign approach compiles to\n\n movsx rsi, esi\n movsx rdi, edi\n xor eax, eax\n sub rdi, rsi\n test rdi, rdi\n setg al\n shr rdi, 63\n sub eax, edi\n ret\n\nwhile the approach Andres suggested compiles to\n\n xor eax, eax\n cmp edi, esi\n setl dl\n setg al\n movzx edx, dl\n sub eax, edx\n ret\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Wed, 7 Feb 2024 20:56:20 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "Mats, I apologize for steamrolling a bit here. I'll take a step back into\na reviewer role.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Wed, 7 Feb 2024 21:08:26 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Wed, Feb 7, 2024 at 9:56 PM Nathan Bossart <nathandbossart@gmail.com>\nwrote:\n\n> On Wed, Feb 07, 2024 at 08:46:56PM +0200, Heikki Linnakangas wrote:\n> > Doesn't hurt to fix the comparison functions, and +1 on using the same\n> > pattern everywhere.\n>\n> I attached a new version of the patch with some small adjustments. I\n> haven't looked through all in-tree qsort() comparators to see if any others\n> need to be adjusted, but we should definitely do so as part of this thread.\n> Mats, are you able to do this?\n>\n\nSure, I checked them and the only ones remaining are those using int16.\nShall I modify those as well?\n\n\n> > However, we use our qsort() with user-defined comparison functions, and\n> we\n> > cannot make any guarantees about what they might do. So we must ensure\n> that\n> > our qsort() doesn't overflow, no matter what the comparison function\n> does.\n> >\n> > Looking at our ST_SORT(), it seems safe to me.\n>\n> Cool.\n>\n> --\n> Nathan Bossart\n> Amazon Web Services: https://aws.amazon.com\n>\n\nOn Wed, Feb 7, 2024 at 9:56 PM Nathan Bossart <nathandbossart@gmail.com> wrote:On Wed, Feb 07, 2024 at 08:46:56PM +0200, Heikki Linnakangas wrote:\n> Doesn't hurt to fix the comparison functions, and +1 on using the same\n> pattern everywhere.\n\nI attached a new version of the patch with some small adjustments. I\nhaven't looked through all in-tree qsort() comparators to see if any others\nneed to be adjusted, but we should definitely do so as part of this thread.\nMats, are you able to do this?Sure, I checked them and the only ones remaining are those using int16. Shall I modify those as well? \n> However, we use our qsort() with user-defined comparison functions, and we\n> cannot make any guarantees about what they might do. So we must ensure that\n> our qsort() doesn't overflow, no matter what the comparison function does.\n> \n> Looking at our ST_SORT(), it seems safe to me.\n\nCool.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Thu, 8 Feb 2024 12:01:22 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Thu, Feb 8, 2024 at 4:08 AM Nathan Bossart <nathandbossart@gmail.com>\nwrote:\n\n> Mats, I apologize for steamrolling a bit here. I'll take a step back into\n> a reviewer role.\n>\n\nNo worries. :)\n\n\n>\n> --\n> Nathan Bossart\n> Amazon Web Services: https://aws.amazon.com\n>\n\nOn Thu, Feb 8, 2024 at 4:08 AM Nathan Bossart <nathandbossart@gmail.com> wrote:Mats, I apologize for steamrolling a bit here. I'll take a step back into\na reviewer role.No worries. :) \n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Thu, 8 Feb 2024 12:06:23 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Thu, Feb 8, 2024 at 12:01 PM Mats Kindahl <mats@timescale.com> wrote:\n\n> On Wed, Feb 7, 2024 at 9:56 PM Nathan Bossart <nathandbossart@gmail.com>\n> wrote:\n>\n>> On Wed, Feb 07, 2024 at 08:46:56PM +0200, Heikki Linnakangas wrote:\n>> > Doesn't hurt to fix the comparison functions, and +1 on using the same\n>> > pattern everywhere.\n>>\n>> I attached a new version of the patch with some small adjustments. I\n>> haven't looked through all in-tree qsort() comparators to see if any\n>> others\n>> need to be adjusted, but we should definitely do so as part of this\n>> thread.\n>> Mats, are you able to do this?\n>>\n>\n> Sure, I checked them and the only ones remaining are those using int16.\n> Shall I modify those as well?\n>\n\nSeems your additional patch dealt with at least one of the cases.\n\n\n>\n>\n>> > However, we use our qsort() with user-defined comparison functions, and\n>> we\n>> > cannot make any guarantees about what they might do. So we must ensure\n>> that\n>> > our qsort() doesn't overflow, no matter what the comparison function\n>> does.\n>> >\n>> > Looking at our ST_SORT(), it seems safe to me.\n>>\n>> Cool.\n>>\n>> --\n>> Nathan Bossart\n>> Amazon Web Services: https://aws.amazon.com\n>>\n>\n\nOn Thu, Feb 8, 2024 at 12:01 PM Mats Kindahl <mats@timescale.com> wrote:On Wed, Feb 7, 2024 at 9:56 PM Nathan Bossart <nathandbossart@gmail.com> wrote:On Wed, Feb 07, 2024 at 08:46:56PM +0200, Heikki Linnakangas wrote:\n> Doesn't hurt to fix the comparison functions, and +1 on using the same\n> pattern everywhere.\n\nI attached a new version of the patch with some small adjustments. I\nhaven't looked through all in-tree qsort() comparators to see if any others\nneed to be adjusted, but we should definitely do so as part of this thread.\nMats, are you able to do this?Sure, I checked them and the only ones remaining are those using int16. Shall I modify those as well?Seems your additional patch dealt with at least one of the cases. \n> However, we use our qsort() with user-defined comparison functions, and we\n> cannot make any guarantees about what they might do. So we must ensure that\n> our qsort() doesn't overflow, no matter what the comparison function does.\n> \n> Looking at our ST_SORT(), it seems safe to me.\n\nCool.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Thu, 8 Feb 2024 12:31:14 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Thu, Feb 8, 2024 at 3:56 AM Nathan Bossart <nathandbossart@gmail.com>\nwrote:\n\n> On Thu, Feb 08, 2024 at 03:49:03PM +1300, Thomas Munro wrote:\n> > On Thu, Feb 8, 2024 at 3:38 PM Thomas Munro <thomas.munro@gmail.com>\n> wrote:\n> >> Perhaps you could wrap it in a branch-free sign() function so you get\n> >> a narrow answer?\n> >>\n> >> https://stackoverflow.com/questions/14579920/fast-sign-of-integer-in-c\n> >\n> > Ah, strike that, it is much like the suggested (a > b) - (a < b) but\n> > with extra steps...\n>\n> Yeah, https://godbolt.org/ indicates that the sign approach compiles to\n>\n> movsx rsi, esi\n> movsx rdi, edi\n> xor eax, eax\n> sub rdi, rsi\n> test rdi, rdi\n> setg al\n> shr rdi, 63\n> sub eax, edi\n> ret\n>\n> while the approach Andres suggested compiles to\n>\n> xor eax, eax\n> cmp edi, esi\n> setl dl\n> setg al\n> movzx edx, dl\n> sub eax, edx\n> ret\n>\n\nHere is a patch that fixes existing cases and introduces a macro for this\ncomparison (it uses the (a > b) - (a < b) approach). Not sure where to\nplace the macro nor what a suitable name should be, so feel free to suggest\nanything.\n\nI also noted that some functions are duplicated and it might be an idea to\nintroduce a few standard functions like pg_qsort_strcmp for, e.g., integers\nand other common types.\n\nAlso noted it is quite common to have this pattern in various places to do\nlexicographic sort of multiple values and continue the comparison if they\nare equal. Not sure if that is something we should look at.\n\nBest wishes,\nMats Kindahl\n\n>\n> --\n> Nathan Bossart\n> Amazon Web Services: https://aws.amazon.com\n>",
"msg_date": "Thu, 8 Feb 2024 14:16:11 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Thu, Feb 08, 2024 at 02:16:11PM +0100, Mats Kindahl wrote:\n> +/*\n> + * Compare two integers and return -1, 0, or 1 without risking overflow.\n> + *\n> + * This macro is used to avoid running into overflow issues because a simple\n> + * subtraction of the two values when implementing a cmp function for qsort().\n> +*/\n> +#define INT_CMP(lhs,rhs) (((lhs) > (rhs)) - ((lhs) < (rhs)))\n\nI think we should offer a few different macros, i.e., separate macros for\nint8, uint8, int16, uint16, int32, etc. For int16, we can do something\nfaster like\n\n\t(int32) (lhs) - (int32) (rhs)\n\nbut for int32, we need to do someting more like what's in the patch.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Thu, 8 Feb 2024 12:38:35 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "Nathan Bossart <nathandbossart@gmail.com> writes:\n> On Thu, Feb 08, 2024 at 02:16:11PM +0100, Mats Kindahl wrote:\n>> +/*\n>> + * Compare two integers and return -1, 0, or 1 without risking overflow.\n>> + *\n>> + * This macro is used to avoid running into overflow issues because a simple\n>> + * subtraction of the two values when implementing a cmp function for qsort().\n>> +*/\n>> +#define INT_CMP(lhs,rhs) (((lhs) > (rhs)) - ((lhs) < (rhs)))\n\n> I think we should offer a few different macros, i.e., separate macros for\n> int8, uint8, int16, uint16, int32, etc. For int16, we can do something\n> faster like\n\n> \t(int32) (lhs) - (int32) (rhs)\n\n> but for int32, we need to do someting more like what's in the patch.\n\nAre we okay with using macros that (a) have double evaluation hazards\nand (b) don't enforce the data types being compared are the same?\nI think static inlines might be a safer technology. Perhaps it's\nokay given the only expected use is in qsort comparators, but ...\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Thu, 08 Feb 2024 13:44:02 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "Hi,\n\nOn 2024-02-08 13:44:02 -0500, Tom Lane wrote:\n> Nathan Bossart <nathandbossart@gmail.com> writes:\n> > On Thu, Feb 08, 2024 at 02:16:11PM +0100, Mats Kindahl wrote:\n> >> +/*\n> >> + * Compare two integers and return -1, 0, or 1 without risking overflow.\n> >> + *\n> >> + * This macro is used to avoid running into overflow issues because a simple\n> >> + * subtraction of the two values when implementing a cmp function for qsort().\n> >> +*/\n> >> +#define INT_CMP(lhs,rhs) (((lhs) > (rhs)) - ((lhs) < (rhs)))\n>\n> > I think we should offer a few different macros, i.e., separate macros for\n> > int8, uint8, int16, uint16, int32, etc. For int16, we can do something\n> > faster like\n\n+1\n\n\n> > \t(int32) (lhs) - (int32) (rhs)\n>\n> > but for int32, we need to do someting more like what's in the patch.\n>\n> Are we okay with using macros that (a) have double evaluation hazards\n> and (b) don't enforce the data types being compared are the same?\n> I think static inlines might be a safer technology.\n\n+1\n\n\nI'd put these static inlines into common/int.h. I don't think this is common\nenough to warrant being in c.h. Probably also doesn't hurt to have a not quite\nas generic name as INT_CMP, I'd not be too surprised if that's defined in some\nlibrary.\n\n\nI think it's worth following int.h's pattern of including [s]igned/[u]nsigned\nin the name, an efficient implementation for signed might not be the same as\nfor unsigned. And if we use static inlines, we need to do so for correct\nsemantics anyway.\n\n\nGreetings,\n\nAndres\n\n\n",
"msg_date": "Thu, 8 Feb 2024 11:59:54 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Thu, Feb 08, 2024 at 11:59:54AM -0800, Andres Freund wrote:\n> On 2024-02-08 13:44:02 -0500, Tom Lane wrote:\n>> Are we okay with using macros that (a) have double evaluation hazards\n>> and (b) don't enforce the data types being compared are the same?\n>> I think static inlines might be a safer technology.\n> \n> +1\n\nAgreed on static inlines.\n\n> I'd put these static inlines into common/int.h. I don't think this is common\n> enough to warrant being in c.h. Probably also doesn't hurt to have a not quite\n> as generic name as INT_CMP, I'd not be too surprised if that's defined in some\n> library.\n> \n> \n> I think it's worth following int.h's pattern of including [s]igned/[u]nsigned\n> in the name, an efficient implementation for signed might not be the same as\n> for unsigned. And if we use static inlines, we need to do so for correct\n> semantics anyway.\n\nSeems reasonable to me.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Thu, 8 Feb 2024 14:07:37 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Thu, Feb 8, 2024 at 7:44 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Nathan Bossart <nathandbossart@gmail.com> writes:\n> > On Thu, Feb 08, 2024 at 02:16:11PM +0100, Mats Kindahl wrote:\n> >> +/*\n> >> + * Compare two integers and return -1, 0, or 1 without risking\n> overflow.\n> >> + *\n> >> + * This macro is used to avoid running into overflow issues because a\n> simple\n> >> + * subtraction of the two values when implementing a cmp function for\n> qsort().\n> >> +*/\n> >> +#define INT_CMP(lhs,rhs) (((lhs) > (rhs)) - ((lhs) < (rhs)))\n>\n> > I think we should offer a few different macros, i.e., separate macros for\n> > int8, uint8, int16, uint16, int32, etc. For int16, we can do something\n> > faster like\n>\n> > (int32) (lhs) - (int32) (rhs)\n>\n> > but for int32, we need to do someting more like what's in the patch.\n>\n> Are we okay with using macros that (a) have double evaluation hazards\n> and (b) don't enforce the data types being compared are the same?\n> I think static inlines might be a safer technology. Perhaps it's\n> okay given the only expected use is in qsort comparators, but ...\n>\n\nI picked a macro simply because it can deal with all kinds of integers, but\nif we want to have separate implementations for each then inline functions\nwork just as well and will be safer.\n\n Best wishes,\nMats Kindahl\n\n\n> regards, tom lane\n>\n\nOn Thu, Feb 8, 2024 at 7:44 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:Nathan Bossart <nathandbossart@gmail.com> writes:\n> On Thu, Feb 08, 2024 at 02:16:11PM +0100, Mats Kindahl wrote:\n>> +/*\n>> + * Compare two integers and return -1, 0, or 1 without risking overflow.\n>> + *\n>> + * This macro is used to avoid running into overflow issues because a simple\n>> + * subtraction of the two values when implementing a cmp function for qsort().\n>> +*/\n>> +#define INT_CMP(lhs,rhs) (((lhs) > (rhs)) - ((lhs) < (rhs)))\n\n> I think we should offer a few different macros, i.e., separate macros for\n> int8, uint8, int16, uint16, int32, etc. For int16, we can do something\n> faster like\n\n> (int32) (lhs) - (int32) (rhs)\n\n> but for int32, we need to do someting more like what's in the patch.\n\nAre we okay with using macros that (a) have double evaluation hazards\nand (b) don't enforce the data types being compared are the same?\nI think static inlines might be a safer technology. Perhaps it's\nokay given the only expected use is in qsort comparators, but ...I picked a macro simply because it can deal with all kinds of integers, but if we want to have separate implementations for each then inline functions work just as well and will be safer. Best wishes,Mats Kindahl\n\n regards, tom lane",
"msg_date": "Thu, 8 Feb 2024 21:34:07 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Thu, Feb 8, 2024 at 9:07 PM Nathan Bossart <nathandbossart@gmail.com>\nwrote:\n\n> On Thu, Feb 08, 2024 at 11:59:54AM -0800, Andres Freund wrote:\n> > On 2024-02-08 13:44:02 -0500, Tom Lane wrote:\n> >> Are we okay with using macros that (a) have double evaluation hazards\n> >> and (b) don't enforce the data types being compared are the same?\n> >> I think static inlines might be a safer technology.\n> >\n> > +1\n>\n> Agreed on static inlines.\n>\n\nSeems to be a general consensus on static inlines. I'll get a new patch.\n\n\n> > I'd put these static inlines into common/int.h. I don't think this is\n> common\n> > enough to warrant being in c.h. Probably also doesn't hurt to have a not\n> quite\n> > as generic name as INT_CMP, I'd not be too surprised if that's defined\n> in some\n> > library.\n> >\n> >\n> > I think it's worth following int.h's pattern of including\n> [s]igned/[u]nsigned\n> > in the name, an efficient implementation for signed might not be the\n> same as\n> > for unsigned. And if we use static inlines, we need to do so for correct\n> > semantics anyway.\n>\n> Seems reasonable to me.\n>\n\nAgree.\n\nBest wishes,\nMats Kindahl\n\n\n>\n> --\n> Nathan Bossart\n> Amazon Web Services: https://aws.amazon.com\n>\n\nOn Thu, Feb 8, 2024 at 9:07 PM Nathan Bossart <nathandbossart@gmail.com> wrote:On Thu, Feb 08, 2024 at 11:59:54AM -0800, Andres Freund wrote:\n> On 2024-02-08 13:44:02 -0500, Tom Lane wrote:\n>> Are we okay with using macros that (a) have double evaluation hazards\n>> and (b) don't enforce the data types being compared are the same?\n>> I think static inlines might be a safer technology.\n> \n> +1\n\nAgreed on static inlines.Seems to be a general consensus on static inlines. I'll get a new patch. \n> I'd put these static inlines into common/int.h. I don't think this is common\n> enough to warrant being in c.h. Probably also doesn't hurt to have a not quite\n> as generic name as INT_CMP, I'd not be too surprised if that's defined in some\n> library.\n> \n> \n> I think it's worth following int.h's pattern of including [s]igned/[u]nsigned\n> in the name, an efficient implementation for signed might not be the same as\n> for unsigned. And if we use static inlines, we need to do so for correct\n> semantics anyway.\n\nSeems reasonable to me.Agree.Best wishes,Mats Kindahl \n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Thu, 8 Feb 2024 21:35:56 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "Nathan Bossart <nathandbossart@gmail.com> writes:\n> On Thu, Feb 08, 2024 at 11:59:54AM -0800, Andres Freund wrote:\n>> I'd put these static inlines into common/int.h. I don't think this is common\n>> enough to warrant being in c.h. Probably also doesn't hurt to have a not quite\n>> as generic name as INT_CMP, I'd not be too surprised if that's defined in some\n>> library.\n>> \n>> I think it's worth following int.h's pattern of including [s]igned/[u]nsigned\n>> in the name, an efficient implementation for signed might not be the same as\n>> for unsigned. And if we use static inlines, we need to do so for correct\n>> semantics anyway.\n\n> Seems reasonable to me.\n\n+1 here also.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Thu, 08 Feb 2024 15:39:29 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Thu, Feb 8, 2024 at 9:39 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Nathan Bossart <nathandbossart@gmail.com> writes:\n> > On Thu, Feb 08, 2024 at 11:59:54AM -0800, Andres Freund wrote:\n> >> I'd put these static inlines into common/int.h. I don't think this is\n> common\n> >> enough to warrant being in c.h. Probably also doesn't hurt to have a\n> not quite\n> >> as generic name as INT_CMP, I'd not be too surprised if that's defined\n> in some\n> >> library.\n> >>\n> >> I think it's worth following int.h's pattern of including\n> [s]igned/[u]nsigned\n> >> in the name, an efficient implementation for signed might not be the\n> same as\n> >> for unsigned. And if we use static inlines, we need to do so for correct\n> >> semantics anyway.\n>\n> > Seems reasonable to me.\n>\n> +1 here also.\n>\n\nHere is a new version introducing pg_cmp_s32 and friends and use them\ninstead of the INT_CMP macro introduced before. It also moves the\ndefinitions to common/int.h and adds that as an include to all locations\nusing these functions.\n\nNote that for integers with sizes less than sizeof(int), C standard\nconversions will convert the values to \"int\" before doing the arithmetic,\nso no casting is *necessary*. I did not force the 16-bit functions to\nreturn -1 or 1 and have updated the comment accordingly.\n\nThe types \"int\" and \"size_t\" are treated as s32 and u32 respectively since\nthat seems to be the case for most of the code, even if strictly not\ncorrect (size_t can be an unsigned long int for some architecture).\n\nI also noted that in many situations size_t values are treated as \"int\" so\nthere is an overflow risk here, even if small. For example, the result of\n\"list_length\" is assigned to an integer. I do not think this is an\nimmediate concern, but just wanted to mention it.\n\nBest wishes,\nMats Kindahl\n\n>\n> regards, tom lane\n>",
"msg_date": "Fri, 9 Feb 2024 08:52:26 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "\n\n> On 8 Feb 2024, at 06:52, Nathan Bossart <nathandbossart@gmail.com> wrote:\n> \n> For the same compASC() test, I see an ~8.4% improvement with your int64\n> code and a ~3.4% improvement with this:\n\nIf we care about branch prediction in comparison function, maybe we could produce sorting that inlines comparator, thus eliminating function call to comparator? We convert comparison logic to int, to extract comparison back then.\n\nI bet “call\" is more expensive than “if\".\n\n\nBest regards, Andrey Borodin.\n\n",
"msg_date": "Fri, 9 Feb 2024 13:19:49 +0500",
"msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Fri, Feb 09, 2024 at 08:52:26AM +0100, Mats Kindahl wrote:\n> Here is a new version introducing pg_cmp_s32 and friends and use them\n> instead of the INT_CMP macro introduced before. It also moves the\n> definitions to common/int.h and adds that as an include to all locations\n> using these functions.\n\nThanks for the new version of the patch.\n\n> Note that for integers with sizes less than sizeof(int), C standard\n> conversions will convert the values to \"int\" before doing the arithmetic,\n> so no casting is *necessary*. I did not force the 16-bit functions to\n> return -1 or 1 and have updated the comment accordingly.\n\nIt might not be necessary, but this is one of those places where I would\nadd casting anyway to make it abundantly clear what we are expecting to\nhappen and why it is safe.\n\n> The types \"int\" and \"size_t\" are treated as s32 and u32 respectively since\n> that seems to be the case for most of the code, even if strictly not\n> correct (size_t can be an unsigned long int for some architecture).\n\nWhy is it safe to do this?\n\n> -\treturn ((const SPLITCOST *) a)->cost - ((const SPLITCOST *) b)->cost;\n> +\treturn INT_CMP(((const SPLITCOST *) a)->cost, ((const SPLITCOST *) b)->cost);\n\nThe patch still contains several calls to INT_CMP.\n\n> +/*------------------------------------------------------------------------\n> + * Comparison routines for integers\n> + *------------------------------------------------------------------------\n> + */\n\nI'd suggest separating this part out to a 0001 patch to make it easier to\nreview. The 0002 patch could take care of converting the existing qsort\ncomparators.\n\n> +static inline int\n> +pg_cmp_s16(int16 a, int16 b)\n> +{\n> +\treturn a - b;\n> +}\n> +\n> +static inline int\n> +pg_cmp_u16(uint16 a, uint16 b)\n> +{\n> +\treturn a - b;\n> +}\n> +\n> +static inline int\n> +pg_cmp_s32(int32 a, int32 b)\n> +{\n> +\treturn (a > b) - (a < b);\n> +}\n> +\n> +static inline int\n> +pg_cmp_u32(uint32 a, uint32 b)\n> +{\n> +\treturn (a > b) - (a < b);\n> +}\n> +\n> +static inline int\n> +pg_cmp_s64(int64 a, int64 b)\n> +{\n> +\treturn (a > b) - (a < b);\n> +}\n> +\n> +static inline int\n> +pg_cmp_u64(uint64 a, uint64 b)\n> +{\n> +\treturn (a > b) - (a < b);\n> +}\n\nAs suggested above, IMHO we should be rather liberal with the casting to\nensure it is abundantly clear what is happening here.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Fri, 9 Feb 2024 10:24:33 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "Nathan Bossart <nathandbossart@gmail.com> writes:\n> On Fri, Feb 09, 2024 at 08:52:26AM +0100, Mats Kindahl wrote:\n>> The types \"int\" and \"size_t\" are treated as s32 and u32 respectively since\n>> that seems to be the case for most of the code, even if strictly not\n>> correct (size_t can be an unsigned long int for some architecture).\n\n> Why is it safe to do this?\n\nWe do pretty much assume that \"int\" is \"int32\". But I agree that\nassuming anything about the width of size_t is bad. I think we need\na separate pg_cmp_size() or pg_cmp_size_t().\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Fri, 09 Feb 2024 11:27:28 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Fri, Feb 09, 2024 at 01:19:49PM +0500, Andrey M. Borodin wrote:\n> If we care about branch prediction in comparison function, maybe we could\n> produce sorting that inlines comparator, thus eliminating function call\n> to comparator? We convert comparison logic to int, to extract comparison\n> back then.\n> \n> I bet “call\" is more expensive than “if\".\n\nIt might make sense to have a couple of built-in qsort implementations for\npointers to integers, pointers to unsigned integers, etc. However, a lot\nof current use-cases require inspecting specific fields of structs, so\n(assuming I understand your proposal correctly), we'd end up with many\nqsort implementations. If that can be made simple and elegant and\ndemonstrates substantial improvements, then it might be worth considering,\nbut I'm somewhat skeptical that the current uses are performance-sensitive\nenough to be worth the effort.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Fri, 9 Feb 2024 10:32:45 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "Hi,\n\nOn 2024-02-09 13:19:49 +0500, Andrey M. Borodin wrote:\n> > On 8 Feb 2024, at 06:52, Nathan Bossart <nathandbossart@gmail.com> wrote:\n> > For the same compASC() test, I see an ~8.4% improvement with your int64\n> > code and a ~3.4% improvement with this:\n>\n> If we care about branch prediction in comparison function, maybe we could\n> produce sorting that inlines comparator, thus eliminating function call to\n> comparator? We convert comparison logic to int, to extract comparison back\n> then.\n\nWe have some infrastructure for that actually, see sort_template.h. But\nperhaps we should define a static inline of the generic pg_qsort() even. OTOH,\nplenty places that'll just end up to a pointless amount of code emitted to\nsort ~5 elements on average.\n\n\n> I bet “call\" is more expensive than “if\".\n\nNot really in this case. The call is perfectly predictable - a single qsort()\nwill use the same callback for every comparison, whereas the if is perfectly\n*unpredictable*. A branch mispredict is far more expensive than a correctly\npredicted function call.\n\nGreetings,\n\nAndres\n\n\n",
"msg_date": "Fri, 9 Feb 2024 10:40:14 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "\n\n> On 9 Feb 2024, at 21:32, Nathan Bossart <nathandbossart@gmail.com> wrote:\n> a lot\n> of current use-cases require inspecting specific fields of structs\nYes, I'm proposing to pass to sorting routine not a comparator, but value extractor. And then rely on operators <,>,==.\nIn a pseudocode: instead of sort(array, (a,b)->a.field-b.field) use sort(array, x->x.field). And rely on \"field\" being comparable.\n\n> If that can be made simple and elegant and\n> demonstrates substantial improvements\nI'll try to produce a PoC and measure it with Andres' intarray test.\n\n> On 9 Feb 2024, at 23:40, Andres Freund <andres@anarazel.de> wrote:\n> \n> We have some infrastructure for that actually, see sort_template.h. But\n> perhaps we should define a static inline of the generic pg_qsort() even. OTOH,\n> plenty places that'll just end up to a pointless amount of code emitted to\n> sort ~5 elements on average.\nI think there might be another benefit. It's easier to think about values order than function comparator that returns -1,0,+1...\n\n>> I bet “call\" is more expensive than “if\".\n> \n> Not really in this case. The call is perfectly predictable - a single qsort()\n> will use the same callback for every comparison, whereas the if is perfectly\n> *unpredictable*. A branch mispredict is far more expensive than a correctly\n> predicted function call.\n\nOh, make sense... I did not understand that. But does cpu predicts what instruction to fetch even after a call instruction? These cpus are really neat things... so, probably, yes, it does.\n\n\nBest regards, Andrey Borodin.\n\n",
"msg_date": "Sat, 10 Feb 2024 00:02:08 +0500",
"msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "Hi,\n\nOn 2024-02-10 00:02:08 +0500, Andrey Borodin wrote:\n> > Not really in this case. The call is perfectly predictable - a single qsort()\n> > will use the same callback for every comparison, whereas the if is perfectly\n> > *unpredictable*. A branch mispredict is far more expensive than a correctly\n> > predicted function call.\n> \n> Oh, make sense... I did not understand that. But does cpu predicts what\n> instruction to fetch even after a call instruction?\n\nYes, it does predict that. Both for branches and calls (which are just special\nkinds of branches in the end). If you want to find more about this, the term\nto search for is \"branch target buffer\". There's also predictions about where\na function return will jump to, since that obviously can differ.\n\nModern predictors aren't just taking the instruction pointer into account, to\npredict where a jump/call will go to. Tey take the history of recent branches\ninto account, i.e. the same instruction will be predicted to jump to different\nlocations, depending on where the current function was called from. This is\nimportant as a function obviously can behave very differently depending on the\ninput.\n\n\n> These cpus are really neat things...\n\nIndeed.\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Fri, 9 Feb 2024 11:24:23 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Fri, Feb 9, 2024 at 5:24 PM Nathan Bossart <nathandbossart@gmail.com>\nwrote:\n\n> On Fri, Feb 09, 2024 at 08:52:26AM +0100, Mats Kindahl wrote:\n> > Here is a new version introducing pg_cmp_s32 and friends and use them\n> > instead of the INT_CMP macro introduced before. It also moves the\n> > definitions to common/int.h and adds that as an include to all locations\n> > using these functions.\n>\n> Thanks for the new version of the patch.\n>\n> > Note that for integers with sizes less than sizeof(int), C standard\n> > conversions will convert the values to \"int\" before doing the arithmetic,\n> > so no casting is *necessary*. I did not force the 16-bit functions to\n> > return -1 or 1 and have updated the comment accordingly.\n>\n> It might not be necessary, but this is one of those places where I would\n> add casting anyway to make it abundantly clear what we are expecting to\n> happen and why it is safe.\n>\n\nI'll add it.\n\n\n> > The types \"int\" and \"size_t\" are treated as s32 and u32 respectively\n> since\n> > that seems to be the case for most of the code, even if strictly not\n> > correct (size_t can be an unsigned long int for some architecture).\n>\n> Why is it safe to do this?\n>\n> > - return ((const SPLITCOST *) a)->cost - ((const SPLITCOST *)\n> b)->cost;\n> > + return INT_CMP(((const SPLITCOST *) a)->cost, ((const SPLITCOST *)\n> b)->cost);\n>\n> The patch still contains several calls to INT_CMP.\n>\n\nI'll fix it.\n\n\n>\n> >\n> +/*------------------------------------------------------------------------\n> > + * Comparison routines for integers\n> > +\n> *------------------------------------------------------------------------\n> > + */\n>\n> I'd suggest separating this part out to a 0001 patch to make it easier to\n> review. The 0002 patch could take care of converting the existing qsort\n> comparators.\n>\n\nOk. Will split it out into two patches.\n\n\n>\n> > +static inline int\n> > +pg_cmp_s16(int16 a, int16 b)\n> > +{\n> > + return a - b;\n> > +}\n> > +\n> > +static inline int\n> > +pg_cmp_u16(uint16 a, uint16 b)\n> > +{\n> > + return a - b;\n> > +}\n> > +\n> > +static inline int\n> > +pg_cmp_s32(int32 a, int32 b)\n> > +{\n> > + return (a > b) - (a < b);\n> > +}\n> > +\n> > +static inline int\n> > +pg_cmp_u32(uint32 a, uint32 b)\n> > +{\n> > + return (a > b) - (a < b);\n> > +}\n> > +\n> > +static inline int\n> > +pg_cmp_s64(int64 a, int64 b)\n> > +{\n> > + return (a > b) - (a < b);\n> > +}\n> > +\n> > +static inline int\n> > +pg_cmp_u64(uint64 a, uint64 b)\n> > +{\n> > + return (a > b) - (a < b);\n> > +}\n>\n> As suggested above, IMHO we should be rather liberal with the casting to\n> ensure it is abundantly clear what is happening here.\n>\n\nOk.\n\n\n>\n> --\n> Nathan Bossart\n> Amazon Web Services: https://aws.amazon.com\n>\n\nOn Fri, Feb 9, 2024 at 5:24 PM Nathan Bossart <nathandbossart@gmail.com> wrote:On Fri, Feb 09, 2024 at 08:52:26AM +0100, Mats Kindahl wrote:\n> Here is a new version introducing pg_cmp_s32 and friends and use them\n> instead of the INT_CMP macro introduced before. It also moves the\n> definitions to common/int.h and adds that as an include to all locations\n> using these functions.\n\nThanks for the new version of the patch.\n\n> Note that for integers with sizes less than sizeof(int), C standard\n> conversions will convert the values to \"int\" before doing the arithmetic,\n> so no casting is *necessary*. I did not force the 16-bit functions to\n> return -1 or 1 and have updated the comment accordingly.\n\nIt might not be necessary, but this is one of those places where I would\nadd casting anyway to make it abundantly clear what we are expecting to\nhappen and why it is safe.I'll add it. \n> The types \"int\" and \"size_t\" are treated as s32 and u32 respectively since\n> that seems to be the case for most of the code, even if strictly not\n> correct (size_t can be an unsigned long int for some architecture).\n\nWhy is it safe to do this?\n\n> - return ((const SPLITCOST *) a)->cost - ((const SPLITCOST *) b)->cost;\n> + return INT_CMP(((const SPLITCOST *) a)->cost, ((const SPLITCOST *) b)->cost);\n\nThe patch still contains several calls to INT_CMP.I'll fix it. \n\n> +/*------------------------------------------------------------------------\n> + * Comparison routines for integers\n> + *------------------------------------------------------------------------\n> + */\n\nI'd suggest separating this part out to a 0001 patch to make it easier to\nreview. The 0002 patch could take care of converting the existing qsort\ncomparators.Ok. Will split it out into two patches. \n\n> +static inline int\n> +pg_cmp_s16(int16 a, int16 b)\n> +{\n> + return a - b;\n> +}\n> +\n> +static inline int\n> +pg_cmp_u16(uint16 a, uint16 b)\n> +{\n> + return a - b;\n> +}\n> +\n> +static inline int\n> +pg_cmp_s32(int32 a, int32 b)\n> +{\n> + return (a > b) - (a < b);\n> +}\n> +\n> +static inline int\n> +pg_cmp_u32(uint32 a, uint32 b)\n> +{\n> + return (a > b) - (a < b);\n> +}\n> +\n> +static inline int\n> +pg_cmp_s64(int64 a, int64 b)\n> +{\n> + return (a > b) - (a < b);\n> +}\n> +\n> +static inline int\n> +pg_cmp_u64(uint64 a, uint64 b)\n> +{\n> + return (a > b) - (a < b);\n> +}\n\nAs suggested above, IMHO we should be rather liberal with the casting to\nensure it is abundantly clear what is happening here.Ok. \n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Fri, 9 Feb 2024 20:26:48 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Fri, Feb 9, 2024 at 5:27 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Nathan Bossart <nathandbossart@gmail.com> writes:\n> > On Fri, Feb 09, 2024 at 08:52:26AM +0100, Mats Kindahl wrote:\n> >> The types \"int\" and \"size_t\" are treated as s32 and u32 respectively\n> since\n> >> that seems to be the case for most of the code, even if strictly not\n> >> correct (size_t can be an unsigned long int for some architecture).\n>\n> > Why is it safe to do this?\n>\n> We do pretty much assume that \"int\" is \"int32\". But I agree that\n> assuming anything about the width of size_t is bad. I think we need\n> a separate pg_cmp_size() or pg_cmp_size_t().\n>\n\nI added precisely one first, but removed it when I saw that all uses\nassumed that it was an int. :)\n\nI'll add it back.\n\nBest wishes,\nMats Kindahl\n\n>\n> regards, tom lane\n>\n\nOn Fri, Feb 9, 2024 at 5:27 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:Nathan Bossart <nathandbossart@gmail.com> writes:\n> On Fri, Feb 09, 2024 at 08:52:26AM +0100, Mats Kindahl wrote:\n>> The types \"int\" and \"size_t\" are treated as s32 and u32 respectively since\n>> that seems to be the case for most of the code, even if strictly not\n>> correct (size_t can be an unsigned long int for some architecture).\n\n> Why is it safe to do this?\n\nWe do pretty much assume that \"int\" is \"int32\". But I agree that\nassuming anything about the width of size_t is bad. I think we need\na separate pg_cmp_size() or pg_cmp_size_t().I added precisely one first, but removed it when I saw that all uses assumed that it was an int. :)I'll add it back.Best wishes,Mats Kindahl \n\n regards, tom lane",
"msg_date": "Fri, 9 Feb 2024 20:35:57 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Fri, Feb 9, 2024 at 5:27 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Nathan Bossart <nathandbossart@gmail.com> writes:\n> > On Fri, Feb 09, 2024 at 08:52:26AM +0100, Mats Kindahl wrote:\n> >> The types \"int\" and \"size_t\" are treated as s32 and u32 respectively\n> since\n> >> that seems to be the case for most of the code, even if strictly not\n> >> correct (size_t can be an unsigned long int for some architecture).\n>\n> > Why is it safe to do this?\n>\n> We do pretty much assume that \"int\" is \"int32\". But I agree that\n> assuming anything about the width of size_t is bad. I think we need\n> a separate pg_cmp_size() or pg_cmp_size_t().\n>\n\nDo we want to have something similar for \"int\" as well? It seems to be\nquite common and even though it usually is an int32, it does not have to be.\n\nBest wishes,\nMats Kindahl\n\n>\n> regards, tom lane\n>\n\nOn Fri, Feb 9, 2024 at 5:27 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:Nathan Bossart <nathandbossart@gmail.com> writes:\n> On Fri, Feb 09, 2024 at 08:52:26AM +0100, Mats Kindahl wrote:\n>> The types \"int\" and \"size_t\" are treated as s32 and u32 respectively since\n>> that seems to be the case for most of the code, even if strictly not\n>> correct (size_t can be an unsigned long int for some architecture).\n\n> Why is it safe to do this?\n\nWe do pretty much assume that \"int\" is \"int32\". But I agree that\nassuming anything about the width of size_t is bad. I think we need\na separate pg_cmp_size() or pg_cmp_size_t().Do we want to have something similar for \"int\" as well? It seems to be quite common and even though it usually is an int32, it does not have to be.Best wishes,Mats Kindahl \n\n regards, tom lane",
"msg_date": "Fri, 9 Feb 2024 20:40:47 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Fri, Feb 9, 2024 at 8:26 PM Mats Kindahl <mats@timescale.com> wrote:\n\n> On Fri, Feb 9, 2024 at 5:24 PM Nathan Bossart <nathandbossart@gmail.com>\n> wrote:\n>\n>> On Fri, Feb 09, 2024 at 08:52:26AM +0100, Mats Kindahl wrote:\n>> > Here is a new version introducing pg_cmp_s32 and friends and use them\n>> > instead of the INT_CMP macro introduced before. It also moves the\n>> > definitions to common/int.h and adds that as an include to all locations\n>> > using these functions.\n>>\n>> Thanks for the new version of the patch.\n>>\n>> > Note that for integers with sizes less than sizeof(int), C standard\n>> > conversions will convert the values to \"int\" before doing the\n>> arithmetic,\n>> > so no casting is *necessary*. I did not force the 16-bit functions to\n>> > return -1 or 1 and have updated the comment accordingly.\n>>\n>> It might not be necessary, but this is one of those places where I would\n>> add casting anyway to make it abundantly clear what we are expecting to\n>> happen and why it is safe.\n>>\n>\n> I'll add it.\n>\n>\n>> > The types \"int\" and \"size_t\" are treated as s32 and u32 respectively\n>> since\n>> > that seems to be the case for most of the code, even if strictly not\n>> > correct (size_t can be an unsigned long int for some architecture).\n>>\n>> Why is it safe to do this?\n>>\n>> > - return ((const SPLITCOST *) a)->cost - ((const SPLITCOST *)\n>> b)->cost;\n>> > + return INT_CMP(((const SPLITCOST *) a)->cost, ((const SPLITCOST\n>> *) b)->cost);\n>>\n>> The patch still contains several calls to INT_CMP.\n>>\n>\n> I'll fix it.\n>\n>\n>>\n>> >\n>> +/*------------------------------------------------------------------------\n>> > + * Comparison routines for integers\n>> > +\n>> *------------------------------------------------------------------------\n>> > + */\n>>\n>> I'd suggest separating this part out to a 0001 patch to make it easier to\n>> review. The 0002 patch could take care of converting the existing qsort\n>> comparators.\n>>\n>\n> Ok. Will split it out into two patches.\n>\n>\n>>\n>> > +static inline int\n>> > +pg_cmp_s16(int16 a, int16 b)\n>> > +{\n>> > + return a - b;\n>> > +}\n>> > +\n>> > +static inline int\n>> > +pg_cmp_u16(uint16 a, uint16 b)\n>> > +{\n>> > + return a - b;\n>> > +}\n>> > +\n>> > +static inline int\n>> > +pg_cmp_s32(int32 a, int32 b)\n>> > +{\n>> > + return (a > b) - (a < b);\n>> > +}\n>> > +\n>> > +static inline int\n>> > +pg_cmp_u32(uint32 a, uint32 b)\n>> > +{\n>> > + return (a > b) - (a < b);\n>> > +}\n>> > +\n>> > +static inline int\n>> > +pg_cmp_s64(int64 a, int64 b)\n>> > +{\n>> > + return (a > b) - (a < b);\n>> > +}\n>> > +\n>> > +static inline int\n>> > +pg_cmp_u64(uint64 a, uint64 b)\n>> > +{\n>> > + return (a > b) - (a < b);\n>> > +}\n>>\n>> As suggested above, IMHO we should be rather liberal with the casting to\n>> ensure it is abundantly clear what is happening here.\n>>\n>\n> Ok.\n>\n\nQQ: right now it looks like this:\n\nstatic inline int\npg_cmp_u16(uint16 a, uint16 b)\n{\n\nreturn (int32)a - (int32)b;\n\n}\n\n\nand\n\nstatic inline int\npg_cmp_u32(uint32 a, uint32 b)\n{\n\nreturn (a > b) - (a < b);\n\n}\n\n\nI think that is clear enough, but do you want more casts added for the\nreturn value as well?\n\nBest wishes,\nMats Kindahl\n\n\n>\n>\n>>\n>> --\n>> Nathan Bossart\n>> Amazon Web Services: https://aws.amazon.com\n>>\n>\n\nOn Fri, Feb 9, 2024 at 8:26 PM Mats Kindahl <mats@timescale.com> wrote:On Fri, Feb 9, 2024 at 5:24 PM Nathan Bossart <nathandbossart@gmail.com> wrote:On Fri, Feb 09, 2024 at 08:52:26AM +0100, Mats Kindahl wrote:\n> Here is a new version introducing pg_cmp_s32 and friends and use them\n> instead of the INT_CMP macro introduced before. It also moves the\n> definitions to common/int.h and adds that as an include to all locations\n> using these functions.\n\nThanks for the new version of the patch.\n\n> Note that for integers with sizes less than sizeof(int), C standard\n> conversions will convert the values to \"int\" before doing the arithmetic,\n> so no casting is *necessary*. I did not force the 16-bit functions to\n> return -1 or 1 and have updated the comment accordingly.\n\nIt might not be necessary, but this is one of those places where I would\nadd casting anyway to make it abundantly clear what we are expecting to\nhappen and why it is safe.I'll add it. \n> The types \"int\" and \"size_t\" are treated as s32 and u32 respectively since\n> that seems to be the case for most of the code, even if strictly not\n> correct (size_t can be an unsigned long int for some architecture).\n\nWhy is it safe to do this?\n\n> - return ((const SPLITCOST *) a)->cost - ((const SPLITCOST *) b)->cost;\n> + return INT_CMP(((const SPLITCOST *) a)->cost, ((const SPLITCOST *) b)->cost);\n\nThe patch still contains several calls to INT_CMP.I'll fix it. \n\n> +/*------------------------------------------------------------------------\n> + * Comparison routines for integers\n> + *------------------------------------------------------------------------\n> + */\n\nI'd suggest separating this part out to a 0001 patch to make it easier to\nreview. The 0002 patch could take care of converting the existing qsort\ncomparators.Ok. Will split it out into two patches. \n\n> +static inline int\n> +pg_cmp_s16(int16 a, int16 b)\n> +{\n> + return a - b;\n> +}\n> +\n> +static inline int\n> +pg_cmp_u16(uint16 a, uint16 b)\n> +{\n> + return a - b;\n> +}\n> +\n> +static inline int\n> +pg_cmp_s32(int32 a, int32 b)\n> +{\n> + return (a > b) - (a < b);\n> +}\n> +\n> +static inline int\n> +pg_cmp_u32(uint32 a, uint32 b)\n> +{\n> + return (a > b) - (a < b);\n> +}\n> +\n> +static inline int\n> +pg_cmp_s64(int64 a, int64 b)\n> +{\n> + return (a > b) - (a < b);\n> +}\n> +\n> +static inline int\n> +pg_cmp_u64(uint64 a, uint64 b)\n> +{\n> + return (a > b) - (a < b);\n> +}\n\nAs suggested above, IMHO we should be rather liberal with the casting to\nensure it is abundantly clear what is happening here.Ok.QQ: right now it looks like this:static inline intpg_cmp_u16(uint16 a, uint16 b){\treturn (int32)a - (int32)b;}andstatic inline intpg_cmp_u32(uint32 a, uint32 b){\treturn (a > b) - (a < b);}I think that is clear enough, but do you want more casts added for the return value as well?Best wishes,Mats Kindahl \n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Fri, 9 Feb 2024 20:43:21 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Fri, Feb 09, 2024 at 08:40:47PM +0100, Mats Kindahl wrote:\n> On Fri, Feb 9, 2024 at 5:27 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> We do pretty much assume that \"int\" is \"int32\". But I agree that\n>> assuming anything about the width of size_t is bad. I think we need\n>> a separate pg_cmp_size() or pg_cmp_size_t().\n> \n> Do we want to have something similar for \"int\" as well? It seems to be\n> quite common and even though it usually is an int32, it does not have to be.\n\nI don't think we need separate functions for int and int32. As Tom noted,\nwe assume they are the same.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Fri, 9 Feb 2024 14:04:29 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On 2024-02-09 14:04:29 -0600, Nathan Bossart wrote:\n> On Fri, Feb 09, 2024 at 08:40:47PM +0100, Mats Kindahl wrote:\n> > On Fri, Feb 9, 2024 at 5:27 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >> We do pretty much assume that \"int\" is \"int32\". But I agree that\n> >> assuming anything about the width of size_t is bad. I think we need\n> >> a separate pg_cmp_size() or pg_cmp_size_t().\n> > \n> > Do we want to have something similar for \"int\" as well? It seems to be\n> > quite common and even though it usually is an int32, it does not have to be.\n> \n> I don't think we need separate functions for int and int32. As Tom noted,\n> we assume they are the same.\n\n+1\n\n\n",
"msg_date": "Fri, 9 Feb 2024 12:08:17 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Fri, Feb 09, 2024 at 08:43:21PM +0100, Mats Kindahl wrote:\n> QQ: right now it looks like this:\n> \n> static inline int\n> pg_cmp_u16(uint16 a, uint16 b)\n> {\n> \n> return (int32)a - (int32)b;\n> \n> }\n> \n> \n> and\n> \n> static inline int\n> pg_cmp_u32(uint32 a, uint32 b)\n> {\n> \n> return (a > b) - (a < b);\n> \n> }\n> \n> \n> I think that is clear enough, but do you want more casts added for the\n> return value as well?\n\nI think that is reasonably clear. The latter does require you to know that\n< and > return (int) 0 or (int) 1, which might be worth a short comment.\nBut that's just nitpicking...\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Fri, 9 Feb 2024 14:08:28 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Fri, Feb 9, 2024 at 9:08 PM Nathan Bossart <nathandbossart@gmail.com>\nwrote:\n\n> On Fri, Feb 09, 2024 at 08:43:21PM +0100, Mats Kindahl wrote:\n> > QQ: right now it looks like this:\n> >\n> > static inline int\n> > pg_cmp_u16(uint16 a, uint16 b)\n> > {\n> >\n> > return (int32)a - (int32)b;\n> >\n> > }\n> >\n> >\n> > and\n> >\n> > static inline int\n> > pg_cmp_u32(uint32 a, uint32 b)\n> > {\n> >\n> > return (a > b) - (a < b);\n> >\n> > }\n> >\n> >\n> > I think that is clear enough, but do you want more casts added for the\n> > return value as well?\n>\n> I think that is reasonably clear. The latter does require you to know that\n> < and > return (int) 0 or (int) 1, which might be worth a short comment.\n> But that's just nitpicking...\n>\n>\nHi all,\n\nSplit the code into two patches: one that just adds the functions\n(including the new pg_cmp_size()) to common/int.h and one that starts using\nthem. I picked the name \"pg_cmp_size\" rather than \"pg_cmp_size_t\" since\n\"_t\" is usually used as a suffix for types.\n\nI added a comment to the (a > b) - (a < b) return and have also added casts\nto (int32) for the int16 and uint16 functions (we need a signed int for\nuin16 since we need to be able to get a negative number).\n\nChanged the type of two instances that had an implicit cast from size_t to\nint and used the new pg_,cmp_size() function.\n\nAlso fixed the missed replacements in the \"contrib\" directory.\n\nBest wishes,\nMats Kindahl\n\n\n> --\n> Nathan Bossart\n> Amazon Web Services: https://aws.amazon.com\n>",
"msg_date": "Sat, 10 Feb 2024 08:59:06 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Sat, Feb 10, 2024 at 08:59:06AM +0100, Mats Kindahl wrote:\n> Split the code into two patches: one that just adds the functions\n> (including the new pg_cmp_size()) to common/int.h and one that starts using\n> them. I picked the name \"pg_cmp_size\" rather than \"pg_cmp_size_t\" since\n> \"_t\" is usually used as a suffix for types.\n> \n> I added a comment to the (a > b) - (a < b) return and have also added casts\n> to (int32) for the int16 and uint16 functions (we need a signed int for\n> uin16 since we need to be able to get a negative number).\n> \n> Changed the type of two instances that had an implicit cast from size_t to\n> int and used the new pg_,cmp_size() function.\n> \n> Also fixed the missed replacements in the \"contrib\" directory.\n\nThanks for the new patches. I think the comparison in resowner.c is\nbackwards, and I think we should expand on some of the commentary in int.h.\nFor example, the comment at the top of int.h seems very tailored to the\nexisting functions and should probably be adjusted. And the \"comparison\nroutines for integers\" comment might benefit from some additional details\nabout the purpose and guarantees of the new functions.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Sat, 10 Feb 2024 14:53:32 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Sat, Feb 10, 2024 at 9:53 PM Nathan Bossart <nathandbossart@gmail.com>\nwrote:\n\n> On Sat, Feb 10, 2024 at 08:59:06AM +0100, Mats Kindahl wrote:\n> > Split the code into two patches: one that just adds the functions\n> > (including the new pg_cmp_size()) to common/int.h and one that starts\n> using\n> > them. I picked the name \"pg_cmp_size\" rather than \"pg_cmp_size_t\" since\n> > \"_t\" is usually used as a suffix for types.\n> >\n> > I added a comment to the (a > b) - (a < b) return and have also added\n> casts\n> > to (int32) for the int16 and uint16 functions (we need a signed int for\n> > uin16 since we need to be able to get a negative number).\n> >\n> > Changed the type of two instances that had an implicit cast from size_t\n> to\n> > int and used the new pg_,cmp_size() function.\n> >\n> > Also fixed the missed replacements in the \"contrib\" directory.\n>\n> Thanks for the new patches. I think the comparison in resowner.c is\n> backwards,\n\n\nThanks for catching that.\n\n\n\n> and I think we should expand on some of the commentary in int.h.\n> For example, the comment at the top of int.h seems very tailored to the\n> existing functions and should probably be adjusted.\n\n\nI rewrote the beginning to the following, does that look good?\n\n * int.h\n * Routines to perform signed and unsigned integer arithmetics, including\n * comparisons, in an overflow-safe way.\n\n\n\n> And the \"comparison\n> routines for integers\" comment might benefit from some additional details\n> about the purpose and guarantees of the new functions.\n>\n\nI expanded that into the following. WDYT?\n\n/*------------------------------------------------------------------------\n * Comparison routines for integers.\n *\n * These routines are used to implement comparison functions for, e.g.,\n * qsort(). They are designed to be efficient and not risk overflows in\n * internal computations that could cause strange results, such as INT_MIN >\n * INT_MAX if you just return \"lhs - rhs\".\n *------------------------------------------------------------------------\n\n\nBest wishes,\nMats Kindahl\n\n\n> --\n> Nathan Bossart\n> Amazon Web Services: https://aws.amazon.com\n>\n\nOn Sat, Feb 10, 2024 at 9:53 PM Nathan Bossart <nathandbossart@gmail.com> wrote:On Sat, Feb 10, 2024 at 08:59:06AM +0100, Mats Kindahl wrote:\n> Split the code into two patches: one that just adds the functions\n> (including the new pg_cmp_size()) to common/int.h and one that starts using\n> them. I picked the name \"pg_cmp_size\" rather than \"pg_cmp_size_t\" since\n> \"_t\" is usually used as a suffix for types.\n> \n> I added a comment to the (a > b) - (a < b) return and have also added casts\n> to (int32) for the int16 and uint16 functions (we need a signed int for\n> uin16 since we need to be able to get a negative number).\n> \n> Changed the type of two instances that had an implicit cast from size_t to\n> int and used the new pg_,cmp_size() function.\n> \n> Also fixed the missed replacements in the \"contrib\" directory.\n\nThanks for the new patches. I think the comparison in resowner.c is\nbackwards,Thanks for catching that. and I think we should expand on some of the commentary in int.h.\nFor example, the comment at the top of int.h seems very tailored to the\nexisting functions and should probably be adjusted. I rewrote the beginning to the following, does that look good? * int.h *\t Routines to perform signed and unsigned integer arithmetics, including *\t comparisons, in an overflow-safe way. And the \"comparison\nroutines for integers\" comment might benefit from some additional details\nabout the purpose and guarantees of the new functions.I expanded that into the following. WDYT?/*------------------------------------------------------------------------ * Comparison routines for integers. * * These routines are used to implement comparison functions for, e.g., * qsort(). They are designed to be efficient and not risk overflows in * internal computations that could cause strange results, such as INT_MIN > * INT_MAX if you just return \"lhs - rhs\". *------------------------------------------------------------------------ Best wishes,Mats Kindahl\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Sun, 11 Feb 2024 15:44:42 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Sun, Feb 11, 2024 at 03:44:42PM +0100, Mats Kindahl wrote:\n> On Sat, Feb 10, 2024 at 9:53 PM Nathan Bossart <nathandbossart@gmail.com>\n> wrote:\n>> and I think we should expand on some of the commentary in int.h.\n>> For example, the comment at the top of int.h seems very tailored to the\n>> existing functions and should probably be adjusted.\n> \n> \n> I rewrote the beginning to the following, does that look good?\n> \n> * int.h\n> * Routines to perform signed and unsigned integer arithmetics, including\n> * comparisons, in an overflow-safe way.\n> \n> \n> \n>> And the \"comparison\n>> routines for integers\" comment might benefit from some additional details\n>> about the purpose and guarantees of the new functions.\n>>\n> \n> I expanded that into the following. WDYT?\n> \n> /*------------------------------------------------------------------------\n> * Comparison routines for integers.\n> *\n> * These routines are used to implement comparison functions for, e.g.,\n> * qsort(). They are designed to be efficient and not risk overflows in\n> * internal computations that could cause strange results, such as INT_MIN >\n> * INT_MAX if you just return \"lhs - rhs\".\n> *------------------------------------------------------------------------\n\nLGTM. I might editorialize a bit before committing, but I think your\nproposed wording illustrates the thrust of the change.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Mon, 12 Feb 2024 09:57:15 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Mon, Feb 12, 2024 at 4:57 PM Nathan Bossart <nathandbossart@gmail.com>\nwrote:\n\n> On Sun, Feb 11, 2024 at 03:44:42PM +0100, Mats Kindahl wrote:\n> > On Sat, Feb 10, 2024 at 9:53 PM Nathan Bossart <nathandbossart@gmail.com\n> >\n> > wrote:\n> >> and I think we should expand on some of the commentary in int.h.\n> >> For example, the comment at the top of int.h seems very tailored to the\n> >> existing functions and should probably be adjusted.\n> >\n> >\n> > I rewrote the beginning to the following, does that look good?\n> >\n> > * int.h\n> > * Routines to perform signed and unsigned integer arithmetics,\n> including\n> > * comparisons, in an overflow-safe way.\n> >\n> >\n> >\n> >> And the \"comparison\n> >> routines for integers\" comment might benefit from some additional\n> details\n> >> about the purpose and guarantees of the new functions.\n> >>\n> >\n> > I expanded that into the following. WDYT?\n> >\n> >\n> /*------------------------------------------------------------------------\n> > * Comparison routines for integers.\n> > *\n> > * These routines are used to implement comparison functions for, e.g.,\n> > * qsort(). They are designed to be efficient and not risk overflows in\n> > * internal computations that could cause strange results, such as\n> INT_MIN >\n> > * INT_MAX if you just return \"lhs - rhs\".\n> >\n> *------------------------------------------------------------------------\n>\n> LGTM. I might editorialize a bit before committing, but I think your\n> proposed wording illustrates the thrust of the change.\n>\n\nThanks Nathan,\n\nHere are the two fixed patches.\n\nBest wishes,\nMats Kindahl\n\n\n>\n> --\n> Nathan Bossart\n> Amazon Web Services: https://aws.amazon.com\n>",
"msg_date": "Mon, 12 Feb 2024 18:09:06 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Mon, Feb 12, 2024 at 06:09:06PM +0100, Mats Kindahl wrote:\n> Here are the two fixed patches.\n\nThese patches look pretty good to me. Barring additional feedback, I'll\nplan on committing them in the next few days.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Mon, 12 Feb 2024 14:51:38 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Mon, Feb 12, 2024 at 5:51 PM Nathan Bossart <nathandbossart@gmail.com>\nwrote:\n>\n> On Mon, Feb 12, 2024 at 06:09:06PM +0100, Mats Kindahl wrote:\n> > Here are the two fixed patches.\n>\n> These patches look pretty good to me. Barring additional feedback, I'll\n> plan on committing them in the next few days.\n>\n\nAlso did some tests locally and everything went well. Patches apply to the\nmain branch without issues and all regression (including checkworld) pass!!\n\nRegards\n-- \nFabrízio de Royes Mello\n\nOn Mon, Feb 12, 2024 at 5:51 PM Nathan Bossart <nathandbossart@gmail.com> wrote:>> On Mon, Feb 12, 2024 at 06:09:06PM +0100, Mats Kindahl wrote:> > Here are the two fixed patches.>> These patches look pretty good to me. Barring additional feedback, I'll> plan on committing them in the next few days.>Also did some tests locally and everything went well. Patches apply to the main branch without issues and all regression (including checkworld) pass!!Regards-- Fabrízio de Royes Mello",
"msg_date": "Mon, 12 Feb 2024 18:20:44 -0300",
"msg_from": "=?UTF-8?Q?Fabr=C3=ADzio_de_Royes_Mello?= <fabriziomello@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "Hi,\n\nOn 2024-02-12 14:51:38 -0600, Nathan Bossart wrote:\n> On Mon, Feb 12, 2024 at 06:09:06PM +0100, Mats Kindahl wrote:\n> > Here are the two fixed patches.\n> \n> These patches look pretty good to me. Barring additional feedback, I'll\n> plan on committing them in the next few days.\n\nOne thing that's worth checking is if this ends up with *worse* code when the\ncomparators are inlined. I think none of the changed comparators will end up\ngetting used with an inlined sort, but ...\n\nThe reason we could end up with worse code is that when inlining the\ncomparisons would make less sense for the compiler. Consider e.g.\n\treturn DO_COMPARE(a, b) < 0 ?\n\t\t(DO_COMPARE(b, c) < 0 ? b : (DO_COMPARE(a, c) < 0 ? c : a))\n\t\t: (DO_COMPARE(b, c) > 0 ? b : (DO_COMPARE(a, c) < 0 ? a : c));\n\nWith a naive implementation the compiler will understand it only cares about\na < b, not about the other possibilities. I'm not sure that's still true with\nthe more complicated optimized version.\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Mon, 12 Feb 2024 13:31:30 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Mon, Feb 12, 2024 at 01:31:30PM -0800, Andres Freund wrote:\n> One thing that's worth checking is if this ends up with *worse* code when the\n> comparators are inlined. I think none of the changed comparators will end up\n> getting used with an inlined sort, but ...\n\nYeah, AFAICT the only inlined sorts are in tuplesort.c and bufmgr.c, and\nthe patches don't touch those files.\n\n> The reason we could end up with worse code is that when inlining the\n> comparisons would make less sense for the compiler. Consider e.g.\n> \treturn DO_COMPARE(a, b) < 0 ?\n> \t\t(DO_COMPARE(b, c) < 0 ? b : (DO_COMPARE(a, c) < 0 ? c : a))\n> \t\t: (DO_COMPARE(b, c) > 0 ? b : (DO_COMPARE(a, c) < 0 ? a : c));\n> \n> With a naive implementation the compiler will understand it only cares about\n> a < b, not about the other possibilities. I'm not sure that's still true with\n> the more complicated optimized version.\n\nYou aren't kidding [0]. Besides perhaps adding a comment in\nsort_template.h, is there anything else you think we should do about this\nnow?\n\n[0] https://godbolt.org/z/bbTqK54zK\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Mon, 12 Feb 2024 17:04:23 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "Hi,\n\nOn 2024-02-12 17:04:23 -0600, Nathan Bossart wrote:\n> On Mon, Feb 12, 2024 at 01:31:30PM -0800, Andres Freund wrote:\n> > One thing that's worth checking is if this ends up with *worse* code when the\n> > comparators are inlined. I think none of the changed comparators will end up\n> > getting used with an inlined sort, but ...\n> \n> Yeah, AFAICT the only inlined sorts are in tuplesort.c and bufmgr.c, and\n> the patches don't touch those files.\n> \n> > The reason we could end up with worse code is that when inlining the\n> > comparisons would make less sense for the compiler. Consider e.g.\n> > \treturn DO_COMPARE(a, b) < 0 ?\n> > \t\t(DO_COMPARE(b, c) < 0 ? b : (DO_COMPARE(a, c) < 0 ? c : a))\n> > \t\t: (DO_COMPARE(b, c) > 0 ? b : (DO_COMPARE(a, c) < 0 ? a : c));\n> > \n> > With a naive implementation the compiler will understand it only cares about\n> > a < b, not about the other possibilities. I'm not sure that's still true with\n> > the more complicated optimized version.\n> \n> You aren't kidding [0]. Besides perhaps adding a comment in\n> sort_template.h, is there anything else you think we should do about this\n> now?\n\nI'd add also a comment to the new functions. I think it's fine otherwise. I\nwish there were formulation that'd be optimal for both cases, but this way we\ncan at least adapt all places at once if either find a better formulation or\nchange all our sorts to happen via an inline implementation of qsort or such.\n\nGreetings,\n\nAndres\n\n\n",
"msg_date": "Mon, 12 Feb 2024 15:41:34 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Tue, Feb 13, 2024 at 12:41 AM Andres Freund <andres@anarazel.de> wrote:\n\n> Hi,\n>\n> On 2024-02-12 17:04:23 -0600, Nathan Bossart wrote:\n> > On Mon, Feb 12, 2024 at 01:31:30PM -0800, Andres Freund wrote:\n> > > One thing that's worth checking is if this ends up with *worse* code\n> when the\n> > > comparators are inlined. I think none of the changed comparators will\n> end up\n> > > getting used with an inlined sort, but ...\n> >\n> > Yeah, AFAICT the only inlined sorts are in tuplesort.c and bufmgr.c, and\n> > the patches don't touch those files.\n> >\n> > > The reason we could end up with worse code is that when inlining the\n> > > comparisons would make less sense for the compiler. Consider e.g.\n> > > return DO_COMPARE(a, b) < 0 ?\n> > > (DO_COMPARE(b, c) < 0 ? b : (DO_COMPARE(a, c) < 0 ? c : a))\n> > > : (DO_COMPARE(b, c) > 0 ? b : (DO_COMPARE(a, c) < 0 ? a :\n> c));\n> > >\n> > > With a naive implementation the compiler will understand it only cares\n> about\n> > > a < b, not about the other possibilities. I'm not sure that's still\n> true with\n> > > the more complicated optimized version.\n> >\n> > You aren't kidding [0]. Besides perhaps adding a comment in\n> > sort_template.h, is there anything else you think we should do about this\n> > now?\n>\n> I'd add also a comment to the new functions. I think it's fine otherwise. I\n> wish there were formulation that'd be optimal for both cases, but this way\n> we\n> can at least adapt all places at once if either find a better formulation\n> or\n> change all our sorts to happen via an inline implementation of qsort or\n> such.\n>\n\nI suspect that this has to do with the fact that we \"abuse\" the type system\nby performing arithmetics on booleans converted to integers and the\ncompilers do not have rules for dealing with these.\n\nFor example, with the inline function \"static inline cmp(a,b) { return a <\nb ? -1 : a > b ? 1 : 0; }\"\n\nWhich trivially can be rewritten by the compiler using very basic rules, as\nfollows:\n\nDO_COMPARE(a,b)\n (a < b ? -1 : a > b ? 1 : 0) < 0\n a < b ? (-1 < 0) : a > b ? (1 < 0) : (0 < 0)\n a < b ? true : a > b ? false : false\n a < b ? true : a > b ? false : false\n a < b ? true : false\n a < b\n\nWhen it comes to (a < b) - (a > b) there are no such rules added since it\nis not a very common case.\n\nClang fares better for this case and at least shows the two alternatives as\nequal.\n\nMaybe we should change to use the original version equivalent to the inline\nfunction above since that works better with surrounding code?\n\nBest wishes,\nMats Kindahl\n\n\n>\n> Greetings,\n>\n> Andres\n>\n\nOn Tue, Feb 13, 2024 at 12:41 AM Andres Freund <andres@anarazel.de> wrote:Hi,\n\nOn 2024-02-12 17:04:23 -0600, Nathan Bossart wrote:\n> On Mon, Feb 12, 2024 at 01:31:30PM -0800, Andres Freund wrote:\n> > One thing that's worth checking is if this ends up with *worse* code when the\n> > comparators are inlined. I think none of the changed comparators will end up\n> > getting used with an inlined sort, but ...\n> \n> Yeah, AFAICT the only inlined sorts are in tuplesort.c and bufmgr.c, and\n> the patches don't touch those files.\n> \n> > The reason we could end up with worse code is that when inlining the\n> > comparisons would make less sense for the compiler. Consider e.g.\n> > return DO_COMPARE(a, b) < 0 ?\n> > (DO_COMPARE(b, c) < 0 ? b : (DO_COMPARE(a, c) < 0 ? c : a))\n> > : (DO_COMPARE(b, c) > 0 ? b : (DO_COMPARE(a, c) < 0 ? a : c));\n> > \n> > With a naive implementation the compiler will understand it only cares about\n> > a < b, not about the other possibilities. I'm not sure that's still true with\n> > the more complicated optimized version.\n> \n> You aren't kidding [0]. Besides perhaps adding a comment in\n> sort_template.h, is there anything else you think we should do about this\n> now?\n\nI'd add also a comment to the new functions. I think it's fine otherwise. I\nwish there were formulation that'd be optimal for both cases, but this way we\ncan at least adapt all places at once if either find a better formulation or\nchange all our sorts to happen via an inline implementation of qsort or such.I suspect that this has to do with the fact that we \"abuse\" the type system by performing arithmetics on booleans converted to integers and the compilers do not have rules for dealing with these.For example, with the inline function \"static inline cmp(a,b) { return a < b ? -1 : a > b ? 1 : 0; }\"Which trivially can be rewritten by the compiler using very basic rules, as follows: DO_COMPARE(a,b) (a < b ? -1 : a > b ? 1 : 0) < 0 a < b ? (-1 < 0) : a > b ? (1 < 0) : (0 < 0) a < b ? true : a > b ? false : false a < b ? true : a > b ? false : false a < b ? true : false a < bWhen it comes to (a < b) - (a > b) there are no such rules added since it is not a very common case.Clang fares better for this case and at least shows the two alternatives as equal.Maybe we should change to use the original version equivalent to the inline function above since that works better with surrounding code?Best wishes,Mats Kindahl \n\nGreetings,\n\nAndres",
"msg_date": "Tue, 13 Feb 2024 09:43:18 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Tue, Feb 13, 2024 at 09:43:18AM +0100, Mats Kindahl wrote:\n> Maybe we should change to use the original version equivalent to the inline\n> function above since that works better with surrounding code?\n\nI don't think that's necessary. We just need to be cognizant of it when\nusing inlined sorts, which are pretty rare at the moment. Your patches\nshould still be a net improvement in many cases because most qsorts use a\nfunction pointer to the comparator.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 13 Feb 2024 12:10:44 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "Here is what I have staged for commit.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Thu, 15 Feb 2024 17:32:19 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Fri, Feb 16, 2024 at 12:32 AM Nathan Bossart <nathandbossart@gmail.com>\nwrote:\n\n> Here is what I have staged for commit.\n>\n\nLooks good to me.\n\nChecked that all of the comparisons are in the expected order, except\ninside compDESC, cmp_lsn, and resource_priority_cmp, where the order is\nreversed.\n\nBest wishes,\nMats Kindahl\n\n>\n> --\n> Nathan Bossart\n> Amazon Web Services: https://aws.amazon.com\n>\n\nOn Fri, Feb 16, 2024 at 12:32 AM Nathan Bossart <nathandbossart@gmail.com> wrote:Here is what I have staged for commit.Looks good to me.Checked that all of the comparisons are in the expected order, except inside compDESC, cmp_lsn, and resource_priority_cmp, where the order is reversed.Best wishes,Mats Kindahl\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Fri, 16 Feb 2024 13:45:52 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Fri, Feb 16, 2024 at 01:45:52PM +0100, Mats Kindahl wrote:\n> Looks good to me.\n\nCommitted.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Fri, 16 Feb 2024 14:09:51 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: glibc qsort() vulnerability"
},
{
"msg_contents": "On Fri, Feb 16, 2024 at 9:09 PM Nathan Bossart <nathandbossart@gmail.com>\nwrote:\n\n> On Fri, Feb 16, 2024 at 01:45:52PM +0100, Mats Kindahl wrote:\n> > Looks good to me.\n>\n> Committed.\n>\n\nThanks Nathan!\n\n\n>\n> --\n> Nathan Bossart\n> Amazon Web Services: https://aws.amazon.com\n>\n\nOn Fri, Feb 16, 2024 at 9:09 PM Nathan Bossart <nathandbossart@gmail.com> wrote:On Fri, Feb 16, 2024 at 01:45:52PM +0100, Mats Kindahl wrote:\n> Looks good to me.\n\nCommitted.Thanks Nathan! \n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Sat, 17 Feb 2024 14:16:26 +0100",
"msg_from": "Mats Kindahl <mats@timescale.com>",
"msg_from_op": true,
"msg_subject": "Re: glibc qsort() vulnerability"
}
] |
[
{
"msg_contents": "Hi hackers,\n\n\nI've encountered and addressed errors in the \n\"0001-pg_stat_advisor-extension.patch\" when applying it to the main \nbranch, specifically trailing whitespace issues at lines 117 and 118:\n\n```\n0001-pg_stat_advisor-extension.patch:117: trailing whitespace.\n QUERY PLAN\n0001-pg_stat_advisor-extension.patch:118: trailing whitespace.\n\nwarning: 2 lines add whitespace errors.\n\n```\n\nAn updated patch is attached for review\n\n\nI welcome your insights, feedback, and evaluations regarding the \nnecessity of integrating this new extension into PostgreSQL.\n\n\nKind regards,\n\nIlia Evdokimov,\n\nTantor Labs LLC.",
"msg_date": "Tue, 6 Feb 2024 18:27:36 +0300",
"msg_from": "Ilia Evdokimov <ilya.evdokimov@tantorlabs.com>",
"msg_from_op": true,
"msg_subject": "Re: pg_stat_advisor extension"
},
{
"msg_contents": "Dear Team,\n\nFirstly, I would like to extend my sincere apologies for the confusion \nand technical oversights in our previous discussions regarding the \n'pg_stat_advisor extension'. To address this and facilitate a clearer, \nmore focused dialogue, I have initiated a new thread to consolidate our \ndiscussions on this matter.\n\nFor context, our previous conversation can be found here: \nhttps://www.postgresql.org/message-id/flat/4681151706615977%40mail.yandex.ru.\n\nThe extension 'pg_stat_advisor' extension is architected to optimize \nquery plan. It operates by suggesting when to create extended \nstatistics, particularly in queries where current selectivity estimates \nfall short. This is achieved through the GUC parameter \n'pg_stat_advisor.suggest_statistics_threshold', which assesses the ratio \nof total tuples compared to the planned rows. This feature is \ninstrumental in identifying scenarios where the planner's estimates \ncould be optimized.\n\nYou can install the extension by:\n\n```\n\nLOAD 'pg_stat_advisor'\n\nSET pg_stat_advisor.suggest_statistics_threshold = 1.0;\n\n```\n\n\nExample:\n\n```\n\nEXPLAIN ANALYZE SELECT * FROM t WHERE i = 100 AND j = 10;\n\nNOTICE: pg_stat_advisor suggestion: CREATE STATISTICS t_i_j ON i, j FROM t\n\n QUERY PLAN\n\n--------------------------------------------------------------------------------------------------------\n\n```\n\nAfter EXPLAIN ANALYZE command you can see the message of suggestion \ncreating statistics with name 't_i_j' on 'i', 'j' columns from 't' table.\n\nThank you for your understanding, patience, and continued support.\n\n\n\nBest regards,\nIlia Evdokimov,\nTantor Labs LLC.\n\n\n",
"msg_date": "Tue, 6 Feb 2024 19:08:05 +0300",
"msg_from": "Ilia Evdokimov <ilya.evdokimov@tantorlabs.com>",
"msg_from_op": true,
"msg_subject": "Re: pg_stat_advisor extension"
},
{
"msg_contents": "On 6/2/2024 22:27, Ilia Evdokimov wrote:\n> \n> I welcome your insights, feedback, and evaluations regarding the \n> necessity of integrating this new extension into PostgreSQL.\nBesides other issues that were immediately raised during the discovery \nof the extension, Let me emphasize two issues:\n1. In the case of parallel workers the plan_rows value has a different \nsemantics than the number of rows predicted. Just explore \nget_parallel_divisor().\n2. The extension recommends new statistics immediately upon an error \nfinding. But what if the reason for the error is stale statistics? Or \nthis error may be raised for only one specific set of constants, and \nestimation will be done well in another 99.9999% of cases for the same \nexpression.\n\nAccording to No.2, it might make sense to collect and track clause \ncombinations and cardinality errors found and let the DBA make decisions \non their own.\n\n-- \nregards,\nAndrei Lepikhov\nPostgres Professional\n\n\n\n",
"msg_date": "Thu, 8 Feb 2024 14:14:18 +0700",
"msg_from": "Andrei Lepikhov <a.lepikhov@postgrespro.ru>",
"msg_from_op": false,
"msg_subject": "Re: pg_stat_advisor extension"
},
{
"msg_contents": "On Feb 8 2024 at 00:00:00 jian he\n\n >INT MAX\n\n >should be 1.0?\n\nI don’t know why Konstantin Knizhnik used the ratio of actual tuples to \nthe planned ones, but most who start testing my extension expect that it \nwill be a coefficient from 0 to 1, which will be the ratio of the \nestimated tuples to the actual ones. Therefore, I changed the value of \nthis coefficient the other way around and now the value can be from 0 to \n1. The patch with changes has been attached.\n\n\n > now CREATE STATISTICS, the statistics name is optional\n\nI constructed the name of the statistics so that the user could copy the \nline with 'CREATE STATISTICS' with the mouse and execute this command \nfaster. But if the user wants ITS name, he can do it manually.\n\n\n > here you can explicitly mention the statistics kind would be great\n\nI agree with you. That would be my next step. That's why I'm doing it now.\n\n\n > Also since the documentation is limited, more comments \nexplainingSuggestMultiColumnStatisticsForNode would be great.\n\n> overall the comments are very little, it should be more (that's my opinion).\n\nYes, certainly. I'll do it in the next patch.\n\nI'm looking forward to your thoughts and feedback.\n\nRegards,\n\nIlia Evdokimov,\n\nTantor Labs LLC.",
"msg_date": "Thu, 8 Feb 2024 16:54:58 +0300",
"msg_from": "Ilia Evdokimov <ilya.evdokimov@tantorlabs.com>",
"msg_from_op": true,
"msg_subject": "Re: pg_stat_advisor extension"
},
{
"msg_contents": "On Feb 08 2024 at 07:14:18, Andrei Lepikhov wrote:\n\n> 1. In the case of parallel workers the plan_rows value has a different \n> semantics than the number of rows predicted. Just explore \n> get_parallel_divisor().\nYes, this is a very weighty and important issue. I need to think about \nthis very carefully.\n>2. The extension recommends new statistics immediately upon an error \n>finding. But what if the reason for the error is stale statistics? Or \n>this error may be raised for only one specific set of constants, and \n>estimation will be done well in another 99.9999% of cases for the same \n>expression.\n>According to No.2, it might make sense to collect and track clause \n>combinations and cardinality errors found and let the DBA make decisions \n>on their own.\nYour proposal is very interesting. In my opinion, it is worth \nconsidering updating the extended statistics if they are truly stale. \nAnd write about this in a separate message with suggestion updating \nstatistics.\nIf I succeed, then in the next patch I will add the kind of extended \nstatistics to the message, deal with the parallel workers and update \nstatistics if necessary.\nIf you have additional suggestions and thoughts, feel free to write them \nin this thread.\n\n\nRegards,\nIlia Evdokimov,\nTantor Labs LLC.\n\n\n\n\n\nOn Feb 08 2024 at 07:14:18, Andrei\n Lepikhov wrote:\n\n\n> 1. In the case of parallel workers the plan_rows value has a different > semantics than the number of rows predicted. Just explore > get_parallel_divisor().\nYes, this is a very weighty and important issue. I need to think about this very carefully.\n\n\n>2. The extension recommends new statistics immediately upon an error >finding. But what if the reason for the error is stale statistics? Or >this error may be raised for only one specific set of constants, and >estimation will be done well in another 99.9999% of cases for the same >expression.\n>According to No.2, it might make sense to collect and track clause >combinations and cardinality errors found and let the DBA make decisions >on their own.\nYour proposal is very interesting. In my opinion, it is worth considering updating the extended statistics if they are truly stale. And write about this in a separate message with suggestion updating statistics.\n\n\n\nIf I succeed, then in the next patch I will add the kind of extended statistics to the message, deal with the parallel workers and update statistics if necessary.\n\n\nIf you have additional suggestions and thoughts, feel free to write them in this thread.\n\n\n\n\n\nRegards,\nIlia Evdokimov,\nTantor Labs LLC.",
"msg_date": "Thu, 8 Feb 2024 17:24:06 +0300",
"msg_from": "Ilia Evdokimov <ilya.evdokimov@tantorlabs.com>",
"msg_from_op": true,
"msg_subject": "Re: pg_stat_advisor extension"
},
{
"msg_contents": ">1. In the case of parallel workers the plan_rows value has a different semantics than the number of rows predicted. Just explore \nget_parallel_divisor().\n\n>2. The extension recommends new statistics immediately upon an error finding. But what if the reason for the error is stale statistics? Or \nthis error may be raised for only one specific set of constants, and \nestimation will be done well in another 99.9999% of cases for the same \nexpression.\n\nThe new parameter, `pg_stat_advisor.analyze_scale_factor`, can suggest \nthe execution of the ANALYZE command on specific tables. The extension \nnow evaluates the ratio of `n_live_tup` (number of live tuples) to \n`n_mod_since_analyze` (number of modifications since last analyze) in \nthe `pg_stat_all_tables` catalog. If this ratio exceeds the value \nspecified in `analyze_scale_factor`, the extension will suggest an \nupdate to the table's statistics.\n\nThere are a lot of parameters that influences on estimated rows. \nStatistics might not help improve estimated rows. This feature is \ndesigned to provide users with data-driven insights to decide whether \nupdating statistics via the ANALYZE command could potentially improve \nquery performance. By suggesting rather than automatically executing \nstatistics updates, we empower you to make informed decisions based on \nthe specific needs and conditions of your database environment.\n\nI've developed an extension that provides suggestions on whether to \nupdate or create statistics for your PostgreSQL database, without \nexecuting any changes. This approach allows you to consider various \nparameters that influence row estimates and make informed decisions \nabout optimizing your database's performance.\n\nYour feedback is invaluable, and we look forward to hearing about your \nexperiences and any improvements you might suggest. Best regards, Ilia \nEvdokimov Tantor Labs LLC.",
"msg_date": "Mon, 13 May 2024 15:26:01 +0300",
"msg_from": "Ilia Evdokimov <ilya.evdokimov@tantorlabs.com>",
"msg_from_op": true,
"msg_subject": "Re: pg_stat_advisor extension"
}
] |
[
{
"msg_contents": "Hi,\n\nAttached is a small patch implemented as I agree with Andres' comment\nbelow noted while reviewing the thread\nhttps://www.postgresql.org/message-id/flat/20240122210740.7vq5fd4woixpwx3f%40awork3.anarazel.de#6eb7595873392621d60e6b5a723941bc\n\nI agree that its easier to not have to refer back to the macros only to\nsee that they're all invoking StartChildProcess(X). All invocations are\nwithin postmaster.c. \n\n> @@ -561,13 +561,13 @@ static void ShmemBackendArrayAdd(Backend *bn);\n> static void ShmemBackendArrayRemove(Backend *bn);\n> #endif\t\t\t\t\t\t\t/* EXEC_BACKEND */\n> \n> -#define StartupDataBase()\t\tStartChildProcess(StartupProcess)\n> -#define StartArchiver()\t\t\tStartChildProcess(ArchiverProcess)\n> -#define StartBackgroundWriter() StartChildProcess(BgWriterProcess)\n> -#define StartCheckpointer()\t\tStartChildProcess(CheckpointerProcess)\n> -#define StartWalWriter()\t\tStartChildProcess(WalWriterProcess)\n> -#define StartWalReceiver()\t\tStartChildProcess(WalReceiverProcess)\n> -#define StartWalSummarizer()\tStartChildProcess(WalSummarizerProcess)\n> +#define StartupDataBase()\t\tStartChildProcess(B_STARTUP)\n> +#define StartArchiver()\t\t\tStartChildProcess(B_ARCHIVER)\n> +#define StartBackgroundWriter() StartChildProcess(B_BG_WRITER)\n> +#define StartCheckpointer()\t\tStartChildProcess(B_CHECKPOINTER)\n> +#define StartWalWriter()\t\tStartChildProcess(B_WAL_WRITER)\n> +#define StartWalReceiver()\t\tStartChildProcess(B_WAL_RECEIVER)\n> +#define StartWalSummarizer()\tStartChildProcess(B_WAL_SUMMARIZER)\n\nNot for this commit, but we ought to rip out these macros - all they do is to make it harder to understand the code.",
"msg_date": "Tue, 06 Feb 2024 11:58:50 -0500",
"msg_from": "reid.thompson@crunchydata.com",
"msg_from_op": true,
"msg_subject": "Remove Start* macros from postmaster.c to ease understanding of\n code"
},
{
"msg_contents": "On Tue, Feb 06, 2024 at 11:58:50AM -0500, reid.thompson@crunchydata.com wrote:\n> Attached is a small patch implemented as I agree with Andres' comment\n> below noted while reviewing the thread\n> https://www.postgresql.org/message-id/flat/20240122210740.7vq5fd4woixpwx3f%40awork3.anarazel.de#6eb7595873392621d60e6b5a723941bc\n> \n> I agree that its easier to not have to refer back to the macros only to\n> see that they're all invoking StartChildProcess(X). All invocations are\n> within postmaster.c. \n\nSeems reasonable to me.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 6 Feb 2024 11:10:18 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Remove Start* macros from postmaster.c to ease understanding of\n code"
},
{
"msg_contents": "On Tue, Feb 6, 2024 at 10:34 PM <reid.thompson@crunchydata.com> wrote:\n>\n> Hi,\n>\n> Attached is a small patch implemented as I agree with Andres' comment\n> below noted while reviewing the thread\n> https://www.postgresql.org/message-id/flat/20240122210740.7vq5fd4woixpwx3f%40awork3.anarazel.de#6eb7595873392621d60e6b5a723941bc\n>\n> I agree that its easier to not have to refer back to the macros only to\n> see that they're all invoking StartChildProcess(X). All invocations are\n> within postmaster.c.\n>\n> > @@ -561,13 +561,13 @@ static void ShmemBackendArrayAdd(Backend *bn);\n> > static void ShmemBackendArrayRemove(Backend *bn);\n> > #endif /* EXEC_BACKEND */\n> >\n> > -#define StartupDataBase() StartChildProcess(StartupProcess)\n> > -#define StartArchiver() StartChildProcess(ArchiverProcess)\n> > -#define StartBackgroundWriter() StartChildProcess(BgWriterProcess)\n> > -#define StartCheckpointer() StartChildProcess(CheckpointerProcess)\n> > -#define StartWalWriter() StartChildProcess(WalWriterProcess)\n> > -#define StartWalReceiver() StartChildProcess(WalReceiverProcess)\n> > -#define StartWalSummarizer() StartChildProcess(WalSummarizerProcess)\n> > +#define StartupDataBase() StartChildProcess(B_STARTUP)\n> > +#define StartArchiver() StartChildProcess(B_ARCHIVER)\n> > +#define StartBackgroundWriter() StartChildProcess(B_BG_WRITER)\n> > +#define StartCheckpointer() StartChildProcess(B_CHECKPOINTER)\n> > +#define StartWalWriter() StartChildProcess(B_WAL_WRITER)\n> > +#define StartWalReceiver() StartChildProcess(B_WAL_RECEIVER)\n> > +#define StartWalSummarizer() StartChildProcess(B_WAL_SUMMARIZER)\n>\n> Not for this commit, but we ought to rip out these macros - all they do is to make it harder to understand the code.\n\n+1. Patch LGTM.\n\n-- \nBharath Rupireddy\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Wed, 7 Feb 2024 00:48:00 +0530",
"msg_from": "Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Remove Start* macros from postmaster.c to ease understanding of\n code"
},
{
"msg_contents": "On Wed, Feb 07, 2024 at 12:48:00AM +0530, Bharath Rupireddy wrote:\n> +1. Patch LGTM.\n\nUnless there are objections, I'll plan on committing this in the next day\nor two.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 6 Feb 2024 14:37:25 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Remove Start* macros from postmaster.c to ease understanding of\n code"
},
{
"msg_contents": "On Tue, Feb 06, 2024 at 02:37:25PM -0600, Nathan Bossart wrote:\n> Unless there are objections, I'll plan on committing this in the next day\n> or two.\n\nCommitted.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Wed, 7 Feb 2024 12:52:43 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Remove Start* macros from postmaster.c to ease understanding of\n code"
}
] |
[
{
"msg_contents": "Hi,\n\n\nI'm seeking to improve the \\conninfo meta-command in psql. Currently, it provides limited information about the current connection. I believe that expanding it using the concept of \"plus\" [+] could ease the work of DBAs, SysAdmins, DevOps, etc., who manage a large volume of databases and/or multiple PostgreSQL servers. The objective of this enhancement is to obtain quick information about the current connection (session). I believe that for a PostgreSQL administrator, it is not feasible to write a plpgsql function and apply it to all databases (for example, imagine managing over 200 databases). I have an example on GitHub https://github.com/maiquelgrassi/DBA-toolkit/blob/main/cluster/dba_whoami_function.sql of a plpgsql function demonstrating exactly what I believe is impractical for the daily routine of a PostgreSQL professional. I see psql's meta-commands as significant allies in daily work in productive environments.\n\n\nNote: As this is a prototype, I will adjust the rest (documentation, tests, etc.) once an agreement is reached.\n\nUse cases for both the current and improved command bellow.\n\nConnection 1 (\"remote server\"):\n\n[postgres@localhost bin]$ ./psql -h 192.168.0.5 -p 5433 -U postgres -d postgres\n\npsql (17devel, server 16.1)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"192.168.0.5\" at port \"5433\".\npostgres=# \\conninfo+\n Current Connection Information\n Attribute | Value\n----------------+----------------\n Database | postgres\n User | postgres\n Server Version | 16.1\n Server Address | 192.168.0.5/32\n Server Port | 5433\n Client Address | 192.168.0.5/32\n Client Port | 52716\n Session PID | 21624\n(8 rows)\n\n\nConnection 2 (socket):\n\n[postgres@localhost bin]$ ./psql\n\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Attribute | Value\n------------------+-----------------------\n Info | Connected via socket!\n Database | postgres\n User | postgres\n Socket Directory | /tmp\n Server Version | 17devel\n Server Port | 5432\n Session PID | 27586\n(7 rows)\n\nConnection 3 (localhost):\n[postgres@localhost bin]$ ./psql -h localhost\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"localhost\" (address \"::1\") at port \"5432\".\npostgres=# \\conninfo+\nCurrent Connection Information\n Attribute | Value\n----------------+-----------\n Database | postgres\n User | postgres\n Host | localhost\n Server Version | 17devel\n Server Address | ::1/128\n Server Port | 5432\n Client Address | ::1/128\n Client Port | 46824\n Session PID | 27598\n(9 rows)\n\nConnection 4 (127.0.0.1):\n[postgres@localhost bin]$ ./psql -h 127.0.0.1\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"127.0.0.1\" at port \"5432\".\npostgres=# \\conninfo+\nCurrent Connection Information\n Attribute | Value\n----------------+--------------\n Database | postgres\n User | postgres\n Server Version | 17devel\n Server Address | 127.0.0.1/32\n Server Port | 5432\n Client Address | 127.0.0.1/32\n Client Port | 34876\n Session PID | 27624\n(8 rows)\n\nRegards,\nMaiquel O. Grassi.",
"msg_date": "Tue, 6 Feb 2024 17:27:01 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "Psql meta-command conninfo+"
},
{
"msg_contents": "On Tue, Feb 06, 2024 at 05:27:01PM +0000, Maiquel Grassi wrote:\n> I'm seeking to improve the \\conninfo meta-command in psql. Currently, it\n> provides limited information about the current connection. I believe that\n> expanding it using the concept of \"plus\" [+] could ease the work of DBAs,\n> SysAdmins, DevOps, etc., who manage a large volume of databases and/or\n> multiple PostgreSQL servers. The objective of this enhancement is to\n> obtain quick information about the current connection (session). I\n> believe that for a PostgreSQL administrator, it is not feasible to write\n> a plpgsql function and apply it to all databases (for example, imagine\n> managing over 200 databases). I have an example on GitHub\n> https://github.com/maiquelgrassi/DBA-toolkit/blob/main/cluster/dba_whoami_function.sql\n> of a plpgsql function demonstrating exactly what I believe is impractical\n> for the daily routine of a PostgreSQL professional. I see psql's\n> meta-commands as significant allies in daily work in productive\n> environments.\n\nThis seems like a reasonable idea to me.\n\n> postgres=# \\conninfo+\n> Current Connection Information\n> Attribute | Value\n> ----------------+----------------\n> Database | postgres\n> User | postgres\n> Server Version | 16.1\n> Server Address | 192.168.0.5/32\n> Server Port | 5433\n> Client Address | 192.168.0.5/32\n> Client Port | 52716\n> Session PID | 21624\n> (8 rows)\n\nMy first reaction is that this should instead return a single row with the\nsame set of columns for any connection type (the not-applicable ones would\njust be set to NULL). That would match the other meta-commands like \\l and\n\\du, and you could still get an expanded display with \\x if needed. Also,\nI think it would simplify the code a bit.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 6 Feb 2024 12:19:19 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "On 2024-02-06 19:19 +0100, Nathan Bossart wrote:\n> On Tue, Feb 06, 2024 at 05:27:01PM +0000, Maiquel Grassi wrote:\n> > postgres=# \\conninfo+\n> > Current Connection Information\n> > Attribute | Value\n> > ----------------+----------------\n> > Database | postgres\n> > User | postgres\n> > Server Version | 16.1\n> > Server Address | 192.168.0.5/32\n> > Server Port | 5433\n> > Client Address | 192.168.0.5/32\n> > Client Port | 52716\n> > Session PID | 21624\n> > (8 rows)\n> \n> My first reaction is that this should instead return a single row with the\n> same set of columns for any connection type (the not-applicable ones would\n> just be set to NULL). That would match the other meta-commands like \\l and\n> \\du, and you could still get an expanded display with \\x if needed. Also,\n> I think it would simplify the code a bit.\n\n+1 for a single-row result and triggering expanded display with \\x for\nconsistency with other commands.\n\n-- \nErik\n\n\n",
"msg_date": "Tue, 6 Feb 2024 20:10:54 +0100",
"msg_from": "Erik Wienhold <ewie@ewie.name>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "On 2024-02-06 19:19 +0100, Nathan Bossart wrote:\n > On Tue, Feb 06, 2024 at 05:27:01PM +0000, Maiquel Grassi wrote:\n > > postgres=# \\conninfo+\n > > Current Connection Information\n > > Attribute | Value\n > > ----------------+----------------\n > > Database | postgres\n > > User | postgres\n > > Server Version | 16.1\n > > Server Address | 192.168.0.5/32\n > > Server Port | 5433\n > > Client Address | 192.168.0.5/32\n > > Client Port | 52716\n > > Session PID | 21624\n > > (8 rows)\n >\n > My first reaction is that this should instead return a single row with the\n > same set of columns for any connection type (the not-applicable ones would\n > just be set to NULL). That would match the other meta-commands like \\l and\n > \\du, and you could still get an expanded display with \\x if needed. Also,\n > I think it would simplify the code a bit.\n\n +1 for a single-row result and triggering expanded display with \\x for\n consistency with other commands.\n\n--//--\n\nI made the adjustment in the code and updated the patch. I believe this is the format suggested by you all. Would this be it?\n\n[postgres@localhost bin]$ ./psql -h 192.168.0.220 -p 5433 -U postgres -d postgres\npsql (17devel, server 16.1)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"192.168.0.220\" at port \"5433\".\npostgres=# \\conninfo+\n Current Connection Information\n Attribute | Value\n----------------+------------------\n Database | postgres\n User | postgres\n Server Version | 16.1\n Server Address | 192.168.0.220/32\n Server Port | 5433\n Client Address | 192.168.0.220/32\n Client Port | 56606\n Session PID | 2424\n(8 rows)\n\n[postgres@localhost bin]$ ./psql\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5432\".\npostgres=# \\conninfo+\nCurrent Connection Information\n Attribute | Value\n----------------+----------\n Database | postgres\n User | postgres\n Server Version | 17devel\n Server Address |\n Server Port | 5432\n Client Address |\n Client Port |\n Session PID | 30216\n(8 rows)\n\n[postgres@localhost bin]$ ./psql -h localhost\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"localhost\" (address \"::1\") at port \"5432\".\npostgres=# \\conninfo+\nCurrent Connection Information\n Attribute | Value\n----------------+----------\n Database | postgres\n User | postgres\n Server Version | 17devel\n Server Address | ::1/128\n Server Port | 5432\n Client Address | ::1/128\n Client Port | 46872\n Session PID | 30220\n(8 rows)\n\n[postgres@localhost bin]$ ./psql -h 127.0.0.1\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"127.0.0.1\" at port \"5432\".\npostgres=# \\conninfo+\nCurrent Connection Information\n Attribute | Value\n----------------+--------------\n Database | postgres\n User | postgres\n Server Version | 17devel\n Server Address | 127.0.0.1/32\n Server Port | 5432\n Client Address | 127.0.0.1/32\n Client Port | 34924\n Session PID | 30223\n(8 rows)\n\nRegards,\nMaiquel O. Grassi.",
"msg_date": "Tue, 6 Feb 2024 20:52:09 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "On Tue, Feb 06, 2024 at 08:52:09PM +0000, Maiquel Grassi wrote:\n> I made the adjustment in the code and updated the patch. I believe this\n> is the format suggested by you all. Would this be it?\n\nI was thinking something more like\n\n SELECT pg_catalog.current_database() AS \"Database\",\n current_user AS \"User\",\n pg_catalog.current_setting('server_version') AS \"Server Version\",\n pg_catalog.inet_server_addr() AS \"Server Address\",\n pg_catalog.current_setting('port') AS \"Port\",\n pg_catalog.inet_client_addr() AS \"Client Address\",\n pg_catalog.inet_client_port() AS \"Client Port\",\n pg_catalog.pg_backend_pid() AS \"Session PID\";\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 6 Feb 2024 15:06:05 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "On Tue, Feb 06, 2024 at 03:06:05PM -0600, Nathan Bossart wrote:\n> On Tue, Feb 06, 2024 at 08:52:09PM +0000, Maiquel Grassi wrote:\n>> I made the adjustment in the code and updated the patch. I believe this\n>> is the format suggested by you all. Would this be it?\n> \n> I was thinking something more like\n> \n> SELECT pg_catalog.current_database() AS \"Database\",\n> current_user AS \"User\",\n> pg_catalog.current_setting('server_version') AS \"Server Version\",\n> pg_catalog.inet_server_addr() AS \"Server Address\",\n> pg_catalog.current_setting('port') AS \"Port\",\n> pg_catalog.inet_client_addr() AS \"Client Address\",\n> pg_catalog.inet_client_port() AS \"Client Port\",\n> pg_catalog.pg_backend_pid() AS \"Session PID\";\n\n... although that seems to be missing items like the socket directory and\nthe host.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 6 Feb 2024 15:12:05 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "On Tue, Feb 06, 2024 at 08:52:09PM +0000, Maiquel Grassi wrote:\n > I made the adjustment in the code and updated the patch. I believe this\n > is the format suggested by you all. Would this be it?\n\n I was thinking something more like\n\n SELECT pg_catalog.current_database() AS \"Database\",\n current_user AS \"User\",\n pg_catalog.current_setting('server_version') AS \"Server Version\",\n pg_catalog.inet_server_addr() AS \"Server Address\",\n pg_catalog.current_setting('port') AS \"Port\",\n pg_catalog.inet_client_addr() AS \"Client Address\",\n pg_catalog.inet_client_port() AS \"Client Port\",\n pg_catalog.pg_backend_pid() AS \"Session PID\";\n\n--//--\n\nGood, I had misunderstood. I liked this adjustment. Now it truly aligns with the central idea of the other extended meta-commands.\n\n[postgres@localhost bin]$ ./psql -h 192.168.0.220 -p 5433 -U postgres -d postgres\npsql (17devel, server 16.1)\nType \"help\" for help.\n\npostgres=# \\conninfo+\n Current Connection Information\n Database | User | Server Version | Server Address | Port | Client Address | Client Port | Session PID\n----------+----------+----------------+----------------+------+----------------+-------------+-------------\n postgres | postgres | 16.1 | 192.168.0.220 | 5433 | 192.168.0.220 | 57112 | 22120\n(1 row)\n\npostgres=# \\q\n[postgres@localhost bin]$ ./psql\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo+\n Current Connection Information\n Database | User | Server Version | Server Address | Port | Client Address | Client Port | Session PID\n----------+----------+----------------+----------------+------+----------------+-------------+-------------\n postgres | postgres | 17devel | | 5432 | | | 31430\n(1 row)\n\npostgres=# \\q\n[postgres@localhost bin]$ ./psql -h localhost\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo+\n Current Connection Information\n Database | User | Server Version | Server Address | Port | Client Address | Client Port | Session PID\n----------+----------+----------------+----------------+------+----------------+-------------+-------------\n postgres | postgres | 17devel | ::1 | 5432 | ::1 | 46918 | 31433\n(1 row)\n\npostgres=# \\q\n[postgres@localhost bin]$ ./psql -h 127.0.0.1\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo+\n Current Connection Information\n Database | User | Server Version | Server Address | Port | Client Address | Client Port | Session PID\n----------+----------+----------------+----------------+------+----------------+-------------+-------------\n postgres | postgres | 17devel | 127.0.0.1 | 5432 | 127.0.0.1 | 34970 | 31435\n(1 row)\n\nRegards,\nMaiquel O. Grassi.",
"msg_date": "Tue, 6 Feb 2024 21:39:20 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "On Tue, Feb 06, 2024 at 03:06:05PM -0600, Nathan Bossart wrote:\n > On Tue, Feb 06, 2024 at 08:52:09PM +0000, Maiquel Grassi wrote:\n >> I made the adjustment in the code and updated the patch. I believe this\n >> is the format suggested by you all. Would this be it?\n >\n > I was thinking something more like\n >\n > SELECT pg_catalog.current_database() AS \"Database\",\n > current_user AS \"User\",\n > pg_catalog.current_setting('server_version') AS \"Server Version\",\n > pg_catalog.inet_server_addr() AS \"Server Address\",\n > pg_catalog.current_setting('port') AS \"Port\",\n > pg_catalog.inet_client_addr() AS \"Client Address\",\n > pg_catalog.inet_client_port() AS \"Client Port\",\n > pg_catalog.pg_backend_pid() AS \"Session PID\";\n\n ... although that seems to be missing items like the socket directory and\n the host.\n\n--//--\n\nMy initial idea has always been that they should continue to appear because \\conninfo+ should show all the things that \\conninfo shows and add more information. I think that's the purpose of the 'plus.' Now we're on a better path than the initial one. We can still add the socket directory and the host.\n\nRegards,\nMaiquel O. Grassi.\n\n\n\n\n\n\n\n \nOn Tue, Feb 06, 2024 at 03:06:05PM -0600, Nathan Bossart wrote:\n > On Tue, Feb 06, 2024 at 08:52:09PM +0000, Maiquel Grassi wrote:\n >> I made the adjustment in the code and updated the patch. I believe this\n >> is the format suggested by you all. Would this be it?\n >\n > I was thinking something more like\n >\n > SELECT pg_catalog.current_database() AS \"Database\",\n > current_user AS \"User\",\n > pg_catalog.current_setting('server_version') AS \"Server Version\",\n > pg_catalog.inet_server_addr() AS \"Server Address\",\n > pg_catalog.current_setting('port') AS \"Port\",\n > pg_catalog.inet_client_addr() AS \"Client Address\",\n > pg_catalog.inet_client_port() AS \"Client Port\",\n > pg_catalog.pg_backend_pid() AS \"Session PID\";\n \n ... although that seems to be missing items like the socket directory and\n the host.\n\n--//--\n\n\nMy initial idea has always been that they should continue to appear because \\conninfo+ should show all the things\n that \\conninfo shows and add more information. I think that's the purpose of the 'plus.' Now we're on a better path than the initial one. We can still add the socket directory and the host.\n\n\nRegards,\nMaiquel O. Grassi.",
"msg_date": "Tue, 6 Feb 2024 21:45:54 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "On Tue, Feb 06, 2024 at 09:45:54PM +0000, Maiquel Grassi wrote:\n> My initial idea has always been that they should continue to appear\n> because \\conninfo+ should show all the things that \\conninfo shows and\n> add more information. I think that's the purpose of the 'plus.' Now we're\n> on a better path than the initial one. We can still add the socket\n> directory and the host.\n\nAgreed.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Tue, 6 Feb 2024 15:50:22 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "On Tue, Feb 06, 2024 at 09:45:54PM +0000, Maiquel Grassi wrote:\n > My initial idea has always been that they should continue to appear\n > because \\conninfo+ should show all the things that \\conninfo shows and\n > add more information. I think that's the purpose of the 'plus.' Now we're\n > on a better path than the initial one. We can still add the socket\n > directory and the host.\n\n Agreed.\n\n--//--\n\nI believe it's resolved reasonably well this way:\n\nSELECT\n pg_catalog.current_database() AS \"Database\",\n current_user AS \"User\",\n pg_catalog.current_setting('server_version') AS \"Server Version\",\n CASE\n WHEN pg_catalog.inet_server_addr() IS NULL\n THEN 'NULL'\n ELSE pg_catalog.inet_server_addr()::text\n END AS \"Server Address\",\n pg_catalog.current_setting('port') AS \"Port\",\n CASE\n WHEN pg_catalog.inet_client_addr() IS NULL\n THEN 'NULL'\n ELSE pg_catalog.inet_client_addr()::text\n END AS \"Client Address\",\n CASE\n WHEN pg_catalog.inet_client_port() IS NULL\n THEN 'NULL'\n ELSE pg_catalog.inet_client_port()::text\n END AS \"Client Port\",\n pg_catalog.pg_backend_pid() AS \"Session PID\",\n CASE\n WHEN pg_catalog.current_setting('unix_socket_directories') = ''\n THEN 'NULL'\n ELSE pg_catalog.current_setting('unix_socket_directories')\n END AS \"Socket Directory\",\n CASE\n WHEN\n pg_catalog.inet_server_addr() IS NULL\n AND pg_catalog.inet_client_addr() IS NULL\n THEN 'NULL'\n WHEN\n pg_catalog.inet_server_addr() = pg_catalog.inet_client_addr()\n THEN 'localhost'\n ELSE pg_catalog.inet_server_addr()::text\n END AS \"Host\";\n\nSee below the tests:\n\n[postgres@localhost bin]$ ./psql\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | User | Server Version | Server Address | Port | Client Address | Client Port | Session PID | Socket Directory | Host\n----------+----------+----------------+----------------+------+----------------+-------------+-------------+------------------+------\n postgres | postgres | 17devel | NULL | 5432 | NULL | NULL | 14348 | /tmp | NULL\n(1 row)\n\n\n[postgres@localhost bin]$ ./psql -h localhost\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"localhost\" (address \"::1\") at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | User | Server Version | Server Address | Port | Client Address | Client Port | Session PID | Socket Directory | Host\n----------+----------+----------------+----------------+------+----------------+-------------+-------------+------------------+-----------\n postgres | postgres | 17devel | ::1/128 | 5432 | ::1/128 | 46988 | 14353 | /tmp | localhost\n(1 row)\n\n\n[postgres@localhost bin]$ ./psql -h ::1\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"::1\" at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | User | Server Version | Server Address | Port | Client Address | Client Port | Session PID | Socket Directory | Host\n----------+----------+----------------+----------------+------+----------------+-------------+-------------+------------------+-----------\n postgres | postgres | 17devel | ::1/128 | 5432 | ::1/128 | 46990 | 14356 | /tmp | localhost\n(1 row)\n\n\n[postgres@localhost bin]$ ./psql -h 127.0.0.1\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"127.0.0.1\" at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | User | Server Version | Server Address | Port | Client Address | Client Port | Session PID | Socket Directory | Host\n----------+----------+----------------+----------------+------+----------------+-------------+-------------+------------------+-----------\n postgres | postgres | 17devel | 127.0.0.1/32 | 5432 | 127.0.0.1/32 | 35042 | 14359 | /tmp | localhost\n(1 row)\n\n\n[postgres@localhost bin]$ ./psql -h 192.168.0.5 -p 5433 -U postgres -d postgres\npsql (17devel, server 16.1)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"192.168.0.5\" at port \"5433\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | User | Server Version | Server Address | Port | Client Address | Client Port | Session PID | Socket Directory | Host\n----------+----------+----------------+----------------+------+----------------+-------------+-------------+------------------+-----------\n postgres | postgres | 16.1 | 192.168.0.5/32 | 5433 | 192.168.0.5/32 | 52783 | 18212 | NULL | localhost\n(1 row)\n\nRegards,\nMaiquel O. Grassi.",
"msg_date": "Wed, 7 Feb 2024 04:13:40 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "On 2024-02-07 05:13 +0100, Maiquel Grassi wrote:\n> On Tue, Feb 06, 2024 at 09:45:54PM +0000, Maiquel Grassi wrote:\n> > My initial idea has always been that they should continue to appear\n> > because \\conninfo+ should show all the things that \\conninfo shows and\n> > add more information. I think that's the purpose of the 'plus.' Now we're\n> > on a better path than the initial one. We can still add the socket\n> > directory and the host.\n> \n> Agreed.\n> \n> --//--\n> \n> I believe it's resolved reasonably well this way:\n> \n> SELECT\n> pg_catalog.current_database() AS \"Database\",\n> current_user AS \"User\",\n> pg_catalog.current_setting('server_version') AS \"Server Version\",\n> CASE\n> WHEN pg_catalog.inet_server_addr() IS NULL\n> THEN 'NULL'\n> ELSE pg_catalog.inet_server_addr()::text\n> END AS \"Server Address\",\n\nShould be NULL instead of string 'NULL'. So the entire CASE expression\nis redundant and you can just return pg_catalog.inet_server_addr().\n\n> pg_catalog.current_setting('port') AS \"Port\",\n> CASE\n> WHEN pg_catalog.inet_client_addr() IS NULL\n> THEN 'NULL'\n> ELSE pg_catalog.inet_client_addr()::text\n> END AS \"Client Address\",\n> CASE\n> WHEN pg_catalog.inet_client_port() IS NULL\n> THEN 'NULL'\n> ELSE pg_catalog.inet_client_port()::text\n> END AS \"Client Port\",\n\nSame here.\n\n> pg_catalog.pg_backend_pid() AS \"Session PID\",\n> CASE\n> WHEN pg_catalog.current_setting('unix_socket_directories') = ''\n> THEN 'NULL'\n> ELSE pg_catalog.current_setting('unix_socket_directories')\n> END AS \"Socket Directory\",\n\nThe CASE expression can be simplified to:\n\n\tnullif(pg_catalog.current_setting('unix_socket_directories'), '')\n\n> CASE\n> WHEN\n> pg_catalog.inet_server_addr() IS NULL\n> AND pg_catalog.inet_client_addr() IS NULL\n> THEN 'NULL'\n> WHEN\n> pg_catalog.inet_server_addr() = pg_catalog.inet_client_addr()\n> THEN 'localhost'\n\nIs it safe to assume localhost here? \\conninfo prints localhost only\nwhen I connect with psql -hlocalhost:\n\n\t$ psql -hlocalhost postgres\n\tpsql (16.1)\n\tpostgres=# \\conninfo\n\tYou are connected to database \"postgres\" as user \"ewie\" on host \"localhost\" (address \"::1\") at port \"5432\".\n\tpostgres=# \\q\n\n\t$ psql -h127.0.0.1 postgres\n\tpsql (16.1)\n\tpostgres=# \\conninfo\n\tYou are connected to database \"postgres\" as user \"ewie\" on host \"127.0.0.1\" at port \"5432\".\n\n> ELSE pg_catalog.inet_server_addr()::text\n> END AS \"Host\";\n\n-- \nErik\n\n\n",
"msg_date": "Wed, 7 Feb 2024 10:54:21 +0100",
"msg_from": "Erik Wienhold <ewie@ewie.name>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "This is a good idea about extended connection info.\n\nOn 07.02.2024 07:13, Maiquel Grassi wrote:\n> SELECT\n> ...\n> current_user AS \"User\",\n\nThis will be inconsistent with \\conninfo.\n\\conninfo returns authenticated user (PQuser), not the current_user.\nIt might be worth showing current_user, session_user, and authenticated user,\nbut I can't find the appropriate sql function for PQuser.\n\nWhat about to include system_user function? It shows useful authentication details.\n\nAlso, it seems that the verbose parameter in the listConnectionInformation\nis unnecessary.\n\n-- \nPavel Luzanov\nPostgres Professional:https://postgrespro.com\n\n\n\n\n\n\nThis is a good idea about extended connection info.\n\n\n On 07.02.2024 07:13, Maiquel Grassi wrote:\n\n\nSELECT\n...\n\n \n current_user AS \"User\",\n\nThis will be inconsistent with \\conninfo.\n\\conninfo returns authenticated user (PQuser), not the current_user.\nIt might be worth showing current_user, session_user, and authenticated user,\nbut I can't find the appropriate sql function for PQuser.\n\nWhat about to include system_user function? It shows useful authentication details.\n\nAlso, it seems that the verbose parameter in the listConnectionInformation\nis unnecessary.\n\n-- \nPavel Luzanov\nPostgres Professional: https://postgrespro.com",
"msg_date": "Wed, 7 Feb 2024 15:35:34 +0300",
"msg_from": "Pavel Luzanov <p.luzanov@postgrespro.ru>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "On 2024-02-07 05:13 +0100, Maiquel Grassi wrote:\n > On Tue, Feb 06, 2024 at 09:45:54PM +0000, Maiquel Grassi wrote:\n > > My initial idea has always been that they should continue to appear\n > > because \\conninfo+ should show all the things that \\conninfo shows and\n > > add more information. I think that's the purpose of the 'plus.' Now we're\n > > on a better path than the initial one. We can still add the socket\n > > directory and the host.\n >\n > Agreed.\n >\n > --//--\n >\n > I believe it's resolved reasonably well this way:\n >\n > SELECT\n > pg_catalog.current_database() AS \"Database\",\n > current_user AS \"User\",\n > pg_catalog.current_setting('server_version') AS \"Server Version\",\n > CASE\n > WHEN pg_catalog.inet_server_addr() IS NULL\n > THEN 'NULL'\n > ELSE pg_catalog.inet_server_addr()::text\n > END AS \"Server Address\",\n\n Should be NULL instead of string 'NULL'. So the entire CASE expression\n is redundant and you can just return pg_catalog.inet_server_addr().\n\n > pg_catalog.current_setting('port') AS \"Port\",\n > CASE\n > WHEN pg_catalog.inet_client_addr() IS NULL\n > THEN 'NULL'\n > ELSE pg_catalog.inet_client_addr()::text\n > END AS \"Client Address\",\n > CASE\n > WHEN pg_catalog.inet_client_port() IS NULL\n > THEN 'NULL'\n > ELSE pg_catalog.inet_client_port()::text\n > END AS \"Client Port\",\n\n Same here.\n\n > pg_catalog.pg_backend_pid() AS \"Session PID\",\n > CASE\n > WHEN pg_catalog.current_setting('unix_socket_directories') = ''\n > THEN 'NULL'\n > ELSE pg_catalog.current_setting('unix_socket_directories')\n > END AS \"Socket Directory\",\n\n The CASE expression can be simplified to:\n\n nullif(pg_catalog.current_setting('unix_socket_directories'), '')\n\n > CASE\n > WHEN\n > pg_catalog.inet_server_addr() IS NULL\n > AND pg_catalog.inet_client_addr() IS NULL\n > THEN 'NULL'\n > WHEN\n > pg_catalog.inet_server_addr() = pg_catalog.inet_client_addr()\n > THEN 'localhost'\n\n Is it safe to assume localhost here? \\conninfo prints localhost only\n when I connect with psql -hlocalhost:\n\n $ psql -hlocalhost postgres\n psql (16.1)\n postgres=# \\conninfo\n You are connected to database \"postgres\" as user \"ewie\" on host \"localhost\" (address \"::1\") at port \"5432\".\n postgres=# \\q\n\n $ psql -h127.0.0.1 postgres\n psql (16.1)\n postgres=# \\conninfo\n You are connected to database \"postgres\" as user \"ewie\" on host \"127.0.0.1\" at port \"5432\".\n\n > ELSE pg_catalog.inet_server_addr()::text\n > END AS \"Host\";\n\n--//--\n\nThere really was no need for the CASES. However, they helped visualize the psql output since for the null value, no word is printed on the screen. I made the adjustment by removing this redundancy.\n\nRegarding the \"Host\" column, the most reliable way to solve this, I believe, is by using the \"host\" variable. So it's necessary to declare char *host = PQhost(pset.db); in listConnectionInformation() and use it in the SQL (see patch v5). This way, we have the same return from \\conninfo reliably.\n\nOnce again, I ran a series of tests.\n\n[postgres@localhost bin]$ ./psql\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | User | Server Version | Server Address | Server Port | Client Address | Client Port | Session PID | Socket Directory | Host\n----------+----------+----------------+----------------+-------------+----------------+-------------+-------------+------------------+------\n postgres | postgres | 17devel | | 5432 | | | 15898 | /tmp |\n(1 row)\n\npostgres=# \\q\n[postgres@localhost bin]$ ./psql -h localhost\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"localhost\" (address \"::1\") at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | User | Server Version | Server Address | Server Port | Client Address | Client Port | Session PID | Socket Directory | Host\n----------+----------+----------------+----------------+-------------+----------------+-------------+-------------+------------------+-----------\n postgres | postgres | 17devel | ::1 | 5432 | ::1 | 47012 | 15900 | /tmp | localhost\n(1 row)\n\npostgres=# \\q\n[postgres@localhost bin]$ ./psql -h ::1\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"::1\" at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | User | Server Version | Server Address | Server Port | Client Address | Client Port | Session PID | Socket Directory | Host\n----------+----------+----------------+----------------+-------------+----------------+-------------+-------------+------------------+------\n postgres | postgres | 17devel | ::1 | 5432 | ::1 | 47014 | 15905 | /tmp | ::1\n(1 row)\n\npostgres=# \\q\n[postgres@localhost bin]$ ./psql -h 127.0.0.1\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"127.0.0.1\" at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | User | Server Version | Server Address | Server Port | Client Address | Client Port | Session PID | Socket Directory | Host\n----------+----------+----------------+----------------+-------------+----------------+-------------+-------------+------------------+-----------\n postgres | postgres | 17devel | 127.0.0.1 | 5432 | 127.0.0.1 | 35066 | 15908 | /tmp | 127.0.0.1\n(1 row)\n\npostgres=# \\q\n[postgres@localhost bin]$ ./psql -h 192.168.0.5 -p 5432 -d postgres -U postgres\npsql (17devel, server 14.3)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"192.168.0.5\" at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | User | Server Version | Server Address | Server Port | Client Address | Client Port | Session PID | Socket Directory | Host\n----------+----------+----------------+----------------+-------------+----------------+-------------+-------------+------------------+-------------\n postgres | postgres | 14.3 | 192.168.0.5 | 5432 | 192.168.0.5 | 60904 | 29264 | | 192.168.0.5\n\nRegards,\nMaiquel O. Grassi.",
"msg_date": "Wed, 7 Feb 2024 12:41:56 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "This is a good idea about extended connection info.\n\n On 07.02.2024 07:13, Maiquel Grassi wrote:\nSELECT\n...\n current_user AS \"User\",\n\n This will be inconsistent with \\conninfo.\n \\conninfo returns authenticated user (PQuser), not the current_user.\n It might be worth showing current_user, session_user, and authenticated user,\n but I can't find the appropriate sql function for PQuser.\n\n What about to include system_user function? It shows useful authentication details.\n\n Also, it seems that the verbose parameter in the listConnectionInformation\n is unnecessary.\n\n--//--\n\nHi,\n\nTks Pavel.\n\nAnalyzing the functions' code more thoroughly, it seems to make more sense.\nI liked your suggestions and implemented them for validation.\nRegarding \"system_user,\" I believe it is valid and also added it to the row.\n\n\"Also, it seems that the verbose parameter in the listConnectionInformation is unnecessary.\"\nCould you point out exactly the line or code snippet you are referring to?\n\nTo print the string from the \"Authenticated User\" column, I chose to use PQuser(pset.db) directly. I did the same for the \"Host\" column, opting for PQhost(pset.db). This does not contradict the result of \\conninfo.\n\nHere are the tests as usual, and v6 patch.\n\n[postgres@localhost bin]$ ./psql\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | Authenticated User | Current User | Session User | System User | Server Version | Server Address | Server Port | Client Address | Client Port | Session PID | Socket Directory | Host\n----------+--------------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+-------------+------------------+------\n postgres | postgres | postgres | postgres | | 17devel | | 5432 | | | 17240 | /tmp |\n(1 row)\n\npostgres=# \\q\n[postgres@localhost bin]$ ./psql -h ::1\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"::1\" at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | Authenticated User | Current User | Session User | System User | Server Version | Server Address | Server Port | Client Address | Client Port | Session PID | Socket Directory | Host\n----------+--------------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+-------------+------------------+------\n postgres | postgres | postgres | postgres | | 17devel | ::1 | 5432 | ::1 | 47024 | 17242 | /tmp | ::1\n(1 row)\n\npostgres=# \\q\n[postgres@localhost bin]$ ./psql -h 127.0.0.1\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"127.0.0.1\" at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | Authenticated User | Current User | Session User | System User | Server Version | Server Address | Server Port | Client Address | Client Port | Session PID | Socket Directory | Host\n----------+--------------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+-------------+------------------+-----------\n postgres | postgres | postgres | postgres | | 17devel | 127.0.0.1 | 5432 | 127.0.0.1 | 35076 | 17245 | /tmp | 127.0.0.1\n(1 row)\n\npostgres=# \\q\n[postgres@localhost bin]$ ./psql -h localhost\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"localhost\" (address \"::1\") at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | Authenticated User | Current User | Session User | System User | Server Version | Server Address | Server Port | Client Address | Client Port | Session PID | Socket Directory | Host\n----------+--------------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+-------------+------------------+-----------\n postgres | postgres | postgres | postgres | | 17devel | ::1 | 5432 | ::1 | 47028 | 17248 | /tmp | localhost\n(1 row)\n\npostgres=# \\q\n[postgres@localhost bin]$ ./psql -h 192.168.0.5 -p 5433 -d postgres -U postgres\npsql (17devel, server 16.1)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"192.168.0.5\" at port \"5433\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | Authenticated User | Current User | Session User | System User | Server Version | Server Address | Server Port | Client Address | Client Port | Session PID | Socket Directory | Host\n----------+--------------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+-------------+------------------+-------------\n postgres | postgres | postgres | postgres | | 16.1 | 192.168.0.5 | 5433 | 192.168.0.5 | 60115 | 28896 | | 192.168.0.5\n(1 row)\n\nRegards,\nMaiquel O. Grassi.",
"msg_date": "Wed, 7 Feb 2024 14:47:31 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi,Maiquel!\n\n\nOn 07.02.2024 17:47, Maiquel Grassi wrote:\n> \"Also, it seems that the verbose parameter in the \n> listConnectionInformation is unnecessary.\" Could you point out exactly \n> the line or code snippet you are referring to?\n\n+bool\n+listConnectionInformation(const char *pattern,*bool verbose*)\n\nI mean that parameter verbose is not used in the function body and listConnectionInformation called only in verbose mode.\n\n-- \nPavel Luzanov\nPostgres Professional:https://postgrespro.com\n\n\n\n\n\n\nHi, Maiquel!\n\nOn 07.02.2024 17:47, Maiquel Grassi\n wrote:\n\n\n\n\n\"Also, it seems that the verbose parameter in the listConnectionInformation is unnecessary.\"\nCould you point out exactly the line or code snippet you are referring to?\n\n\n+bool\n+listConnectionInformation(const char *pattern, bool verbose)\n\nI mean that parameter verbose is not used in the function body and listConnectionInformation called only in verbose mode.\n\n-- \nPavel Luzanov\nPostgres Professional: https://postgrespro.com",
"msg_date": "Wed, 7 Feb 2024 19:40:28 +0300",
"msg_from": "Pavel Luzanov <p.luzanov@postgrespro.ru>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "> Hi, Maiquel!\n>\n> On 07.02.2024 17:47, Maiquel Grassi wrote:\n\n> \"Also, it seems that the verbose parameter in the listConnectionInformation is unnecessary.\"\n> Could you point out exactly the line or code snippet you are referring to?\n\n> +bool\n> +listConnectionInformation(const char *pattern, bool verbose)\n>\n> I mean that parameter verbose is not used in the function body and listConnectionInformation called only in verbose mode.\n\n\n--//--\n\nThere really was no need for the bool verbose. Therefore, it was removed.\nRegarding the \"system_user\" function, as it is relatively new, I added\nthe necessary handling to avoid conflicts with versions lower than version 16.\n\nI believe in v7 patch we have a quite substantial meta-command feature.\n\nI validated the \"System User\" column for three versions. This way, we have a sample:\n\n[postgres@localhost bin]$ ./psql -h 192.168.0.5 -p 5432 -U postgres -d postgres\n\npsql (17devel, server 14.3)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"192.168.0.5\" at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | Authenticated User | Current User | Session User | Session PID | Server Version | Server Address | Server Port | Client Address | Client Port | Socket Directory | Host\n----------+--------------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+------------------+-------------\n postgres | postgres | postgres | postgres | 9008 | 14.3 | 192.168.0.5 | 5432 | 192.168.0.5 | 63631 | | 192.168.0.5\n(1 row)\n\npostgres=# \\q\n[postgres@localhost bin]$ ./psql -h 192.168.0.5 -p 5433 -U postgres -d postgres\npsql (17devel, server 16.1)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"192.168.0.5\" at port \"5433\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | Authenticated User | System User | Current User | Session User | Session PID | Server Version | Server Address | Server Port | Client Address | Client Port | Socket Directory | Host\n----------+--------------------+-------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+------------------+-------------\n postgres | postgres | | postgres | postgres | 3348 | 16.1 | 192.168.0.5 | 5433 | 192.168.0.5 | 63633 | | 192.168.0.5\n(1 row)\n\npostgres=# \\q\n[postgres@localhost bin]$ ./psql -h localhost\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"localhost\" (address \"::1\") at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | Authenticated User | System User | Current User | Session User | Session PID | Server Version | Server Address | Server Port | Client Address | Client Port | Socket Directory | Host\n----------+--------------------+-------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+------------------+-----------\n postgres | postgres | | postgres | postgres | 26147 | 17devel | ::1 | 5432 | ::1 | 47466 | /tmp | localhost\n(1 row)\n\nRegards,\nMaiquel O. Grassi.",
"msg_date": "Wed, 7 Feb 2024 20:13:15 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi Maiquel\n\nOn 07.02.24 21:13, Maiquel Grassi wrote:\n>\n> I believe in v7 patch we have a quite substantial meta-command feature.\n>\n>\nThanks for implementing this. I find it very handy.\n\nI was just wondering if a \"permission denied\" error for non-superusers\nis the best choice for \"\\conninfo+\":\n\npostgres=> \\conninfo+\nERROR: permission denied to examine \"unix_socket_directories\"\nDETAIL: Only roles with privileges of the \"pg_read_all_settings\" role\nmay examine this parameter.\n\n.. since it is not the case with \"\\conninfo\":\n\npostgres=> \\conninfo\nYou are connected to database \"postgres\" as user \"jim\" via socket in\n\"/tmp\" at port \"5432\".\n\nPerhaps excluding the column from the result set or returning NULL in\nthe affected columns would be less confusing?\n\nThere are also some indentation issues in your patch:\n\n/home/jim/Downloads/v7-0001-psql-meta-command-conninfo-plus.patch:142:\nindent with spaces.\n PGresult *res;\n/home/jim/Downloads/v7-0001-psql-meta-command-conninfo-plus.patch:143:\nindent with spaces.\n PQExpBufferData buf;\n/home/jim/Downloads/v7-0001-psql-meta-command-conninfo-plus.patch:144:\nindent with spaces.\n printQueryOpt myopt = pset.popt;\n/home/jim/Downloads/v7-0001-psql-meta-command-conninfo-plus.patch:146:\nindent with spaces.\n initPQExpBuffer(&buf);\n/home/jim/Downloads/v7-0001-psql-meta-command-conninfo-plus.patch:148:\nindent with spaces.\n printfPQExpBuffer(&buf,\nwarning: squelched 34 whitespace errors\nwarning: 39 lines add whitespace errors.\n\nLooking forward to see the documentation and tests!\n\n-- \nJim\n\n\n\n",
"msg_date": "Thu, 8 Feb 2024 12:01:55 +0100",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi,\n\nOn 07.02.2024 23:13, Maiquel Grassi wrote:\n\n> Regarding the \"system_user\" function, as it is relatively new, I added \n> the necessary handling to avoid conflicts with versions lower than \n> version 16.\n>\nYes, that's rights.\n\nA couple of doubts about the implementation details.\nBut keep in mind that I'm not very good at programming in the C language.\nI hope for the help of more experienced developers.\n\n\n1.\n+\t\t\tif (db == NULL)\n+\t\t\t\tprintf(_(\"You are currently not connected to a database.\\n\"));\n\nThis check is performed for \\conninfo, but not for \\conninfo+.\n\n\n2.\nSome values (address, socket) are evaluated separately for \\conninfo\n(via C functions) and for \\conninfo+ (via sql functions).\nIt may be worth evaluating them in one place. But I'm not sure about that.\n\nThe final version of the patch will require changes to the documentation and tests.\n\n-- \nPavel Luzanov\nPostgres Professional:https://postgrespro.com\n\n\n\n\n\n\nHi,\n\n\n\nOn 07.02.2024 23:13, Maiquel Grassi wrote:\n\n\n\nRegarding the \"system_user\" function, as it is relatively new, I added\nthe necessary handling to avoid conflicts with versions lower than version 16.\n\n\n\nYes, that's rights.\n\nA couple of doubts about the implementation details.\nBut keep in mind that I'm not very good at programming in the C language.\nI hope for the help of more experienced developers.\n\n\n1.\n+\t\t\tif (db == NULL)\n+\t\t\t\tprintf(_(\"You are currently not connected to a database.\\n\"));\n\nThis check is performed for \\conninfo, but not for \\conninfo+.\n\n\n2.\nSome values (address, socket) are evaluated separately for \\conninfo\n(via C functions) and for \\conninfo+ (via sql functions).\nIt may be worth evaluating them in one place. But I'm not sure about that.\n\nThe final version of the patch will require changes to the documentation and tests.\n\n\n-- \nPavel Luzanov\nPostgres Professional: https://postgrespro.com",
"msg_date": "Thu, 8 Feb 2024 14:01:55 +0300",
"msg_from": "Pavel Luzanov <p.luzanov@postgrespro.ru>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "> Hi,\n\n> On 07.02.2024 23:13, Maiquel Grassi wrote:\n\n\n> Regarding the \"system_user\" function, as it is relatively new, I added\n> the necessary handling to avoid conflicts with versions lower than version 16.\n\n\n> Yes, that's rights.\n>\n> A couple of doubts about the implementation details.\n> But keep in mind that I'm not very good at programming in the C language.\n> I hope for the help of more experienced developers.\n>\n>\n> 1.\n> + if (db == NULL)\n> + printf(_(\"You are currently not connected to a database.\\n\"));\n>\n> This check is performed for \\conninfo, but not for \\conninfo+.\n>\n>\n> 2.\n> Some values (address, socket) are evaluated separately for \\conninfo\n> (via C functions) and for \\conninfo+ (via sql functions).\n> It may be worth evaluating them in one place. But I'm not sure about that.\n>\n> The final version of the patch will require changes to the documentation and tests.\n\n--//--\n\nHi Pavel,\n\nFirst of all, thank you very much for your observations.\n\n1. The connection check for the case of \\conninfo+ is handled by \"describe.c\" itself since it deals with queries. I might be mistaken, but I believe that by using \"printQuery()\" via \"describe.c\", this is already ensured, and there is no need to evaluate the connection status.\n\n2. I believe that by implementing the evaluations separately as they are, it becomes easier to perform future maintenance by minimizing the mixing of C code with SQL code as much as possible. However, certainly, the possibility of a better suggestion than mine remains open.\n\nRegards,\nMaiquel O. Grassi.\n\n\n\n\n\n\n\n> Hi,\n\n> On 07.02.2024 23:13, Maiquel Grassi wrote:\n\n\n> Regarding the \"system_user\" function, as it is relatively new, I added\n> the necessary handling to avoid conflicts with versions lower than version 16.\n\n\n> Yes, that's rights.\n> \n> A couple of doubts about the implementation details.\n> But keep in mind that I'm not very good at programming in the C language.\n> I hope for the help of more experienced developers.\n> \n> \n> 1.\n> +\t\t\tif (db == NULL)\n> +\t\t\t\tprintf(_(\"You are currently not connected to a database.\\n\"));\n> \n> This check is performed for \\conninfo, but not for \\conninfo+.\n> \n> \n> 2.\n> Some values (address, socket) are evaluated separately for \\conninfo\n> (via C functions) and for \\conninfo+ (via sql functions).\n> It may be worth evaluating them in one place. But I'm not sure about that.\n> \n> The final version of the patch will require changes to the documentation and tests.--//--Hi Pavel,First of all, thank you very much for your observations.1. The connection check for the case of \\conninfo+ is handled by \"describe.c\" itself since it deals with queries. I might be mistaken, but I believe that by using \"printQuery()\" via \"describe.c\", this is already ensured, and there is no need to evaluate the connection status.2. I believe that by implementing the evaluations separately as they are, it becomes easier to perform future maintenance by minimizing the mixing of C code with SQL code as much as possible. However, certainly, the possibility of a better suggestion than mine remains open.Regards,Maiquel O. Grassi.",
"msg_date": "Thu, 8 Feb 2024 14:58:19 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "> On 07.02.24 21:13, Maiquel Grassi wrote:\n>>\n>> I believe in v7 patch we have a quite substantial meta-command feature.\n>>\n>>\n> Thanks for implementing this. I find it very handy.\n>\n> I was just wondering if a \"permission denied\" error for non-superusers\n> is the best choice for \"\\conninfo+\":\n>\n> postgres=> \\conninfo+\n> ERROR: permission denied to examine \"unix_socket_directories\"\n> DETAIL: Only roles with privileges of the \"pg_read_all_settings\" role\n> may examine this parameter.\n>\n> .. since it is not the case with \"\\conninfo\":\n>\n> postgres=> \\conninfo\n> You are connected to database \"postgres\" as user \"jim\" via socket in\n> \"/tmp\" at port \"5432\".\n>\n> Perhaps excluding the column from the result set or returning NULL in\n> the affected columns would be less confusing?\n>\n> There are also some indentation issues in your patch:\n>\n> /home/jim/Downloads/v7-0001-psql-meta-command-conninfo-plus.patch:142:\n> indent with spaces.\n> PGresult *res;\n> /home/jim/Downloads/v7-0001-psql-meta-command-conninfo-plus.patch:143:\n> indent with spaces.\n> PQExpBufferData buf;\n> /home/jim/Downloads/v7-0001-psql-meta-command-conninfo-plus.patch:144:\n> indent with spaces.\n> printQueryOpt myopt = pset.popt;\n> /home/jim/Downloads/v7-0001-psql-meta-command-conninfo-plus.patch:146:\n> indent with spaces.\n> initPQExpBuffer(&buf);\n> /home/jim/Downloads/v7-0001-psql-meta-command-conninfo-plus.patch:148:\n> indent with spaces.\n> printfPQExpBuffer(&buf,\n> warning: squelched 34 whitespace errors\n> warning: 39 lines add whitespace errors.\n>\n> Looking forward to see the documentation and tests!\n\n--//--\n\nHi Jim,\nThank you for your support on this patch!\nAs I believe in its usability, I have been dedicating efforts to make it really interesting.\nI hadn't thought about the permissioning issue for \"unix_socket_directories\". I appreciate that.\nI thought about solving this situation using the same approach as \\conninfo. I added the validation if (is_unixsock_path(host) && !(hostaddr && *hostaddr)) in the SQL part along with an \"append\". In case of a negative result, another \"append\" adds NULL.\nRegarding the whitespace issue, before generating v8 patch file, I used pgindent to adjust each modified file. I believe it should be ok now. If you could verify, I'd be grateful.\nBelow are the tests after adjusting for the permissioning issues:\n\n[postgres@localhost bin]$ ./psql\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | Authenticated User | System User | Current User | Session User | Session PID | Server Version | Server Address | Server Port | Client Address | Client Port | Socket Directory | Host\n----------+--------------------+-------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+------------------+------\n postgres | postgres | | postgres | postgres | 31479 | 17devel | | 5432 | | | /tmp |\n(1 row)\n\npostgres=# CREATE USER maiquel;\nCREATE ROLE\npostgres=# \\q\n[postgres@localhost bin]$ ./psql -U maiquel -d postgres\npsql (17devel)\nType \"help\" for help.\n\npostgres=> \\conninfo\nYou are connected to database \"postgres\" as user \"maiquel\" via socket in \"/tmp\" at port \"5432\".\npostgres=> \\conninfo+\n Current Connection Information\n Database | Authenticated User | System User | Current User | Session User | Session PID | Server Version | Server Address | Server Port | Client Address | Client Port | Socket Directory | Host\n----------+--------------------+-------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+------------------+------\n postgres | maiquel | | maiquel | maiquel | 31482 | 17devel | | 5432 | | | /tmp |\n(1 row)\n\npostgres=> \\q\n[postgres@localhost bin]$ ./psql -h localhost -U maiquel -d postgres\npsql (17devel)\nType \"help\" for help.\n\npostgres=> \\conninfo\nYou are connected to database \"postgres\" as user \"maiquel\" on host \"localhost\" (address \"::1\") at port \"5432\".\npostgres=> \\conninfo+\n Current Connection Information\n Database | Authenticated User | System User | Current User | Session User | Session PID | Server Version | Server Address | Server Port | Client Address | Client Port | Socket Directory | Host\n----------+--------------------+-------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+------------------+-----------\n postgres | maiquel | | maiquel | maiquel | 31485 | 17devel | ::1 | 5432 | ::1 | 47482 | | localhost\n(1 row)\n\npostgres=> \\q\n[postgres@localhost bin]$ ./psql -h localhost\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"localhost\" (address \"::1\") at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | Authenticated User | System User | Current User | Session User | Session PID | Server Version | Server Address | Server Port | Client Address | Client Port | Socket Directory | Host\n----------+--------------------+-------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+------------------+-----------\n postgres | postgres | | postgres | postgres | 31488 | 17devel | ::1 | 5432 | ::1 | 47484 | | localhost\n(1 row)\n\nRegards,\nMaiquel.",
"msg_date": "Thu, 8 Feb 2024 15:50:20 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "\nOn 08.02.24 16:50, Maiquel Grassi wrote:\n> Hi Jim,\n> Thank you for your support on this patch!\n> As I believe in its usability, I have been dedicating efforts to make\n> it really interesting.\n> I hadn't thought about the permissioning issue for\n> \"unix_socket_directories\". I appreciate that.\n> I thought about solving this situation using the same approach as\n> \\conninfo. I added the validation if (is_unixsock_path(host) &&\n> !(hostaddr && *hostaddr)) in the SQL part along with an \"append\". In\n> case of a negative result, another \"append\" adds NULL.\n> Regarding the whitespace issue, before generating v8 patch file, I\n> used pgindent to adjust each modified file. I believe it should be ok\n> now. If you could verify, I'd be grateful.\n> Below are the tests after adjusting for the permissioning issues:\n>\n> [postgres@localhost bin]$ ./psql\n> psql (17devel)\n> Type \"help\" for help.\n>\n> postgres=# \\conninfo\n> You are connected to database \"postgres\" as user \"postgres\" via socket\n> in \"/tmp\" at port \"5432\".\n> postgres=# \\conninfo+\n> \n> Current Connection Information\n> Database | Authenticated User | System User | Current User | Session\n> User | Session PID | Server Version | Server Address | Server Port |\n> Client Address | Client Port | Socket Directory | Host\n> ----------+--------------------+-------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+------------------+------\n> postgres | postgres | | postgres | postgres\n> | 31479 | 17devel | | 5432 | \n> | | /tmp |\n> (1 row)\n>\n> postgres=# CREATE USER maiquel;\n> CREATE ROLE\n> postgres=# \\q\n> [postgres@localhost bin]$ ./psql -U maiquel -d postgres\n> psql (17devel)\n> Type \"help\" for help.\n>\n> postgres=> \\conninfo\n> You are connected to database \"postgres\" as user \"maiquel\" via socket\n> in \"/tmp\" at port \"5432\".\n> postgres=> \\conninfo+\n> \n> Current Connection Information\n> Database | Authenticated User | System User | Current User | Session\n> User | Session PID | Server Version | Server Address | Server Port |\n> Client Address | Client Port | Socket Directory | Host\n> ----------+--------------------+-------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+------------------+------\n> postgres | maiquel | | maiquel | maiquel\n> | 31482 | 17devel | | 5432 | \n> | | /tmp |\n> (1 row)\n>\n> postgres=> \\q\n> [postgres@localhost bin]$ ./psql -h localhost -U maiquel -d postgres\n> psql (17devel)\n> Type \"help\" for help.\n>\n> postgres=> \\conninfo\n> You are connected to database \"postgres\" as user \"maiquel\" on host\n> \"localhost\" (address \"::1\") at port \"5432\".\n> postgres=> \\conninfo+\n> \n> Current Connection Information\n> Database | Authenticated User | System User | Current User | Session\n> User | Session PID | Server Version | Server Address | Server Port |\n> Client Address | Client Port | Socket Directory | Host\n> ----------+--------------------+-------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+------------------+-----------\n> postgres | maiquel | | maiquel | maiquel\n> | 31485 | 17devel | ::1 | 5432 |\n> ::1 | 47482 | | localhost\n> (1 row)\n>\n> postgres=> \\q\n> [postgres@localhost bin]$ ./psql -h localhost\n> psql (17devel)\n> Type \"help\" for help.\n>\n> postgres=# \\conninfo\n> You are connected to database \"postgres\" as user \"postgres\" on host\n> \"localhost\" (address \"::1\") at port \"5432\".\n> postgres=# \\conninfo+\n> \n> Current Connection Information\n> Database | Authenticated User | System User | Current User | Session\n> User | Session PID | Server Version | Server Address | Server Port |\n> Client Address | Client Port | Socket Directory | Host\n> ----------+--------------------+-------------+--------------+--------------+-------------+----------------+----------------+-------------+----------------+-------------+------------------+-----------\n> postgres | postgres | | postgres | postgres\n> | 31488 | 17devel | ::1 | 5432 |\n> ::1 | 47484 | | localhost\n> (1 row)\n>\n> Regards,\n> Maiquel.\n\nv8 no longer throws a permission denied error for non-superusers - it is\nIMHO much nicer this way.\n\n$ /usr/local/postgres-dev/bin/psql postgres -p 5432 -h 127.0.0.1 -U jim\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\x\nExpanded display is on.\npostgres=# \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]------+----------\nDatabase | postgres\nAuthenticated User | jim\nSystem User |\nCurrent User | jim\nSession User | jim\nSession PID | 1321493\nServer Version | 17devel\nServer Address | 127.0.0.1\nServer Port | 5432\nClient Address | 127.0.0.1\nClient Port | 49366\nSocket Directory |\nHost | 127.0.0.1\n\npostgres=# SET ROLE foo;\nSET\npostgres=> \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]------+----------\nDatabase | postgres\nAuthenticated User | jim\nSystem User |\nCurrent User | foo\nSession User | jim\nSession PID | 1321493\nServer Version | 17devel\nServer Address | 127.0.0.1\nServer Port | 5432\nClient Address | 127.0.0.1\nClient Port | 49366\nSocket Directory |\nHost | 127.0.0.1\n\n\nThe patch now applies cleanly.\n\nOne thing I just noticed. The psql autocomplete feature does not suggest\nthe new + option of \\conninfo. For instance, when typing \"\\connin[TAB]\"\nit automatically autocompletes to \"\\conninfo \". I guess it should also\nbe included in this patch.\n\nI can do a more thorough review of the code when you add the\ndocumentation and tests to the patch.\n\nThanks!\n\n-- \nJim\n\n\n\n",
"msg_date": "Thu, 8 Feb 2024 20:37:38 +0100",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "On 2024-02-08 20:37 +0100, Jim Jones wrote:\n> One thing I just noticed. The psql autocomplete feature does not suggest\n> the new + option of \\conninfo. For instance, when typing \"\\connin[TAB]\"\n> it automatically autocompletes to \"\\conninfo \". I guess it should also\n> be included in this patch.\n\nModifiers such as + or S in \\dS are not covered by autocompletion.\nsrc/bin/psql/tab-complete.c only specifies backslash commands in their\nbasic form (without modifiers).\n\n(\\dS<TAB> actually autocompletes to \\ds to my surprise)\n\n> I can do a more thorough review of the code when you add the\n> documentation and tests to the patch.\n\nI noticed that the pattern parameter in listConnectionInformation is\nunused. exec_command_conninfo scans the pattern but \\conninfo should\nnot accept any argument. So the pattern can be removed entirely.\n\n-- \nErik\n\n\n",
"msg_date": "Thu, 8 Feb 2024 21:37:54 +0100",
"msg_from": "Erik Wienhold <ewie@ewie.name>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "> v8 no longer throws a permission denied error for non-superusers - it is\n> IMHO much nicer this way.\n>\n> $ /usr/local/postgres-dev/bin/psql postgres -p 5432 -h 127.0.0.1 -U jim\n> psql (17devel)\n> Type \"help\" for help.\n>\n> postgres=# \\x\n> Expanded display is on.\n> postgres=# \\conninfo+\n> Current Connection Information\n> -[ RECORD 1 ]------+----------\n> Database | postgres\n> Authenticated User | jim\n> System User |\n> Current User | jim\n> Session User | jim\n> Session PID | 1321493\n> Server Version | 17devel\n> Server Address | 127.0.0.1\n> Server Port | 5432\n> Client Address | 127.0.0.1\n> Client Port | 49366\n> Socket Directory |\n> Host | 127.0.0.1\n>\n> postgres=# SET ROLE foo;\n> SET\n> postgres=> \\conninfo+\n> Current Connection Information\n> -[ RECORD 1 ]------+----------\n> Database | postgres\n> Authenticated User | jim\n> System User |\n> Current User | foo\n> Session User | jim\n> Session PID | 1321493\n> Server Version | 17devel\n> Server Address | 127.0.0.1\n> Server Port | 5432\n> Client Address | 127.0.0.1\n> Client Port | 49366\n> Socket Directory |\n> Host | 127.0.0.1\n>\n> The patch now applies cleanly.\n>\n> One thing I just noticed. The psql autocomplete feature does not suggest\n> the new + option of \\conninfo. For instance, when typing \"\\connin[TAB]\"\n> it automatically autocompletes to \"\\conninfo \". I guess it should also\n> be included in this patch.\n>\n> I can do a more thorough review of the code when you add the\n> documentation and tests to the patch.\n>\n> Thanks!\n\n--//--\n\nHi Jim,\n\n\nIt's not a psql standard to use tab-complete for commands ending with +.\nYou can verify this in the /* psql's backslash commands. */ section of\nthe file \"/src/bin/psql/tab-complete.c\".\n\nhttps://github.com/postgres/postgres/blob/fdfb92c0307c95eba10854196628d88e6708901e/src/bin/psql/tab-complete.c\n\nIn v9, I started the documentation work and am open to suggestions.\n\n\n> \"I can do a more thorough review of the code when you add the\n\n> documentation and tests to the patch.\"\n\nSoon I'll be developing the tests. And that will be welcome.\n\nThanks a lot!\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Thu, 8 Feb 2024 20:47:44 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": ">On 2024-02-08 20:37 +0100, Jim Jones wrote:\n>> One thing I just noticed. The psql autocomplete feature does not suggest\n>> the new + option of \\conninfo. For instance, when typing \"\\connin[TAB]\"\n>> it automatically autocompletes to \"\\conninfo \". I guess it should also\n>> be included in this patch.\n>\n>Modifiers such as + or S in \\dS are not covered by autocompletion.\n>src/bin/psql/tab-complete.c only specifies backslash commands in their\n>basic form (without modifiers).\n>\n>(\\dS<TAB> actually autocompletes to \\ds to my surprise)\n>\n>> I can do a more thorough review of the code when you add the\n>> documentation and tests to the patch.\n>\n>I noticed that the pattern parameter in listConnectionInformation is\n>unused. exec_command_conninfo scans the pattern but \\conninfo should\n>not accept any argument. So the pattern can be removed entirely.\n\n--//--\n\nHi Erik,\n\n\nExactly, in \"\\conninfo+\" the \"pattern\" argument was not introduced and\ntherefore \"listConnectionInformation()\" can be declared (signed) without\nany arguments. In the future, if necessary, and if there is a need to add\nany \"pattern\", then that can be done. However, that's not the current\nscenario. I removed everything related to the \"pattern\" from the patch.\n\nRegarding \"(\\dS<TAB> actually autocompletes to \\ds to my surprise)\",\nI was also surprised. I haven't studied the code yet to understand why\nthis happens. It seems curious to me. I'll try to understand this\nimplementation better.\n\nI'm continuing the development of \"\\conninfo+\" and now moving on to tests.\n\nTks a lot!\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Thu, 8 Feb 2024 22:28:29 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi Erik\n\nOn 08.02.24 21:37, Erik Wienhold wrote:\n> Modifiers such as + or S in \\dS are not covered by autocompletion.\n> src/bin/psql/tab-complete.c only specifies backslash commands in their\n> basic form (without modifiers).\n>\n> (\\dS<TAB> actually autocompletes to \\ds to my surprise)\n>\nAha... I never noticed it. Well, with most commands having 1 - 3\ncharacters it is not a surprised I never used it :)\nThat \"\\dS<TAB>\" autocompletes to \"\\ds \" surprises me even more.\nThanks for pointing out!\n\n-- \nJim\n\n\n\n",
"msg_date": "Fri, 9 Feb 2024 00:34:54 +0100",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "On 08.02.24 21:37, Erik Wienhold wrote:\r\n>> Modifiers such as + or S in \\dS are not covered by autocompletion.\r\n>> src/bin/psql/tab-complete.c only specifies backslash commands in their\r\n>> basic form (without modifiers).\r\n>>\r\n>> (\\dS<TAB> actually autocompletes to \\ds to my surprise)\r\n>>\r\n>Aha... I never noticed it. Well, with most commands having 1 - 3\r\n>characters it is not a surprised I never used it :)\r\n>That \"\\dS<TAB>\" autocompletes to \"\\ds \" surprises me even more.\r\n>Thanks for pointing out!\r\n\r\n--//--\r\n\r\nGood evening, dear all!\r\n\r\n\r\nHere is the mechanism that implements this:\r\n\r\nhttps://github.com/postgres/postgres/blob/b619852086ed2b5df76631f5678f60d3bebd3745/src/bin/psql/tab-complete.h\r\n\r\n.\r\n.\r\n.\r\n1673 /* Match the last N words before point, case-sensitively. */\r\n\r\n1674 #define TailMatchesCS(...) \\\r\n1675 TailMatchesImpl(true, previous_words_count, previous_words, \\\r\n\r\n1676 VA_ARGS_NARGS(__VA_ARGS__), __VA_ARGS__)\r\n.\r\n.\r\n.\r\n4824 else if (TailMatchesCS(\"\\\\ds*\"))\r\n4825 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_sequences);\r\n.\r\n.\r\n.\r\n\r\nThere is a rather large list of meta-commands that are handled by TailMatchesCS(...).\r\n\r\nFor example:\r\n\\ENCODING<TAB> autocompletes to \\encoding\r\n\\eNcOdInG<TAB> autocompletes to \\encoding\r\n\\dU<TAB> or \\DU<TAB> autocompletes to \\du\r\n\r\nIncluding the command under discussion:\r\n\\CONNINFO<TAB> autocompletes to \\conninfo\r\n\r\nFor the meta-commands[+], there is no autocomplete.\r\n\r\nRegards,\r\nMaiquel Grassi.\r\n\n\n\n\n\n\n\n\n\nOn 08.02.24 21:37, Erik Wienhold wrote:\r\n>> Modifiers such as + or S in \\dS are not covered by autocompletion.\r\n>> src/bin/psql/tab-complete.c only specifies backslash commands in their\r\n>> basic form (without modifiers).\r\n>>\r\n>> (\\dS<TAB> actually autocompletes to \\ds to my surprise)\r\n>>\r\n>Aha... I never noticed it. Well, with most commands having 1 - 3\r\n>characters it is not a surprised I never used it :)\r\n>That \"\\dS<TAB>\" autocompletes to \"\\ds \" surprises me even more.\r\n>Thanks for pointing out!\n\r\n--//--\n\r\nGood evening, dear all!\n\n\nHere is the mechanism that implements this:\nhttps://github.com/postgres/postgres/blob/b619852086ed2b5df76631f5678f60d3bebd3745/src/bin/psql/tab-complete.h\n.\r\n.\r\n.\r\n1673 /* Match the last N words before point, case-sensitively. */\n1674 #define TailMatchesCS(...) \\\n1675 TailMatchesImpl(true, previous_words_count, previous_words, \\\n\n1676 VA_ARGS_NARGS(__VA_ARGS__), __VA_ARGS__)\r\n.\r\n.\r\n.\r\n4824 else if (TailMatchesCS(\"\\\\ds*\"))\r\n4825 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_sequences);\r\n.\r\n.\r\n.\n\r\nThere is a rather large list of meta-commands that are handled by TailMatchesCS(...).\n\r\nFor example:\r\n\\ENCODING<TAB> autocompletes to \\encoding\r\n\\eNcOdInG<TAB> autocompletes to \\encoding\r\n\\dU<TAB> or \\DU<TAB> autocompletes to \\du\n\r\nIncluding the command under discussion:\r\n\\CONNINFO<TAB> autocompletes to \\conninfo\n\r\nFor the meta-commands[+], there is no autocomplete.\n\r\nRegards,\r\nMaiquel Grassi.",
"msg_date": "Fri, 9 Feb 2024 02:00:11 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Sorry if this has been brought up, but I noticed that some of the\ninformation is listed below the result set:\n\n\tpostgres=# \\conninfo+\n\tCurrent Connection Information\n\t-[ RECORD 1 ]------+---------\n\tDatabase | postgres\n\tAuthenticated User | nathan\n\tSystem User | \n\tCurrent User | nathan\n\tSession User | nathan\n\tSession PID | 659410\n\tServer Version | 17devel\n\tServer Address | ::1\n\tServer Port | 5432\n\tClient Address | ::1\n\tClient Port | 59886\n\tSocket Directory | \n\tHost | ::1\n\n\tSSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)\n\nShouldn't we move this information into the result set? Separately, does\nthe server version really belong here? I'm not sure I would consider that\nto be connection information.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Thu, 8 Feb 2024 20:41:55 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi Nathan\n\nOn 09.02.24 03:41, Nathan Bossart wrote:\n\n> Separately, does\n> the server version really belong here? I'm not sure I would consider that\n> to be connection information.\n>\nI tend to agree with you. The info there wouldn't hurt, but perhaps the\nclient version would be a better fit.\n\n-- \nJim\n\n\n\n",
"msg_date": "Fri, 9 Feb 2024 08:24:41 +0100",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi, Maiquel!\n\nThe patch v10 build ends with a warning:\n$ make -j --silent\ndescribe.c:911:1: warning: no previous prototype for ‘listConnectionInformation’ [-Wmissing-prototypes]\n 911 | listConnectionInformation()\n | ^~~~~~~~~~~~~~~~~~~~~~~~~\n\nAbout terms.\n\npostgres@postgres(17.0)=# \\x \\conninfo+\nExpanded display is on.\nCurrent Connection Information\n-[ RECORD 1 ]------+---------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User |\nCurrent User | postgres\nSession User | postgres\n*Session PID | 951112 *Server Version | 17devel\nServer Address |\nServer Port | 5401\nClient Address |\nClient Port |\nSocket Directory | /tmp\nHost |\n\nIt looks like \"Session PID\" is a new term for the server process identifier.\nHow about changing the name to \"Backend PID\" (from pg_backend_pid) or even PID (from pg_stat_activity)?\n\nOn 08.02.2024 17:58, Maiquel Grassi wrote:\n> > 1. > + if (db == NULL) > + printf(_(\"You are currently not connected to \n> a database.\\n\")); > > This check is performed for \\conninfo, but not \n> for \\conninfo+.\n> 1. The connection check for the case of \\conninfo+ is handled by \n> \"describe.c\" itself since it deals with queries. I might be mistaken, \n> but I believe that by using \"printQuery()\" via \"describe.c\", this is \n> already ensured, and there is no need to evaluate the connection status.\n\nI found that \\conninfo and \\conninfo+ act differently when the connection is broken.\nI used pg_terminate_backend function from another session to terminate an open psql session.\nAfter that, \\conninfo does not see the connection break (surprisingly!), and \\conninfo+ returns an error:\n\npostgres@postgres(17.0)=# \\conninfo+\nFATAL: terminating connection due to administrator command\nserver closed the connection unexpectedly\n\tThis probably means the server terminated abnormally\n\tbefore or while processing the request.\nThe connection to the server was lost. Attempting reset: Succeeded.\n\npostgres@postgres(17.0)=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5401\".\n\nAnother surprise is that this check:if (db == NULL) did not work in both cases.\n\n-- \nPavel Luzanov\nPostgres Professional:https://postgrespro.com\n\n\n\n\n\n\nHi, Maiquel!\n\nThe patch v10 build ends with a warning:\n$ make -j --silent\ndescribe.c:911:1: warning: no previous prototype for ‘listConnectionInformation’ [-Wmissing-prototypes]\n 911 | listConnectionInformation()\n | ^~~~~~~~~~~~~~~~~~~~~~~~~\n\nAbout terms.\n\npostgres@postgres(17.0)=# \\x \\conninfo+\nExpanded display is on.\nCurrent Connection Information\n-[ RECORD 1 ]------+---------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User | \nCurrent User | postgres\nSession User | postgres\nSession PID | 951112\nServer Version | 17devel\nServer Address | \nServer Port | 5401\nClient Address | \nClient Port | \nSocket Directory | /tmp\nHost | \n\nIt looks like \"Session PID\" is a new term for the server process identifier.\nHow about changing the name to \"Backend PID\" (from pg_backend_pid) or even PID (from pg_stat_activity)?\n\n\n On 08.02.2024 17:58, Maiquel Grassi wrote:\n\n> 1.\n> +\t\t\tif (db == NULL)\n> +\t\t\t\tprintf(_(\"You are currently not connected to a database.\\n\"));\n> \n> This check is performed for \\conninfo, but not for \\conninfo+.\n\n\n\n\n1. The connection check for the case of \\conninfo+ is handled by \"describe.c\" itself since it deals with queries. I might be mistaken, but I believe that by using \"printQuery()\" via \"describe.c\", this is already ensured, and there is no need to evaluate the connection status.\n\n\nI found that \\conninfo and \\conninfo+ act differently when the connection is broken.\nI used pg_terminate_backend function from another session to terminate an open psql session.\nAfter that, \\conninfo does not see the connection break (surprisingly!), and \\conninfo+ returns an error:\n\npostgres@postgres(17.0)=# \\conninfo+\nFATAL: terminating connection due to administrator command\nserver closed the connection unexpectedly\n\tThis probably means the server terminated abnormally\n\tbefore or while processing the request.\nThe connection to the server was lost. Attempting reset: Succeeded.\n\npostgres@postgres(17.0)=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5401\".\n\nAnother surprise is that this check: if (db == NULL) did not work in both cases.\n-- \nPavel Luzanov\nPostgres Professional: https://postgrespro.com",
"msg_date": "Fri, 9 Feb 2024 10:58:15 +0300",
"msg_from": "Pavel Luzanov <p.luzanov@postgrespro.ru>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": ">Sorry if this has been brought up, but I noticed that some of the\n\n>information is listed below the result set:\n>\n > postgres=# \\conninfo+\n > Current Connection Information\n > -[ RECORD 1 ]------+---------\n > Database | postgres\n > Authenticated User | nathan\n > System User |\n > Current User | nathan\n > Session User | nathan\n > Session PID | 659410\n > Server Version | 17devel\n > Server Address | ::1\n > Server Port | 5432\n > Client Address | ::1\n > Client Port | 59886\n > Socket Directory |\n > Host | ::1\n\n > SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)\n\n>Shouldn't we move this information into the result set? Separately, does\n>the server version really belong here? I'm not sure I would consider that\n>to be connection information.\n\n--//--\n\n\nHi Nathan,\n\nThe \"Server Version\" information is closely related to the connection. However,\nit does seem to be an element that does not belong to this set. I removed this\ncolumn and left only what is truly connection info.\n\n\nRegarding the functions \"printSSLInfo()\" and \"printGSSInfo()\", I agree that we\nshould include them in the returned dataset (as two additional columns). A good\nargument is that this will make more sense when using \\x (Expanded display).\nHowever, they are declared and defined within the \"command.c\" file. To make\ncalls to \"printSSLInfo()\" and \"printGSSInfo()\" within \"describe.c\", we would need\nto move their declarations to a new header and create a new C file. I believe\nsomething like \"ssl_gss_info.h\" and \"ssl_gss_info.c\". I'm not sure, but at first glance,\nthis is what occurs to me. Do you have any better or more concise suggestions\nfor resolving this?\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Fri, 9 Feb 2024 08:30:54 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi Pavel!\n\n>The patch v10 build ends with a warning:\n>$ make -j --silent\n>describe.c:911:1: warning: no previous prototype for ‘listConnectionInformation’ [-Wmissing-prototypes]\n> 911 | listConnectionInformation()\n | ^~~~~~~~~~~~~~~~~~~~~~~~~\n\n>About terms.\n\nI resolved this in v11. I had forgotten to put\nthe 'void' inside the parentheses (describe.h and describe.c).\n\n\n>postgres@postgres(17.0)=# \\x \\conninfo+\n>Expanded display is on.\n>Current Connection Information\n>-[ RECORD 1 ]------+---------\n>Database | postgres\n>Authenticated User | postgres\n>System User |\n>Current User | postgres\n>Session User | postgres\n>Session PID | 951112\n>Server Version | 17devel\n>Server Address |\n>Server Port | 5401\n>Client Address |\n>Client Port |\n>Socket Directory | /tmp\n>Host |\n\n>It looks like \"Session PID\" is a new term for the server process identifier.\n>How about changing the name to \"Backend PID\" (from pg_backend_pid) or even PID (from pg_stat_activity)?\n\n\nYou're right, it's better to stick with the proper terms already in use\nin PostgreSQL. This ensures that the user doesn't get confused. I've\nchanged it to \"Backend PID\".\n\n\n>On 08.02.2024 17:58, Maiquel Grassi wrote:\n\n> 1.\n> + if (db == NULL)\n> + printf(_(\"You are currently not connected to a database.\\n\"));\n>\n> This check is performed for \\conninfo, but not for \\conninfo+.\n\n1. The connection check for the case of \\conninfo+ is handled by \"describe.c\" itself since it deals with queries. I might be mistaken, but I believe that by using \"printQuery()\" via \"describe.c\", this is already ensured, and there is no need to evaluate the connection status.\n\n>I found that \\conninfo and \\conninfo+ act differently when the connection is broken.\n>I used pg_terminate_backend function from another session to terminate an open psql session.\n>After that, \\conninfo does not see the connection break (surprisingly!), and \\conninfo+ returns an error:\n\n>postgres@postgres(17.0)=# \\conninfo+\n>FATAL: terminating connection due to administrator command\n>server closed the connection unexpectedly\n >This probably means the server terminated abnormally\n >before or while processing the request.\n>The connection to the server was lost. Attempting reset: Succeeded.\n\n\nFor this case, I believe it's already resolved, because if you get a\nreturn indicating that the connection was terminated, and indeed it was,\nthen \"describe.c\" is handling it correctly. At least that's what\nit seems like.\n\n>postgres@postgres(17.0)=# \\conninfo\n>You are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5401\".\n\n\nHere it seems like we have an issue to be studied and subsequently resolved.\n\n>Another surprise is that this check: if (db == NULL) did not work in both cases.\n\nI will investigate further and, if necessary, remove it.\n\nHere's v12, in the next version, I'll try to address the above situation.\n\nThanks a lot!\nMaiquel Grassi.",
"msg_date": "Fri, 9 Feb 2024 09:18:44 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": ">Hi Nathan\n>\n>On 09.02.24 03:41, Nathan Bossart wrote:\n>\n>> Separately, does\n>> the server version really belong here? I'm not sure I would consider that\n>> to be connection information.\n>>\n>I tend to agree with you. The info there wouldn't hurt, but perhaps the\n>client version would be a better fit.\n\n--//--\n\nHi!\n\nI believe that if we include the server version, it would also be\nnecessary to include the version of psql. This would make it\nclearer for the user. I agree that this won't make much difference\nin practice, especially because we're interested in creating a setof\ninformation directly related to the connection. I prefer to keep it\nsuppressed for now. In the future, if necessary, we can add this\ninformation without any problem. In v12, \"Server Version\" is\nalready removed.\n\nTks!\nMaiquel Grassi.\n\n\n\n\n\n\n\n\n>Hi Nathan\n>\n>On 09.02.24 03:41, Nathan Bossart wrote:\n>\n>> Separately, does\n>> the server version really belong here? I'm not sure I would consider that\n>> to be connection information.\n>>\n>I tend to agree with you. The info there wouldn't hurt, but perhaps the\n>client version would be a better fit.\n\n--//--\n\nHi!\n\n\nI believe that if we include the server version, it would also be\nnecessary to include the version of psql. This would make it\nclearer for the user. I agree that this won't make much difference\nin practice, especially because we're interested in creating a setof\ninformation directly related to the connection. I prefer to keep it\nsuppressed for now. In the future, if necessary, we can add this\ninformation without any problem. In v12, \"Server Version\" is\nalready removed.\n\nTks!\nMaiquel Grassi.",
"msg_date": "Fri, 9 Feb 2024 09:38:35 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Hmm, I noticed that this would call printSSLInfo() and printGSSInfo()\nafter listConnectionInformation. It would be much better to show these\nin tabular format as well and remove the calls to printSSL/GSSInfo.\n\nI propose additional columns to the same \\conninfo+ table; when SSL,\nlike this:\n\nDatabase | postgres\n[...]\nHost | 127.0.0.1\nEncryption | SSL\nProtocol | PQsslAttribute(protocol)\nCipher | PQsslAttribute(cipher)\nCompression | PQsslAttribute(compression)\n\nWhen GSS, like this\n\nDatabase | postgres\n[...]\nHost | 127.0.0.1\nEncryption | GSS\n\n(why don't we print anything else in printGSSInfo()? That's weird.)\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": "Fri, 9 Feb 2024 11:19:03 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": ">Hmm, I noticed that this would call printSSLInfo() and printGSSInfo()\n>after listConnectionInformation. It would be much better to show these\n>in tabular format as well and remove the calls to printSSL/GSSInfo.\n>\n>I propose additional columns to the same \\conninfo+ table; when SSL,\n>like this:\n>\n>Database | postgres\n>[...]\n>Host | 127.0.0.1\n>Encryption | SSL\n>Protocol | PQsslAttribute(protocol)\n>Cipher | PQsslAttribute(cipher)\n>Compression | PQsslAttribute(compression)\n>\n>When GSS, like this\n>\n>Database | postgres\n>[...]\n>Host | 127.0.0.1\n>Encryption | GSS\n>\n>(why don't we print anything else in printGSSInfo()? That's weird.)\n\n--//--\n\nHi Álvaro,\n\n\nThank you for the suggestion. I will remove printSSLInfo() and printGSSInfo() and\nincorporate the suggested fields into the tabular result of \"\\conninfo+\".\n\nIf it's necessary to adjust printGSSInfo(), we can work on that as well. At first\nglance, I leave it open for others to analyze and give their opinion.\n\nI'd also like to ask for help with a difficulty. Currently, I'm working on\n\nresolving this situation (highlighted by Pavel Luzanov). How can we\nmake \\conninfo return the same message as \\conninfo+ after closing\nthe current session in another session with pg_terminate_backend(pid)?\n\n[postgres@localhost bin]$ ./psql\n\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | Authenticated User | System User | Current User | Session User | Backend PID | Server Address | Server Port | Client Address | Client Port | Socket Directory | Host\n----------+--------------------+-------------+--------------+--------------+-------------+----------------+-------------+----------------+-------------+------------------+------\n postgres | postgres | | postgres | postgres | 17281 | | 5432 | | | /tmp |\n(1 row)\n\npostgres=# 2024-02-09 09:15:24.152 -03 [17281] FATAL: terminating connection due to administrator command\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5432\".\npostgres=# \\conninfo+\nFATAL: terminating connection due to administrator command\nserver closed the connection unexpectedly\n This probably means the server terminated abnormally\n before or while processing the request.\nThe connection to the server was lost. Attempting reset: Succeeded.\npostgres=#\n\nTks a lot!\nMaiquel Grassi.\n\n\n\n\n\n\n\n\n>Hmm, I noticed that this would call printSSLInfo() and printGSSInfo()\n>after listConnectionInformation. It would be much better to show these\n>in tabular format as well and remove the calls to printSSL/GSSInfo.\n>\n>I propose additional columns to the same \\conninfo+ table; when SSL,\n>like this:\n>\n>Database | postgres\n>[...]\n>Host | 127.0.0.1\n>Encryption | SSL\n>Protocol | PQsslAttribute(protocol)\n>Cipher | PQsslAttribute(cipher)\n>Compression | PQsslAttribute(compression)\n>\n>When GSS, like this\n>\n>Database | postgres\n>[...]\n>Host | 127.0.0.1\n>Encryption | GSS\n>\n>(why don't we print anything else in printGSSInfo()? That's weird.)\n\n--//--\n\nHi Álvaro,\n\n\nThank you for the suggestion. I will remove printSSLInfo() and printGSSInfo() and\nincorporate the suggested fields into the tabular result of \"\\conninfo+\".\n\nIf it's necessary to adjust printGSSInfo(), we can work on that as well. At first\nglance, I leave it open for others to analyze and give their opinion.\n\nI'd also like to ask for help with a difficulty. Currently, I'm working on\nresolving this situation (highlighted by Pavel Luzanov). How can we\nmake \\conninfo return the same message as\n\\conninfo+ after closing\nthe current session in another session with \npg_terminate_backend(pid)?\n\n[postgres@localhost bin]$ ./psql\npsql (17devel)\nType \"help\" for help.\n\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5432\".\npostgres=# \\conninfo+\n Current Connection Information\n Database | Authenticated User | System User | Current User | Session User | Backend PID | Server Address | Server Port | Client Address | Client Port | Socket\n Directory | Host\n----------+--------------------+-------------+--------------+--------------+-------------+----------------+-------------+----------------+-------------+------------------+------\n postgres | postgres | | postgres | postgres | 17281 | | 5432 | | | /tmp\n |\n(1 row)\n\n\npostgres=# 2024-02-09 09:15:24.152 -03 [17281] FATAL: terminating connection due to administrator command\n\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5432\".\npostgres=# \\conninfo+\nFATAL: terminating connection due to administrator command\nserver closed the connection unexpectedly\n This probably means the server terminated abnormally\n before or while processing the request.\nThe connection to the server was lost. Attempting reset: Succeeded.\npostgres=#\n\nTks a lot!\nMaiquel Grassi.",
"msg_date": "Fri, 9 Feb 2024 15:33:23 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": ">Database | postgres\n>[...]\n>Host | 127.0.0.1\n>Encryption | SSL\n>Protocol | PQsslAttribute(protocol)\n>Cipher | PQsslAttribute(cipher)\n>Compression | PQsslAttribute(compression)\n>\n>When GSS, like this\n>\n>Database | postgres\n>[...]\n>Host | 127.0.0.1\n>Encryption | GSS\n\n--//--\n\nHi PgHackers,\n\nColumns were added for SSL and GSS.\n\n\nFor SSL, I conducted some tests as follows. For GSS, I will perform\nthem and intend to provide a sample here in the next interaction.\n\nIf anyone can and wants to test GSSAPI as well, I appreciate it.\n\n[postgres@localhost bin]$ ./psql -h localhost -p 5432 -x\n\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"localhost\" (address \"::1\") at port \"5432\".\npostgres=# \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]------+----------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User |\nCurrent User | postgres\nSession User | postgres\nBackend PID | 15809\nServer Address | ::1\nServer Port | 5432\nClient Address | ::1\nClient Port | 56890\nSocket Directory |\nHost | localhost\n\npostgres=# \\q\n[postgres@localhost bin]$ ./psql -h localhost -p 5433 -x\npsql (17devel, server 15.6)\nSSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, compression: off)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"localhost\" (address \"::1\") at port \"5433\".\nSSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, compression: off)\npostgres=# \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]------+----------------------------\nDatabase | postgres\nAuthenticated User | postgres\nCurrent User | postgres\nSession User | postgres\nBackend PID | 15811\nServer Address | ::1\nServer Port | 5433\nClient Address | ::1\nClient Port | 40622\nSocket Directory |\nHost | localhost\nEncryption | SSL\nProtocol | TLSv1.2\nCipher | ECDHE-RSA-AES256-GCM-SHA384\nCompression | off\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Sat, 10 Feb 2024 17:38:23 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": ">I found that \\conninfo and \\conninfo+ act differently when the connection is broken.\n>I used pg_terminate_backend function from another session to terminate an open psql session.\n>After that, \\conninfo does not see the connection break (surprisingly!), and \\conninfo+ returns an error:\n>\n>postgres@postgres(17.0)=# \\conninfo+\n>FATAL: terminating connection due to administrator command\n>server closed the connection unexpectedly\n> This probably means the server terminated abnormally\n> before or while processing the request.\n>The connection to the server was lost. Attempting reset: Succeeded.\n>\n>postgres@postgres(17.0)=# \\conninfo\n>You are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5401\".\n>\n>Another surprise is that this check: if (db == NULL) did not work in both cases.\n\n--//--\n\nHi Pavel!\n\n(v14)\n\nThe \"if (db == NULL)\" has been removed, as well\nas the message inside it. To always maintain the\nsame error messages, I changed the validation of\n\"\\conninfo\" to match the validation used for \"\\conninfo+\".\nTherefore, now \"\\conninfo\" and \"\\conninfo+\" return\nthe same error when \"pg_terminate_backend()\" terminates\nthis session through another session. The result of\nthe adjustment is as follows:\n\n\nCase 1 (\"\\conninfo+\"):\n\n[postgres@localhost bin]$ ./psql -x\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5432\".\npostgres=# \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]------+---------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User |\nCurrent User | postgres\nSession User | postgres\nBackend PID | 24381\nServer Address |\nServer Port | 5432\nClient Address |\nClient Port |\nSocket Directory | /tmp\nHost |\n\npostgres=# \\conninfo+\nFATAL: terminating connection due to administrator command\nserver closed the connection unexpectedly\n This probably means the server terminated abnormally\n before or while processing the request.\nThe connection to the server was lost. Attempting reset: Succeeded.\n\n\nCase 2 (\"\\conninfo\"):\n\n[postgres@localhost bin]$ ./psql -x\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5432\".\npostgres=# \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]------+---------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User |\nCurrent User | postgres\nSession User | postgres\nBackend PID | 24539\nServer Address |\nServer Port | 5432\nClient Address |\nClient Port |\nSocket Directory | /tmp\nHost |\n\npostgres=# \\conninfo\nFATAL: terminating connection due to administrator command\nserver closed the connection unexpectedly\n This probably means the server terminated abnormally\n before or while processing the request.\n\nThe connection to the server was lost. Attempting reset: Succeeded.\n\nIn both cases, the sessions were terminated by another session.\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Mon, 12 Feb 2024 14:16:00 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi,\n\nOn 12.02.2024 17:16, Maiquel Grassi wrote:\n>\n> The \"if (db == NULL)\" has been removed, as well as the message inside \n> it. To always maintain the same error messages, I changed the \n> validation of \"\\conninfo\" to match the validation used for \n> \"\\conninfo+\". Therefore, now \"\\conninfo\" and \"\\conninfo+\" return the \n> same error when \"pg_terminate_backend()\" terminates this session \n> through another session.\n>\n\nThis make sense to me. Thank you for this work.\n\n-- \nPavel Luzanov\nPostgres Professional:https://postgrespro.com\n\n\n\n\n\n\n Hi,\n\nOn 12.02.2024\n 17:16, Maiquel Grassi wrote:\n\n\n\n\nThe \"if (db == NULL)\" has been removed, as well\nas the message inside it. To always maintain the\nsame error messages, I changed the validation of\n\"\\conninfo\" to match the validation used for \"\\conninfo+\".\nTherefore, now \"\\conninfo\" and \"\\conninfo+\" return\nthe same error when \"pg_terminate_backend()\" terminates\nthis session through another session.\n\n\n This make sense to me. Thank you for this work. \n-- \nPavel Luzanov\nPostgres Professional: https://postgrespro.com",
"msg_date": "Tue, 13 Feb 2024 00:53:50 +0300",
"msg_from": "Pavel Luzanov <p.luzanov@postgrespro.ru>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "\n\nOn 12.02.24 15:16, Maiquel Grassi wrote:\n>\n> (v14)\n>\n>\nv14 applies cleanly and the SSL info is now shown as previously\nsuggested. Here is a more comprehensive test:\n\n$ /usr/local/postgres-dev/bin/psql -x \"\\\n host=server.uni-muenster.de\n hostaddr=172.19.42.1\n user=jim dbname=postgres\n sslrootcert=server-certificates/server.crt\n sslcert=jim-certificates/jim.crt\n sslkey=jim-certificates/jim.key\"\n \npsql (17devel)\nSSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\ncompression: off)\nType \"help\" for help.\n\npostgres=# SET ROLE foo;\nSET\npostgres=> \\conninfo+\nCurrent Connection Information\n-[ RECORD 1\n]------+---------------------------------------------------------------------------------------------------------------------------\nDatabase | postgres\nAuthenticated User | jim\nSystem User | cert:emailAddress=jim@uni-muenster.de,CN=jim,OU=WWU\nIT,O=Universitaet Muenster,L=Muenster,ST=Nordrhein-Westfalen,C=DE\nCurrent User | foo\nSession User | jim\nBackend PID | 278294\nServer Address | 172.19.42.1\nServer Port | 5432\nClient Address | 192.168.178.27\nClient Port | 54948\nSocket Directory |\nHost | server.uni-muenster.de\nEncryption | SSL\nProtocol | TLSv1.3\nCipher | TLS_AES_256_GCM_SHA384\nCompression | off\n\npostgres=> \\conninfo\nYou are connected to database \"postgres\" as user \"jim\" on host\n\"server.uni-muenster.de\" (address \"127.0.0.1\") at port \"5432\".\nSSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\ncompression: off)\n\nA little odd is that \"Server Address\" of \\conninfo+ differs from\n\"address\" of \\conninfo...\n\nI think the documentation could add a little more info than just this:\n\n> When no + is specified, it simply prints a textual description of a\nfew connection options. When + is given, more complete information is\ndisplayed as a table.\n\nPerhaps briefly mentioning the returned columns or simply listing them\nwould be IMHO a nice addition. For some users the semantics of\n\"Authenticated User\", \"System User\", \"Current User\" and \"Session User\"\ncan be a little confusing. And yes, I realize the current documentation\nof \\conninfo is already a little vague :).\n\nThanks for working on this\n\n-- \nJim\n\n\n\n",
"msg_date": "Wed, 14 Feb 2024 12:36:49 +0100",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": ">v14 applies cleanly and the SSL info is now shown as previously\n>suggested. Here is a more comprehensive test:\n>\n>\n>$ /usr/local/postgres-dev/bin/psql -x \"\\\n> host=server.uni-muenster.de\n> hostaddr=172.19.42.1\n> user=jim dbname=postgres\n> sslrootcert=server-certificates/server.crt\n> sslcert=jim-certificates/jim.crt\n> sslkey=jim-certificates/jim.key\"\n>\n>psql (17devel)\n>SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\n>compression: off)\n>Type \"help\" for help.\n>\n>postgres=# SET ROLE foo;\n>SET\n>postgres=> \\conninfo+\n>Current Connection Information\n>-[ RECORD 1\n>]------+---------------------------------------------------------------------------------------------------------------------------\n>Database | postgres\n>Authenticated User | jim\n>System User | cert:emailAddress=jim@uni-muenster.de,CN=jim,OU=WWU\n>IT,O=Universitaet Muenster,L=Muenster,ST=Nordrhein-Westfalen,C=DE\n>Current User | foo\n>Session User | jim\n>Backend PID | 278294\n>Server Address | 172.19.42.1\n>Server Port | 5432\n>Client Address | 192.168.178.27\n>Client Port | 54948\n>Socket Directory |\n>Host | server.uni-muenster.de\n>Encryption | SSL\n>Protocol | TLSv1.3\n>Cipher | TLS_AES_256_GCM_SHA384\n>Compression | off\n>\n>postgres=> \\conninfo\n>You are connected to database \"postgres\" as user \"jim\" on host\n>\"server.uni-muenster.de\" (address \"127.0.0.1\") at port \"5432\".\n>SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\n>compression: off)\n\n>A little odd is that \"Server Address\" of \\conninfo+ differs from\n>\"address\" of \\conninfo...\n\n----//----\n\nHi Jim!\n\n\nTests performed on CentOS Linux 7.\n\n\nI made some further observations and concluded that there will\nbe more cases where the \"address\" from \\conninfo will differ from\nthe \"Server Address\" from \\conninfo+. Below is a more detailed example.\n\nThe input of \"hostaddr\" or \"host\" in the psql call can be any pointing to\n\"loopback local\" and the connection will still be established. For example,\nall of these are accepted:\n\nCase (inet):\npsql -x --host 0\npsql -x --host 0.0.0.0\npsql -x hostaddr=0\npsql -x hostaddr=0.0.0.0\nAll these examples will have \"Server Address\" = 127.0.0.1\n\nCase (inet6):\npsql -x --host ::\npsql -x --host * (this entry is not accepted)\npsql -x --host \\*\n\npsql -x --host \"*\"\npsql -x hostaddr=::\npsql -x hostaddr=*\nAll these examples will have \"Server Address\" = ::1\n\nThus, the inet_server_addr() function will return 127.0.0.1 or ::1 which in some cases will differ from the \"address\" from \\conninfo.\n\n[postgres@localhost bin]$ ./psql -x hostaddr=0\n\nPassword for user postgres:\npsql (17devel)\nSSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, compression: off)\nType \"help\" for help.\n\npostgres=# SET ROLE maiquel;\nSET\npostgres=> \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"0\" (address \"0.0.0.0\") at port \"5432\".\nSSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, compression: off)\npostgres=> \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]------+----------------------------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User | scram-sha-256:postgres\nCurrent User | maiquel\nSession User | postgres\nBackend PID | 15205\nServer Address | 127.0.0.1\nServer Port | 5432\nClient Address | 127.0.0.1\nClient Port | 57598\nSocket Directory |\nHost | 0\nEncryption | SSL\nProtocol | TLSv1.2\nCipher | ECDHE-RSA-AES256-GCM-SHA384\nCompression | off\n\npostgres=> \\q\n[postgres@localhost bin]$ ping 0.0.0.0\nPING 0.0.0.0 (127.0.0.1) 56(84) bytes of data.\n64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.061 ms\n64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.069 ms\n64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.071 ms\n64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.107 ms\n^C\n--- 0.0.0.0 ping statistics ---\n4 packets transmitted, 4 received, 0% packet loss, time 3003ms\nrtt min/avg/max/mdev = 0.061/0.077/0.107/0.017 ms\n\nAs demonstrated above, \"address\" = 0.0.0.0 and \"Server Address\" = 127.0.0.1 are divergent.\n\nIn practice, these IPs are the \"same\", and the ping from the example proves it.\n\n\nHowever, we are concerned here with the psql user, and this may seem confusing to them at\nfirst glance. I would like to propose a change in \"address\" so that it always returns the same as\n\"Server Address\", that is, to use the inet_server_address() function in \"address\".\n\nResult:\n\n[postgres@localhost bin]$ ./psql -x hostaddr=0\n\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"0\" (address \"127.0.0.1\") at port \"5432\".\npostgres=# \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]------+----------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User |\nCurrent User | postgres\nSession User | postgres\nBackend PID | 26859\nServer Address | 127.0.0.1\nServer Port | 5432\nClient Address | 127.0.0.1\nClient Port | 58254\nSocket Directory |\nHost | 0\n\n----//----\n\n>I think the documentation could add a little more info than just this:\n\n>> When no + is specified, it simply prints a textual description of a\n>>few connection options. When + is given, more complete information is\n>>displayed as a table.\n\n>Perhaps briefly mentioning the returned columns or simply listing them\n>would be IMHO a nice addition. For some users the semantics of\n>\"Authenticated User\", \"System User\", \"Current User\" and \"Session User\"\n>can be a little confusing. And yes, I realize the current documentation\n>of \\conninfo is already a little vague :).\n\nYour suggestion was well received, and I'will made the adjustment to make\nthe command description more comprehensive.\n\nHere is version v15 where I sought to correct 'Adress' to make it the same\nas 'Server Address'.\n\nCould you perform the same test and validate?\n\nThank you so much!\nMaiquel Grassi.",
"msg_date": "Thu, 15 Feb 2024 19:47:05 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi!\n\n(v16)\n\nIn this version, I made a small adjustment to the indentation\nof the \\conninfo code and described the columns as returned\nby \\conninfo+ as suggested by Jim Jones.\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Thu, 15 Feb 2024 22:16:33 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "\n\nOn 15.02.24 23:16, Maiquel Grassi wrote:\n>\n> Hi!\n>\n> (v16)\n>\n> In this version, I made a small adjustment to the indentation\n> of the \\conninfo code and described the columns as returned\n> by \\conninfo+ as suggested by Jim Jones.\n>\n>\n\nI've performed the following tests with v16:\n\n1) hostaddr=172.19.42.1\n\n$ /usr/local/postgres-dev/bin/psql -x \"\\\n host=server.uni-muenster.de\n hostaddr=172.19.42.1\n user=jim dbname=postgres\n sslrootcert=server-certificates/server.crt\n sslcert=jim-certificates/jim.crt\n sslkey=jim-certificates/jim.key\" -c \"\\conninfo+\" -c \"\\conninfo\"\n\nCurrent Connection Information\n-[ RECORD 1\n]------+---------------------------------------------------------------------------------------------------------------------------\nDatabase | postgres\nAuthenticated User | jim\nSystem User |\ncert:emailAddress=wwwadmin@uni-muenster.de,CN=jim,OU=WWU\nIT,O=Universitaet Muenster,L=Muenster,ST=Nordrhein-Westfalen,C=DE\nCurrent User | jim\nSession User | jim\nBackend PID | 386839\nServer Address | 172.19.42.1\nServer Port | 5432\nClient Address | 192.168.178.27\nClient Port | 35602\nSocket Directory |\nHost | server.uni-muenster.de\nEncryption | SSL\nProtocol | TLSv1.3\nCipher | TLS_AES_256_GCM_SHA384\nCompression | off\n\nYou are connected to database \"postgres\" as user \"jim\" on host\n\"server.uni-muenster.de\" (address \"172.19.42.1\") at port \"5432\".\nSSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\ncompression: off)\n\n\nThe same with non-superusers\n\n$ /usr/local/postgres-dev/bin/psql -x \"\\\n host=server.uni-muenster.de\n hostaddr=172.19.42.1\n user=jim dbname=postgres\n sslrootcert=server-certificates/server.crt\n sslcert=jim-certificates/jim.crt\n sslkey=jim-certificates/jim.key\" -c \"SET ROLE foo\" -c \"\\conninfo+\"\n-c \"\\conninfo\"\nSET\nCurrent Connection Information\n-[ RECORD 1\n]------+---------------------------------------------------------------------------------------------------------------------------\nDatabase | postgres\nAuthenticated User | jim\nSystem User |\ncert:emailAddress=wwwadmin@uni-muenster.de,CN=jim,OU=WWU\nIT,O=Universitaet Muenster,L=Muenster,ST=Nordrhein-Westfalen,C=DE\nCurrent User | foo\nSession User | jim\nBackend PID | 547733\nServer Address | 172.19.42.1\nServer Port | 5432\nClient Address | 192.168.178.27\nClient Port | 58508\nSocket Directory |\nHost | server.uni-muenster.de\nEncryption | SSL\nProtocol | TLSv1.3\nCipher | TLS_AES_256_GCM_SHA384\nCompression | off\n\nYou are connected to database \"postgres\" as user \"jim\" on host\n\"server.uni-muenster.de\" (address \"172.19.42.1\") at port \"5432\".\nSSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\ncompression: off)\n\n\n2) -h 192.168.178.27\n\n$ /usr/local/postgres-dev/bin/psql -x -U postgres -h 192.168.178.27 -c\n\"\\conninfo+\" -c \"\\conninfo\"\nCurrent Connection Information\n-[ RECORD 1 ]------+-----------------------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User |\nCurrent User | postgres\nSession User | postgres\nBackend PID | 399670\nServer Address | 192.168.178.27\nServer Port | 5432\nClient Address | 192.168.178.27\nClient Port | 44174\nSocket Directory |\nHost | 192.168.178.27\nEncryption | SSL\nProtocol | TLSv1.3\nCipher | TLS_AES_256_GCM_SHA384\nCompression | off\n\nYou are connected to database \"postgres\" as user \"postgres\" on host\n\"192.168.178.27\" at port \"5432\".\nSSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\ncompression: off)\n\n\n3) via socket\n\n$ /usr/local/postgres-dev/bin/psql -x -U postgres -c \"\\conninfo+\" -c\n\"\\conninfo\"\nCurrent Connection Information\n-[ RECORD 1 ]------+---------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User |\nCurrent User | postgres\nSession User | postgres\nBackend PID | 394273\nServer Address |\nServer Port | 5432\nClient Address |\nClient Port |\nSocket Directory | /tmp\nHost |\n\nYou are connected to database \"postgres\" as user \"postgres\" via socket\nin \"/tmp\" at port \"5432\".\n\n4) -h 127.0.0.1\n\n$ /usr/local/postgres-dev/bin/psql -x -U postgres -h 127.0.0.1 -c\n\"\\conninfo+\" -c \"\\conninfo\"\nCurrent Connection Information\n-[ RECORD 1 ]------+-----------------------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User |\nCurrent User | postgres\nSession User | postgres\nBackend PID | 396070\nServer Address | 127.0.0.1\nServer Port | 5432\nClient Address | 127.0.0.1\nClient Port | 52528\nSocket Directory |\nHost | 127.0.0.1\nEncryption | SSL\nProtocol | TLSv1.3\nCipher | TLS_AES_256_GCM_SHA384\nCompression | off\n\nYou are connected to database \"postgres\" as user \"postgres\" on host\n\"127.0.0.1\" at port \"5432\".\nSSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\ncompression: off)\n\n\n5) -h localhost\n\n$ /usr/local/postgres-dev/bin/psql -x -U postgres -h localhost -c\n\"\\conninfo+\" -c \"\\conninfo\"\nCurrent Connection Information\n-[ RECORD 1 ]------+-----------------------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User |\nCurrent User | postgres\nSession User | postgres\nBackend PID | 397056\nServer Address | 127.0.0.1\nServer Port | 5432\nClient Address | 127.0.0.1\nClient Port | 53578\nSocket Directory |\nHost | localhost\nEncryption | SSL\nProtocol | TLSv1.3\nCipher | TLS_AES_256_GCM_SHA384\nCompression | off\n\nYou are connected to database \"postgres\" as user \"postgres\" on host\n\"localhost\" (address \"127.0.0.1\") at port \"5432\".\nSSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\ncompression: off)\n\n6) -h 0\n\n$ /usr/local/postgres-dev/bin/psql -x -U postgres -h 0 -c \"\\conninfo+\"\n-c \"\\conninfo\"\nCurrent Connection Information\n-[ RECORD 1 ]------+-----------------------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User |\nCurrent User | postgres\nSession User | postgres\nBackend PID | 406342\nServer Address | 127.0.0.1\nServer Port | 5432\nClient Address | 127.0.0.1\nClient Port | 38674\nSocket Directory |\nHost | 0\nEncryption | SSL\nProtocol | TLSv1.3\nCipher | TLS_AES_256_GCM_SHA384\nCompression | off\n\nYou are connected to database \"postgres\" as user \"postgres\" on host \"0\"\n(address \"127.0.0.1\") at port \"5432\".\nSSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\ncompression: off)\n\n7) -h 0.0.0.0 - As you mentioned, this is one of the cases where host\nand \"server address\" differ.\n I am not sure if it is an issue. Perhaps the other reviewers might\nhave an opinion on it\n\n$ /usr/local/postgres-dev/bin/psql -x -U postgres -h 0.0.0.0 -c\n\"\\conninfo+\" -c \"\\conninfo\"\nCurrent Connection Information\n-[ RECORD 1 ]------+-----------------------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User |\nCurrent User | postgres\nSession User | postgres\nBackend PID | 404395\nServer Address | 127.0.0.1\nServer Port | 5432\nClient Address | 127.0.0.1\nClient Port | 54806\nSocket Directory |\nHost | 0.0.0.0\nEncryption | SSL\nProtocol | TLSv1.3\nCipher | TLS_AES_256_GCM_SHA384\nCompression | off\n\nYou are connected to database \"postgres\" as user \"postgres\" on host\n\"0.0.0.0\" at port \"5432\".\nSSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\ncompression: off)\n\n\n> I would like to propose a change in \"address\" so that it always\nreturns the same as\n> \"Server Address\", that is, to use the inet_server_address() function\nin \"address\".\n\nI'm not sure of the impact of this change in the existing \\conninfo - at\nleast the cfbot and \"make -j check-world\" didn't complain.\nI'll take a closer look at it as soon we have test cases.\n\nDocs:\n\n+ <term><literal>\\conninfo[+]</literal></term>\n <listitem>\n <para>\n Outputs information about the current database connection.\n+ When no <literal>+</literal> is specified, it simply prints\n+ a textual description of a few connection options.\n+ When <literal>+</literal> is given, more complete information\n+ is displayed as a table.\n+ </para>\n\n\nTo keep it consistent with the other options, we might wanna use \"+ is\nappended\" instead of \"+ is specified\" or \"+ is given\"\n\n\n+ When <literal>+</literal> is given, more complete information\n+ is displayed as a table.\n+ </para>\n+\n+ <para>\n+ \"Database\", \"Authenticated User\", \"System User\" (only for\nPostgreSQL 16 or higher),\n+ \"Current User\", \"Session User\", \"Backend PID\", \"Server\nAddress\", \"Server Port\",\n+ \"Client Address\", \"Client Port\", \"Socket Directory\", and \"Host\"\ncolumns are listed\n+ by default when <literal>\\conninfo+</literal> is invoked. The\ncolumns \"Encryption\",\n+ \"Protocol\", \"Cipher\", and \"Compression\" are added to this\noutput when TLS (SSL)\n+ authentication is used. The same applies to GSS authentication\nis used, where the\n+ \"GSSAPI\" column is also added to the\n<literal>\\conninfo+</literal> output.\n\n\nI think that a list with a brief description of all columns would be\nmore interesting in this case (it is just a suggestion based on personal\ntaste, so feel to ignore it)\n\nI had something along these lines in mind:\n\nOutputs a string containing information about the current database\nconnection.\nWhen + is appended, it outputs a table containing the following columns:\n\n* Database: lorem ipsum\n* Authenticated User:lorem ipsum\n* System User: lorem ipsum\n* Current User: lorem ipsum\n* Session User: lorem ipsum\n* Backend PID: lorem ipsum\n* Server Address: lorem ipsum\n* Server Port: lorem ipsum\n* Client Address:lorem ipsum\n* Client Port: lorem ipsum\n* Socket Directory: lorem ipsum\n* Host: lorem ipsum\n\nTLS (SSL) authentication\n\nThese columns are added to the table TLS (SSL) authentication is used\n\n* Encryption:lorem ipsum\n* Cipher:lorem ipsum\n* Protocol:lorem ipsum\n\nGSS authentication ...\n...\n\n\nThanks\n\n\n-- \nJim\n\n\n\n",
"msg_date": "Fri, 16 Feb 2024 12:18:45 +0100",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Thanks for your work on this. I haven't been keeping up with the\ndiscussion, but I took a quick look at the latest patch.\n\n+ <para>\n+ \"Database\", \"Authenticated User\", \"System User\" (only for PostgreSQL 16 or higher),\n+ \"Current User\", \"Session User\", \"Backend PID\", \"Server Address\", \"Server Port\",\n+ \"Client Address\", \"Client Port\", \"Socket Directory\", and \"Host\" columns are listed\n+ by default when <literal>\\conninfo+</literal> is invoked. The columns \"Encryption\",\n+ \"Protocol\", \"Cipher\", and \"Compression\" are added to this output when TLS (SSL)\n+ authentication is used. The same applies to GSS authentication is used, where the\n+ \"GSSAPI\" column is also added to the <literal>\\conninfo+</literal> output.\n </para>\n\nI might be alone on this, but I think this command should output the same\ncolumns regardless of the version, whether it's using SSL, etc. and just\nput NULL in any that do not apply. IMHO that would simplify the code and\nhelp prevent confusion. Plus, I'm not aware of any existing meta-commands\nthat provide certain columns conditionally.\n\n+\tif (PQsslInUse(pset.db))\n+\t{\n+\t\tprotocol = PQsslAttribute(pset.db, \"protocol\");\n+\t\tcipher = PQsslAttribute(pset.db, \"cipher\");\n+\t\tcompression = PQsslAttribute(pset.db, \"compression\");\n+\t\tappendPQExpBuffer(&buf,\n+\t\t\t\t\t\t \" ,'SSL' AS \\\"Encryption\\\",\\n\"\n+\t\t\t\t\t\t \" '%s' AS \\\"Protocol\\\",\\n\"\n+\t\t\t\t\t\t \" '%s' AS \\\"Cipher\\\",\\n\"\n+\t\t\t\t\t\t \" '%s' AS \\\"Compression\\\"\\n\",\n+\t\t\t\t\t\t protocol ? protocol : _(\"unknown\"),\n+\t\t\t\t\t\t cipher ? cipher : _(\"unknown\"),\n+\t\t\t\t\t\t (compression && strcmp(compression, \"off\") != 0) ? _(\"on\") : _(\"off\"));\n+\t}\n\nCould we pull some of this information from pg_stat_ssl instead of from\nlibpq? The reason I suggest this is because I think it would be nice if\nthe query that \\conninfo+ uses could be copy/pasted as needed and not rely\non hard-coded values chosen by the client.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Fri, 16 Feb 2024 09:54:49 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi!\n\n>7) -h 0.0.0.0 - As you mentioned, this is one of the cases where host\n>and \"server address\" differ.\n> I am not sure if it is an issue. Perhaps the other reviewers might\n>have an opinion on it\n\n>$ /usr/local/postgres-dev/bin/psql -x -U postgres -h 0.0.0.0 -c\n>\"\\conninfo+\" -c \"\\conninfo\"\n>Current Connection Information\n>-[ RECORD 1 ]------+-----------------------\n>Database | postgres\n>Authenticated User | postgres\n>System User |\n>Current User | postgres\n>Session User | postgres\n>Backend PID | 404395\n>Server Address | 127.0.0.1\n>Server Port | 5432\n>Client Address | 127.0.0.1\n>Client Port | 54806\n>Socket Directory |\n>Host | 0.0.0.0\n>Encryption | SSL\n>Protocol | TLSv1.3\n>Cipher | TLS_AES_256_GCM_SHA384\n>Compression | off\n\nI believe we don't actually have a problem here. To me, this makes sense.\nI'm not a Networking expert, but from my standpoint, any string or IP\naccepted by the \"host\" parameter of psql, pointing to \"127.0.0.1\" or to \"::1\", is correct.\nI see it as a convention (would need to revisit Tanenbaum's books haha),\nand I don't think there's a need to modify it. But as you mentioned, if someone\nwith more Networking knowledge could weigh in, a suggestion would be welcome.\n\n>I'm not sure of the impact of this change in the existing \\conninfo - at\n>least the cfbot and \"make -j check-world\" didn't complain.\n>I'll take a closer look at it as soon we have test cases.\n\nThis type of modification, in principle, does not generate errors as we\nare only changing the display on screen of the strings already previously stored.\n\n>To keep it consistent with the other options, we might wanna use \"+ is\n>appended\" instead of \"+ is specified\" or \"+ is given\"\n\nIt seems to me that \"appended\" sounds good. I opted for it.\nFollowing your suggestion, and merging this with the existing\nprevious ideas from the documentation, I've created a provisional\nprototype of the column descriptions. At a later stage, I'll place the\ndescriptions correctly by removing placeholders (blah blah blah).\nAlong with this, I'll evaluate an iteration suggested by Nathan Bossart,\n\nwho also proposed changes.\n\nThank you for your work.\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Fri, 16 Feb 2024 21:48:16 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi Nathan!\n\n(v18)\n\n>I might be alone on this, but I think this command should output the same\n>columns regardless of the version, whether it's using SSL, etc. and just\n>put NULL in any that do not apply. IMHO that would simplify the code and\n>help prevent confusion. Plus, I'm not aware of any existing meta-commands\n>that provide certain columns conditionally.\n\nI implemented your suggestion. Now, whenever the \\conninfo+ command is\ninvoked, all columns will appear. Contextually inappropriate cases will return\nNULL. I also adjusted the names of the columns related to SSL to make this\ninformation clearer for the user. I haven't focused on documenting the\ncolumns yet. I will do that soon.\n\n>Could we pull some of this information from pg_stat_ssl instead of from\n>libpq? The reason I suggest this is because I think it would be nice if\n>the query that \\conninfo+ uses could be copy/pasted as needed and not rely\n>on hard-coded values chosen by the client.\n\nI've been considering using the views \"pg_stat_ssl\" and \"pg_stat_gssapi\"; however,\nI realized that dealing with version-related cases using them is more complicated.\n\nLet me explain the reasons:\n\nThe \"pg_stat_ssl\" view is available from >= PG 9.5, and the \"pg_stat_gssapi\" view is\navailable from >= PG 12. The \"compression\" column was removed from the\n\"pg_stat_ssl\" from >= PG 14. All of these cases introduce greater complexity in\nmaintaining the SQL. The central idea from the beginning has always been to show\nthe user all the information from \\conninfo and extend it in \\conninfo+. The absence\nof the \"compression\" column in version 14 and above makes dealing with this even\nmore complicated, and not showing it seems to contradict \\conninfo.\n\n\nSSL support has been available since version 7.1 (see documentation); if there was\n\nsupport before that, I can't say. In this regard, it may seem strange, but there are still\nmany legacy systems running older versions of PostgreSQL. Just yesterday, I assisted\na client who is still using PG 8.2. In these cases, using the \"pg_stat_ssl\" and\n\"pg_stat_gssapi\" views would not be possible because they don't exist on the server.\nI believe that psql should cover as many cases as possible when it comes to compatibility\nwith older versions (even those no longer supported). In this case, concerning SSL and\nGSS, I think libpq is better prepared to handle this.\n\nI may be mistaken in my statement and I welcome any better suggestions. For now, I've\nmaintained the implementation using libpq as it seems to be working well and is not\ncontradicting \\conninfo. If you have any suggestions on how to work around the absence\nof the \"compression\" column, we can reconsider how to implement it without using libpq.\n\nTests:\n\n[postgres@localhost bin]$ ./psql -x -h 127.0.0.1 -p 5432\n\nPassword for user postgres:\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"127.0.0.1\" at port \"5432\".\npostgres=# \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]------+-----------------------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User | scram-sha-256:postgres\nCurrent User | postgres\nSession User | postgres\nBackend PID | 22431\nServer Address | 127.0.0.1\nServer Port | 5432\nClient Address | 127.0.0.1\nClient Port | 51300\nSocket Directory |\nHost | 127.0.0.1\nSSL Connection | f\nSSL Protocol |\nSSL Cipher |\nSSL Compression |\nGSSAPI | f\n\n\n[postgres@localhost bin]$ ./psql -x -h 127.0.0.1 -p 5433\nPassword for user postgres:\npsql (17devel, server 15.6)\nSSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, compression: off)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"127.0.0.1\" at port \"5433\".\nSSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, compression: off)\npostgres=# \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]------+----------------------------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User |\nCurrent User | postgres\nSession User | postgres\nBackend PID | 22438\nServer Address | 127.0.0.1\nServer Port | 5433\nClient Address | 127.0.0.1\nClient Port | 36016\nSocket Directory |\nHost | 127.0.0.1\nSSL Connection | t\nSSL Protocol | TLSv1.2\nSSL Cipher | ECDHE-RSA-AES256-GCM-SHA384\nSSL Compression | off\nGSSAPI | f\n\nThank you very much for your sugestions and help!\nMaiquel Grassi.",
"msg_date": "Sat, 17 Feb 2024 14:53:43 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi!\n\n(v19)\n\nAdjusted the description of each column in the documentation as promised.\nI used the existing documentation as a basis for each SQL function used,\nas well as for functions and views related to SSL and GSSAPI (documentation).\n\nIf you can validate, I appreciate it.\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Wed, 21 Feb 2024 23:30:17 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "On Sat, Feb 17, 2024 at 02:53:43PM +0000, Maiquel Grassi wrote:\n> The \"pg_stat_ssl\" view is available from >= PG 9.5, and the \"pg_stat_gssapi\" view is\n> available from >= PG 12. The \"compression\" column was removed from the\n> \"pg_stat_ssl\" from >= PG 14. All of these cases introduce greater complexity in\n> maintaining the SQL. The central idea from the beginning has always been to show\n> the user all the information from \\conninfo and extend it in \\conninfo+.\n\nIMHO we should use the views whenever possible (for the reason stated\nabove [0]). I think it's okay if we need to fall back to a different\napproach for older versions. But presumably we'll discontinue psql support\nfor these old server versions at some point, at which point we can simply\ndelete the dead code that doesn't use the views.\n\n> The absence\n> of the \"compression\" column in version 14 and above makes dealing with this even\n> more complicated, and not showing it seems to contradict \\conninfo.\n\nI would be okay with using PQsslAttribute() for all versions for this one\nsince any remaining support for this feature is on its way out. Once psql\nno longer supports any versions that allow SSL compression, we could\nprobably remove it from \\conninfo[+] completely or hard-code it to \"off\".\n\n> SSL support has been available since version 7.1 (see documentation); if there was\n> \n> support before that, I can't say. In this regard, it may seem strange, but there are still\n> many legacy systems running older versions of PostgreSQL. Just yesterday, I assisted\n> a client who is still using PG 8.2. In these cases, using the \"pg_stat_ssl\" and\n> \"pg_stat_gssapi\" views would not be possible because they don't exist on the server.\n> I believe that psql should cover as many cases as possible when it comes to compatibility\n> with older versions (even those no longer supported). In this case, concerning SSL and\n> GSS, I think libpq is better prepared to handle this.\n\nAt the moment, the psql support cutoff appears to be v9.2 (see commit\ncf0cab8), which has been out of support for over 6 years. If \\conninfo+\nhappens to work for older versions, then great, but I don't think we should\nexpend too much energy in this area.\n\n[0] https://postgr.es/m/20240216155449.GA1236054%40nathanxps13\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Sat, 24 Feb 2024 14:44:12 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "On Sat, Feb 17, 2024 at 02:53:43PM +0000, Maiquel Grassi wrote:\n>> The \"pg_stat_ssl\" view is available from >= PG 9.5, and the \"pg_stat_gssapi\" view is\n>> available from >= PG 12. The \"compression\" column was removed from the\n>> \"pg_stat_ssl\" from >= PG 14. All of these cases introduce greater complexity in\n>> maintaining the SQL. The central idea from the beginning has always been to show\n>> the user all the information from \\conninfo and extend it in \\conninfo+.\n\n>IMHO we should use the views whenever possible (for the reason stated\n>above [0]). I think it's okay if we need to fall back to a different\n>approach for older versions. But presumably we'll discontinue psql support\n>for these old server versions at some point, at which point we can simply\n>delete the dead code that doesn't use the views.\n\n>> The absence\n>> of the \"compression\" column in version 14 and above makes dealing with this even\n>> more complicated, and not showing it seems to contradict \\conninfo.\n\n>I would be okay with using PQsslAttribute() for all versions for this one\n>since any remaining support for this feature is on its way out. Once psql\n>no longer supports any versions that allow SSL compression, we could\n>probably remove it from \\conninfo[+] completely or hard-code it to \"off\".\n\n>> SSL support has been available since version 7.1 (see documentation); if there was\n>> support before that, I can't say. In this regard, it may seem strange, but there are still\n>> many legacy systems running older versions of PostgreSQL. Just yesterday, I assisted\n>> a client who is still using PG 8.2. In these cases, using the \"pg_stat_ssl\" and\n>> \"pg_stat_gssapi\" views would not be possible because they don't exist on the server.\n>> I believe that psql should cover as many cases as possible when it comes to compatibility\n>> with older versions (even those no longer supported). In this case, concerning SSL and\n>> GSS, I think libpq is better prepared to handle this.\n\n>At the moment, the psql support cutoff appears to be v9.2 (see commit\n>cf0cab8), which has been out of support for over 6 years. If \\conninfo+\n>happens to work for older versions, then great, but I don't think we should\n>expend too much energy in this area.\n\n[0] https://postgr.es/m/20240216155449.GA1236054%40nathanxps13\n\n----//----\n\nHi Nathan!\n\nSorry for the delay. I will make the adjustments as requested soon.\n\nRegards,\nMaiquel Grassi.\n\n\n\n\n\n\n\n\nOn Sat, Feb 17, 2024 at 02:53:43PM +0000, Maiquel Grassi wrote:\n>> The \"pg_stat_ssl\" view is available from >= PG 9.5, and the \"pg_stat_gssapi\" view is\n>> available from >= PG 12. The \"compression\" column was removed from the\n>> \"pg_stat_ssl\" from >= PG 14. All of these cases introduce greater complexity in\n>> maintaining the SQL. The central idea from the beginning has always been to show\n>> the user all the information from \\conninfo and extend it in \\conninfo+.\n\n\n>IMHO we should use the views whenever possible (for the reason stated\n>above [0]). I think it's okay if we need to fall back to a different\n>approach for older versions. But presumably we'll discontinue psql support\n>for these old server versions at some point, at which point we can simply\n>delete the dead code that doesn't use the views.\n\n\n>> The absence\n>> of the \"compression\" column in version 14 and above makes dealing with this even\n>> more complicated, and not showing it seems to contradict \\conninfo.\n\n\n>I would be okay with using PQsslAttribute() for all versions for this one\n>since any remaining support for this feature is on its way out. Once psql\n>no longer supports any versions that allow SSL compression, we could\n>probably remove it from \\conninfo[+] completely or hard-code it to \"off\".\n\n\n>> SSL support has been available since version 7.1 (see\n documentation); if there was\n>> support before that, I can't say. In this regard, it may seem strange, but there are still\n>> many legacy systems running older versions of PostgreSQL. Just yesterday, I assisted\n>> a client who is still using PG 8.2. In these cases, using the \"pg_stat_ssl\" and\n>> \"pg_stat_gssapi\" views would not be possible because they don't exist on the server.\n>> I believe that psql should cover as many cases as possible when it comes to compatibility\n>> with older versions (even those no longer supported). In this case, concerning SSL and\n>> GSS, I think libpq is better prepared to handle this.\n\n\n>At the moment, the psql support cutoff appears to be v9.2 (see commit\n>cf0cab8), which has been out of support for over 6 years. If \\conninfo+\n>happens to work for older versions, then great, but I don't think we should\n>expend too much energy in this area.\n\n\n[0] \nhttps://postgr.es/m/20240216155449.GA1236054%40nathanxps13\n\n----//----\n\nHi Nathan!\n\n\nSorry for the delay. I will make the adjustments as requested soon.\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Thu, 29 Feb 2024 22:02:21 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "On Thu, Feb 29, 2024 at 10:02:21PM +0000, Maiquel Grassi wrote:\n> Sorry for the delay. I will make the adjustments as requested soon.\n\nLooking forward to it.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Thu, 29 Feb 2024 16:41:31 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi Maiquel,\n\nOn Thu, Feb 29, 2024 at 10:02:21PM +0000, Maiquel Grassi wrote:\n> Sorry for the delay. I will make the adjustments as requested soon.\n\nWe have only a few weeks left before feature-freeze for v17. Do you think\nyou will be able to send an updated patch soon?\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Thu, 14 Mar 2024 11:46:11 -0500",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "On Thu, Feb 29, 2024 at 10:02:21PM +0000, Maiquel Grassi wrote:\n> Sorry for the delay. I will make the adjustments as requested soon.\n\nLooking forward to it.\n\n----//----\n\nHi Nathan!\n\nSorry for the delay, I was busy with other professional as well as personal activities.\n\nI made all the changes you suggested. I removed the variables and started using\nviews \"pg_stat_ssl\" and \"pg_stat_gssapi\". I handled the PostgreSQL versioning regarding the views used.\n\nHere's a brief demonstration of the result:\n\n[postgres@localhost ~]$ /home/pgsql-17devel/bin/psql -E -x -p 5433\n\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo+\n/******** QUERY *********/\nSELECT\n pg_catalog.current_database() AS \"Database\",\n 'postgres' AS \"Authenticated User\",\n pg_catalog.system_user() AS \"System User\",\n pg_catalog.current_user() AS \"Current User\",\n pg_catalog.session_user() AS \"Session User\",\n pg_catalog.pg_backend_pid() AS \"Backend PID\",\n pg_catalog.inet_server_addr() AS \"Server Address\",\n pg_catalog.current_setting('port') AS \"Server Port\",\n pg_catalog.inet_client_addr() AS \"Client Address\",\n pg_catalog.inet_client_port() AS \"Client Port\",\n '/tmp' AS \"Socket Directory\",\n CASE\n WHEN\n pg_catalog.inet_server_addr() IS NULL\n AND pg_catalog.inet_client_addr() IS NULL\n THEN NULL\n ELSE '/tmp'\n END AS \"Host\",\n (SELECT gss_authenticated AS \"GSSAPI\"\n FROM pg_catalog.pg_stat_gssapi\n WHERE pid = pg_catalog.pg_backend_pid()),\n ssl.ssl AS \"SSL Connection\",\n ssl.version AS \"SSL Protocol\",\n ssl.cipher AS \"SSL Cipher\",\n NULL AS \"SSL Compression\"\nFROM\n pg_catalog.pg_stat_ssl ssl\nWHERE\n pid = pg_catalog.pg_backend_pid()\n;\n/************************/\n\nCurrent Connection Information\n-[ RECORD 1 ]------+---------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User |\nCurrent User | postgres\nSession User | postgres\nBackend PID | 29007\nServer Address |\nServer Port | 5433\nClient Address |\nClient Port |\nSocket Directory | /tmp\nHost |\nGSSAPI | f\nSSL Connection | f\nSSL Protocol |\nSSL Cipher |\nSSL Compression |\n\nRergards,\nMaiquel Grassi.",
"msg_date": "Mon, 18 Mar 2024 22:05:17 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "> Hi Nathan!\n\n>\n> Sorry for the delay, I was busy with other professional as well as personal activities.\n\n> I made all the changes you suggested. I removed the variables and started using\n> views \"pg_stat_ssl\" and \"pg_stat_gssapi\". I handled the PostgreSQL versioning regarding the views used.\n\n--//--\n\nOlá Nathan!\n\nI think we are very close to possibly finishing this patch, and\nI would like your help to do it. Is there any correction you\ndeem necessary still?\n\nRegards,\nMaiquel Grassi.\n\n\n\n\n\n\n\n\n> Hi Nathan!\n>\n> Sorry for the delay, I was busy with other professional as well as personal activities.\n> I made all the changes you suggested. I removed the variables and started using\n> views \"pg_stat_ssl\" and \"pg_stat_gssapi\". I handled the PostgreSQL versioning regarding the views used.\n\n--//--\n\nOlá Nathan!\n\nI think we are very close to possibly finishing this patch, and\nI would like your help to do it. Is there any correction you\ndeem necessary still?\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Wed, 27 Mar 2024 13:23:32 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi,\r\n\r\nThanks for working on this.\r\n\r\nI have a few comments about the current patch.\r\n\r\n1/ I looked through other psql-meta commands and the “+” adds details but\r\ndoes not change output format. In this patch, conninfo and conninfo+\r\nhave completely different output. The former is a string with all the details\r\nand the latter is a table. Should conninfo just be a table with the minimal info\r\nand additional details can be displayed with \"+\" appended?\r\n\r\ninstead of \\conninfo displaying a string\r\n\r\nYou are connected to database \"postgres\" as user \"postgres\" on host \"127.0.01\" (address \"127.0.0.1\") at port \"5432\".\r\n\r\nIt can instead display the same information in table format\r\n\r\nCurrent Connection Information\r\n-[ RECORD 1 ]-----------+-----------------------\r\nDatabase | postgres\r\nAuthenticated User | postgres\r\nSocket Directory |\r\nHost | 127.0.0.1\r\nPort | 5432\r\n\r\nand \\conninfo+ can show the rest of the details\r\n\r\nCurrent Connection Information\r\n-[ RECORD 1 ]----------+----------------------------\r\nDatabase | postgres\r\nAuthenticated User | postgres\r\nSocket Directory |\r\nHost | 127.0.0.1\r\nPort | 5432\r\nBackend PID | 1234\r\n...\r\n.....\r\n\r\n2/ GSSAPI details should show the full details, such as \"principal\",\r\n\"encrypted\" and \"credentials_delegated\".\r\n\r\nThis also means that pg_stat_ssl will need to be joined with pg_stat_gssapi\r\n\r\n\r\nFROM\r\n\r\npg_catalog.pg_stat_ssl ssl LEFT JOIN pg_catalog.pg_stat_gssapi gssapi\r\n\r\nON ssl.pid = gssapi.pid\r\n\r\nssl.pid = pg_catalog.pg_backend_pid()\r\n\r\n\r\n3/ A very nice to have is \"Application Name\", in the case one\r\nsets the application_name within a connection or in the connection string.\r\n\r\nRegards,\r\n\r\nSami Imseih\r\nAmazon Web Services (AWS)\r\n\r\n\r\n\r\n\n\n\n\n\n\n\n\n\nHi,\n \nThanks for working on this.\n \nI have a few comments about the current patch.\n \n1/ I looked through other psql-meta commands and the “+” adds details but\ndoes not change output format. In this patch, conninfo and conninfo+\r\n\nhave completely different output. The former is a string with all the details\r\n\nand the latter is a table. Should conninfo just be a table with the minimal info\r\n\nand additional details can be displayed with \"+\" appended?\n \ninstead of \\conninfo displaying a string\n \nYou are connected to database \"postgres\" as user \"postgres\" on host \"127.0.01\" (address \"127.0.0.1\") at port \"5432\".\n \nIt can instead display the same information in table format\n \nCurrent Connection Information\n-[ RECORD 1 ]-----------+-----------------------\nDatabase | postgres\nAuthenticated User | postgres\nSocket Directory | \nHost | 127.0.0.1\nPort | 5432\n \nand \\conninfo+ can show the rest of the details\n \nCurrent Connection Information\n-[ RECORD 1 ]----------+----------------------------\nDatabase | postgres\nAuthenticated User | postgres\nSocket Directory | \nHost | 127.0.0.1\nPort | 5432\nBackend PID | 1234\n...\n.....\n \n2/ GSSAPI details should show the full details, such as \"principal\",\n\"encrypted\" and \"credentials_delegated\".\n \nThis also means that pg_stat_ssl will need to be joined with pg_stat_gssapi\n \nFROM\npg_catalog.pg_stat_ssl ssl LEFT JOIN pg_catalog.pg_stat_gssapi gssapi\nON ssl.pid = gssapi.pid\nssl.pid = pg_catalog.pg_backend_pid()\n \n \n3/ A very nice to have is \"Application Name\", in the case one\r\n\nsets the application_name within a connection or in the connection string.\n \nRegards,\n \nSami Imseih \nAmazon Web Services (AWS)",
"msg_date": "Wed, 27 Mar 2024 23:08:24 +0000",
"msg_from": "\"Imseih (AWS), Sami\" <simseih@amazon.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi Sami!\n\n(v21)\n\nFirst and foremost, thank you very much for the review.\n\n\n> 1/ I looked through other psql-meta commands and the “+” adds details but\n\n> does not change output format. In this patch, conninfo and conninfo+\n\n> have completely different output. The former is a string with all the details\n\n> and the latter is a table. Should conninfo just be a table with the minimal info\n\n> and additional details can be displayed with \"+\" appended?\n\nThe initial and central idea was always to keep the metacommand\n\"\\conninfo\" in its original state, that is, to preserve the string as it is.\nThe idea of \"\\conninfo+\" is to expand this to include more information.\nIf I change the \"\\conninfo\" command and transform it into a table,\nI would have to remove all the translation part (files) that has already\nbeen implemented in the past. I believe that keeping the string and\nits translations is a good idea and there is no great reason to change that.\n\n> 2/ GSSAPI details should show the full details, such as \"principal\",\n\n> \"encrypted\" and \"credentials_delegated\".\n\nIn this new patch, I added these columns. I handled the 'server versions'\nfor cases where the 'credentials_delegated' column is not in the view.\nIt turned out well. Thank you for the idea.\n\n3/ A very nice to have is \"Application Name\", in the case one\n\nsets the application_name within a connection or in the connection string.\n\nI did the same here. I liked your idea and added this column in the SQL.\n\nLook below to see how it turned out after it's finished.\n\nExemple 1:\n\n[postgres@localhost ~]$ /home/pgsql-17devel/bin/psql -x -p 5432\n\npsql (17devel, server 15.6)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5432\".\npostgres=# \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]----------------+---------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User |\nCurrent User | postgres\nSession User | postgres\nApplication Name | psql\nBackend PID | 19439\nServer Address |\nServer Port | 5432\nClient Address |\nClient Port |\nSocket Directory | /tmp\nHost |\nSSL Connection | f\nSSL Protocol |\nSSL Cipher |\nSSL Compression |\nGSSAPI Authenticated | f\nGSSAPI Principal |\nGSSAPI Encrypted | f\nGSSAPI Credentials Delegated |\n\nExemple 2:\n\n[postgres@localhost ~]$ /home/pgsql-17devel/bin/psql -x -p 5000\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5000\".\npostgres=# \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]----------------+---------\nDatabase | postgres\nAuthenticated User | postgres\nSystem User |\nCurrent User | postgres\nSession User | postgres\nApplication Name | psql\nBackend PID | 19468\nServer Address |\nServer Port | 5000\nClient Address |\nClient Port |\nSocket Directory | /tmp\nHost |\nSSL Connection | f\nSSL Protocol |\nSSL Cipher |\nSSL Compression |\nGSSAPI Authenticated | f\nGSSAPI Principal |\nGSSAPI Encrypted | f\nGSSAPI Credentials Delegated | f\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Thu, 28 Mar 2024 19:07:47 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Thank you for the updated patch.\r\n\r\nFirst and foremost, thank you very much for the review.\r\n\r\n> The initial and central idea was always to keep the metacommand\r\n> \"\\conninfo\" in its original state, that is, to preserve the string as it is.\r\n> The idea of \"\\conninfo+\" is to expand this to include more information.\r\n> If I change the \"\\conninfo\" command and transform it into a table,\r\n> I would have to remove all the translation part (files) that has already\r\n> been implemented in the past. I believe that keeping the string and\r\n> its translations is a good idea and there is no great reason to change that.\r\n\r\nYou are right. Not much to be gained to change this.\r\n\r\n\r\n\r\nFor the current patch, I have a few more comments.\r\n\r\n\r\n\r\n1/ The output should be reorganized to show the fields that are part of “conninfo” first.\r\n\r\n\r\n\r\nI suggest it should look like this:\r\n\r\n\r\n\r\nCurrent Connection Information\r\n\r\n-[ RECORD 1 ]----------------+---------\r\n\r\nDatabase | postgres\r\n\r\nAuthenticated User | postgres\r\n\r\nSocket Directory | /tmp\r\n\r\nHost |\r\n\r\nServer Port | 5432\r\n\r\nServer Address |\r\n\r\nClient Address |\r\n\r\nClient Port |\r\n\r\nBackend PID | 30846\r\n\r\nSystem User |\r\n\r\nCurrent User | postgres\r\n\r\nSession User | postgres\r\n\r\nApplication Name | psql\r\n\r\nSSL Connection | f\r\n\r\nSSL Protocol |\r\n\r\nSSL Cipher |\r\n\r\nSSL Compression |\r\n\r\nGSSAPI Authenticated | f\r\n\r\nGSSAPI Principal |\r\n\r\nGSSAPI Encrypted | f\r\n\r\nGSSAPI Credentials Delegated | f\r\n\r\n\r\n\r\n\r\n\r\nWith regards to the documentation. I think it's a good idea that every field has an\r\n\r\ndescription. However, I have some comments:\r\n\r\n\r\n\r\n1/ For the description of the conninfo command, what about simplifying like below?\r\n\r\n\r\n\r\n\"Outputs a string displaying information about the current database connection. When + is appended, more details about the connection are displayed in table format:\"\r\n\r\n\r\n\r\n2/ I don't think the descriptions need to start with \"Displays\". It is very repetitive.\r\n\r\n\r\n\r\n3/ For the \"Socket Directory\" description, this could be NULL if the host was not specified.\r\n\r\n\r\n\r\nwhat about the below?\r\n\r\n\r\n\r\n\"The socket directory of the connection. NULL if the host or hostaddr are specified for the connection\"\r\n\r\n\r\n\r\n4/ For most of the fields, they are just the output of a function, such as \"pg_catalog.system_user()\". What about the docs simply\r\n\r\nlink to the documentation of the function. This way we are not copying descriptions and have to be concerned if the description\r\n\r\nof the function changes in the future.\r\n\r\n\r\n\r\n5/ \"true\" and \"false\", do not need double quotes. This is not the convention used in other places docs.\r\n\r\n\r\n\r\n\r\n\r\nRegards,\r\n\r\n\r\n\r\nSami\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\n\n\n\n\n\n\n\n\n\n\nThank you for the updated patch.\n\r\nFirst and foremost, thank you very much for the review.\n\n> The initial and central idea was always to keep the metacommand\n> \"\\conninfo\" in its original state, that is, to preserve the string as it is.\n> The idea of \"\\conninfo+\" is to expand this to include more information.\n> If I change the \"\\conninfo\" command and transform it into a table,\n> I would have to remove all the translation part (files) that has already\n> been implemented in the past. I believe that keeping the string and\n> its translations is a good idea and there is no great reason to change that.\n\nYou are right. Not much to be gained to change this.\n \nFor the current patch, I have a few more comments.\n \n1/ The output should be reorganized to show the fields that are part of “conninfo” first.\n \nI suggest it should look like this:\n \nCurrent Connection Information\n-[ RECORD 1 ]----------------+---------\nDatabase | postgres\nAuthenticated User | postgres\nSocket Directory | /tmp\nHost |\r\n\nServer Port | 5432\nServer Address |\nClient Address |\r\n\nClient Port |\nBackend PID | 30846\r\n\nSystem User |\r\n\nCurrent User | postgres\nSession User | postgres\nApplication Name | psql\nSSL Connection | f\nSSL Protocol |\r\n\nSSL Cipher |\r\n\nSSL Compression |\r\n\nGSSAPI Authenticated | f\nGSSAPI Principal |\r\n\nGSSAPI Encrypted | f\nGSSAPI Credentials Delegated | f\n \n \nWith regards to the documentation. I think it's a good idea that every field has an\r\n\ndescription. However, I have some comments:\n \n1/ For the description of the conninfo command, what about simplifying like below?\n \n\"Outputs a string displaying information about the current database connection. When + is appended, more details about the connection are displayed in table format:\"\n \n2/ I don't think the descriptions need to start with \"Displays\". It is very repetitive.\n \n3/ For the \"Socket Directory\" description, this could be NULL if the host was not specified.\r\n\n \nwhat about the below?\n \n\"The socket directory of the connection. NULL if the host or hostaddr are specified for the connection\"\n \n4/ For most of the fields, they are just the output of a function, such as \"pg_catalog.system_user()\". What about the docs simply\nlink to the documentation of the function. This way we are not copying descriptions and have to be concerned if the description\nof the function changes in the future.\n \n5/ \"true\" and \"false\", do not need double quotes. This is not the convention used in other places docs.\n \n \nRegards,\n \nSami",
"msg_date": "Fri, 29 Mar 2024 06:13:56 +0000",
"msg_from": "\"Imseih (AWS), Sami\" <simseih@amazon.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "> For the current patch, I have a few more comments.\n\n> 1/ The output should be reorganized to show the fields that are part of “conninfo” first.\n\n> With regards to the documentation. I think it's a good idea that every field has an\n\n> description. However, I have some comments:\n\n> 1/ For the description of the conninfo command, what about simplifying like below?\n\n> \"Outputs a string displaying information about the current database connection. When + is appended, more details about the connection are displayed in table format:\"\n\n> 2/ I don't think the descriptions need to start with \"Displays\". It is very repetitive.\n\n> 3/ For the \"Socket Directory\" description, this could be NULL if the host was not specified.\n\n> What about the below?\n\n> \"The socket directory of the connection. NULL if the host or hostaddr are specified for the connection\"\n\n\n> 4/ For most of the fields, they are just the output of a function, such as \"pg_catalog.system_user()\". What about the docs simply\n\n> link to the documentation of the function. This way we are not copying descriptions and have to be concerned if the description\n\n> of the function changes in the future.\n\n\n> 5/ \"true\" and \"false\", do not need double quotes. This is not the convention used in other places docs.\n\n-----//-----\n\nHi Sami!\n\n(v22)\n\n\nI did everything you mentioned earlier, that is, I followed all your suggestions. However,\nI didn't complete item 4. I'm not sure, but I believe that linking it to the documentation\ncould confuse the user a bit. I chose to keep the descriptions as they were. However, if\nyou have any ideas on how we could outline it, let me know and perhaps we can\nimplement it.\n\nThank you so much!\n\nExemples:\n\n[postgres@localhost bin]$ ./psql -x -p 5000 -h 127.0.0.1\n\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"127.0.0.1\" at port \"5000\".\npostgres=# \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]----------------+----------\nDatabase | postgres\nAuthenticated User | postgres\nSocket Directory |\nHost | 127.0.0.1\nServer Port | 5000\nServer Address | 127.0.0.1\nClient Address | 127.0.0.1\nClient Port | 33100\nBackend PID | 2974\nSystem User |\nCurrent User | postgres\nSession User | postgres\nApplication Name | psql\nSSL Connection | f\nSSL Protocol |\nSSL Cipher |\nSSL Compression |\nGSSAPI Authenticated | f\nGSSAPI Principal |\nGSSAPI Encrypted | f\nGSSAPI Credentials Delegated | f\n\npostgres=# \\q\n[postgres@localhost bin]$ ./psql -x -p 5432 -h localhost\nPassword for user postgres:\npsql (17devel, server 15.6)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"localhost\" (address \"::1\") at port \"5432\".\npostgres=# \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]----------------+----------\nDatabase | postgres\nAuthenticated User | postgres\nSocket Directory |\nHost | localhost\nServer Port | 5432\nServer Address | ::1\nClient Address | ::1\nClient Port | 57010\nBackend PID | 3000\nSystem User |\nCurrent User | postgres\nSession User | postgres\nApplication Name | psql\nSSL Connection | f\nSSL Protocol |\nSSL Cipher |\nSSL Compression |\nGSSAPI Authenticated | f\nGSSAPI Principal |\nGSSAPI Encrypted | f\nGSSAPI Credentials Delegated |\n\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Sat, 30 Mar 2024 16:23:24 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Hello,\n\nNote that, in the patch as posted, the column names are not\ntranslatable. In order to be translatable, the code needs to do\nsomething like\n\nappendPQExpBuffer(&buf,\n\t\t\" NULL AS \\\"%s\\\",\\n\"\n\t\t\" NULL AS \\\"%s\\\",\\n\"\n\t\t\" NULL AS \\\"%s\\\",\\n\"\n\t\t\" NULL AS \\\"%s\\\",\\n\",\n\t\t_(\"SSL Connection\"),\n\t\t_(\"SSL Protocol\"),\n\t\t_(\"SSL Cipher\"),\n\t\t_(\"SSL Compression\"));\n\ninstead of \n\n appendPQExpBuffer(&buf,\n \" NULL AS \\\"SSL Connection\\\",\\n\"\n \" NULL AS \\\"SSL Protocol\\\",\\n\"\n \" NULL AS \\\"SSL Cipher\\\",\\n\"\n \" NULL AS \\\"SSL Compression\\\",\\n\");\n\n\nPlease list me as reviewer for this patch, as I provided significant\nguidance before it was even posted.\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/\n\n\n",
"msg_date": "Sat, 30 Mar 2024 18:09:19 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Note that, in the patch as posted, the column names are not\ntranslatable. In order to be translatable, the code needs to do\nsomething like\n\nappendPQExpBuffer(&buf,\n \" NULL AS \\\"%s\\\",\\n\"\n \" NULL AS \\\"%s\\\",\\n\"\n \" NULL AS \\\"%s\\\",\\n\"\n \" NULL AS \\\"%s\\\",\\n\",\n _(\"SSL Connection\"),\n _(\"SSL Protocol\"),\n _(\"SSL Cipher\"),\n _(\"SSL Compression\"));\n\ninstead of\n\n appendPQExpBuffer(&buf,\n \" NULL AS \\\"SSL Connection\\\",\\n\"\n \" NULL AS \\\"SSL Protocol\\\",\\n\"\n \" NULL AS \\\"SSL Cipher\\\",\\n\"\n \" NULL AS \\\"SSL Compression\\\",\\n\");\n\n\nPlease list me as reviewer for this patch, as I provided significant\nguidance before it was even posted.\n\n-----//-----\n\nHello!\n\n(v23)\n\nYes Álvaro, I have already appointed you as the patch reviewer.\nIt's true, even before publishing it on Commifest, you have\nalready provided good ideas and guidance.\n\nI adjusted the translation syntax for the SSL and GSSAPI columns.\nAfter your validation, that is, an okay confirmation that it's fine, I'll\nproceed with the others.\n\nTest:\n\n[postgres@localhost bin]$ ./psql -x -p 5000 -h 127.0.0.1\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" on host \"127.0.0.1\" at port \"5000\".\npostgres=# \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]----------------+----------\nDatabase | postgres\nAuthenticated User | postgres\nSocket Directory |\nHost | 127.0.0.1\nServer Port | 5000\nServer Address | 127.0.0.1\nClient Address | 127.0.0.1\nClient Port | 52966\nBackend PID | 1693\nSystem User |\nCurrent User | postgres\nSession User | postgres\nApplication Name | psql\nSSL Connection | f\nSSL Protocol |\nSSL Cipher |\nSSL Compression |\nGSSAPI Authenticated | f\nGSSAPI Principal |\nGSSAPI Encrypted | f\nGSSAPI Credentials Delegated | f\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Sun, 31 Mar 2024 21:39:54 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": ">. However,\r\n> I didn't complete item 4. I'm not sure, but I believe that linking it to the documentation\r\n> could confuse the user a bit. I chose to keep the descriptions as they were. However, if\r\n> you have any ideas on how we could outline it, let me know and perhaps we can\r\n> implement it.\r\n\r\n\r\n\r\nThat is fair, after spending some time thinking about this, it is better\r\n\r\nto make the documentation as crystal clear as possible.\r\n\r\n\r\n\r\nI do have some rewording suggestions for the following fields.\r\n\r\n\r\n\r\n\r\n\r\nDatabase:\r\n\r\nThe database name of the connection.\r\n\r\n\r\n\r\nAuthenticated User:\r\n\r\nThe authenticated database user of the connection.\r\n\r\n\r\n\r\nSocket Directory:\r\n\r\nThe Unix socket directory of the connection. NULL if host or hostaddr are specified.\r\n\r\n\r\n\r\nHost:\r\n\r\nThe host name or address of the connection. NULL if a Unix socket is used.\r\n\r\n\r\n\r\nServer Port:\r\n\r\nThe IP address of the connection. NULL if a Unix socket is used.\r\n\r\n\r\n\r\nServer Address:\r\n\r\nThe IP address of the host name. NULL if a Unix socket is used.\r\n\r\n\r\n\r\nClient Address:\r\n\r\nThe IP address of the client connected to this backend. NULL if a Unix socket is used.\r\n\r\n\r\n\r\nClient Port:\r\n\r\nThe port of the client connected to this backend. NULL if a Unix socket is used.\r\n\r\n\r\n\r\nBackend PID:\r\n\r\nThe process id of the backend for the connection.\r\n\r\n\r\n\r\nApplication name:\r\n\r\n<literal>psql<literal> is the default for a psql connection\r\n\r\nunless otherwise specified in the <xref linkend=\"guc-application-name\"/>\r\n\r\nconfiguration parameter.\r\n\r\n\r\n\r\nFor System User, you should use the full definition here\r\n\r\nhttps://github.com/postgres/postgres/blob/master/doc/src/sgml/func.sgml#L24251-L24259.\r\n\r\nThe current path is missing the full description.\r\n\r\n\r\n\r\n\r\n\r\nRegards,\r\n\r\n\r\n\r\nSami\r\n\r\n\r\n\n\n\n\n\n\n\n\n\n\n>. However,\n> I didn't complete item 4. I'm not sure, but I believe that linking it to the documentation\n> could confuse the user a bit. I chose to keep the descriptions as they were. However, if\n> you have any ideas on how we could outline it, let me know and perhaps we can\n> implement it.\n \nThat is fair, after spending some time thinking about this, it is better\nto make the documentation as crystal clear as possible.\n \nI do have some rewording suggestions for the following fields.\n \n \nDatabase:\nThe database name of the connection.\n \nAuthenticated User:\nThe authenticated database user of the connection.\n \nSocket Directory:\nThe Unix socket directory of the connection. NULL if host or hostaddr are specified.\n \nHost:\nThe host name or address of the connection. NULL if a Unix socket is used.\n \nServer Port:\nThe IP address of the connection. NULL if a Unix socket is used.\n \nServer Address:\nThe IP address of the host name. NULL if a Unix socket is used.\n \nClient Address:\nThe IP address of the client connected to this backend. NULL if a Unix socket is used.\n \nClient Port: \nThe port of the client connected to this backend. NULL if a Unix socket is used.\n \nBackend PID:\nThe process id of the backend for the connection.\n \nApplication name:\n<literal>psql<literal> is the default for a psql connection\r\n\nunless otherwise specified in the <xref linkend=\"guc-application-name\"/>\r\n\nconfiguration parameter.\n \nFor System User, you should use the full definition here\r\n\nhttps://github.com/postgres/postgres/blob/master/doc/src/sgml/func.sgml#L24251-L24259.\r\n\nThe current path is missing the full description.\n \n \nRegards,\n \nSami",
"msg_date": "Sun, 31 Mar 2024 22:59:44 +0000",
"msg_from": "\"Imseih (AWS), Sami\" <simseih@amazon.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "On 2024-Mar-31, Maiquel Grassi wrote:\n\n> Yes Álvaro, I have already appointed you as the patch reviewer.\n> It's true, even before publishing it on Commifest, you have\n> already provided good ideas and guidance.\n\nThanks.\n\n> I adjusted the translation syntax for the SSL and GSSAPI columns.\n> After your validation, that is, an okay confirmation that it's fine, I'll\n> proceed with the others.\n\nI meant those columns to be just examples, but this should be applied to\nall the other columns in the output as well.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"No necesitamos banderas\n No reconocemos fronteras\" (Jorge González)\n\n\n",
"msg_date": "Mon, 1 Apr 2024 12:51:18 +0200",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi!\n\n(v24)\n\n> I meant those columns to be just examples, but this should be applied to\n> all the other columns in the output as well.\n\nApplied the translation to all columns.\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Mon, 1 Apr 2024 14:53:05 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Hello\n\nYeah, that's what I meant about the translations, thanks.\n\n\nTwo more comments,\n\n- You don't need a two-level conditional here\n\tif (pset.sversion >= 90500)\n\t{\n\t\tif (pset.sversion < 140000)\n\t\t\tappendPQExpBuffer(&buf,\n\t\t\t\t\t\t\t \" ssl.ssl AS \\\"%s\\\",\\n\"\n\t\t\t\t\t\t\t \" ssl.version AS \\\"%s\\\",\\n\"\n\t\t\t\t\t\t\t \" ssl.cipher AS \\\"%s\\\",\\n\"\n\t\t\t\t\t\t\t \" ssl.compression AS \\\"%s\\\",\\n\",\n\t\t\t\t\t\t\t _(\"SSL Connection\"),\n\t\t\t\t\t\t\t _(\"SSL Protocol\"),\n\t\t\t\t\t\t\t _(\"SSL Cipher\"),\n\t\t\t\t\t\t\t _(\"SSL Compression\"));\n\t\tif (pset.sversion >= 140000)\n\t\t\tappendPQExpBuffer(&buf,\n\t\t\t\t\t\t\t \" ssl.ssl AS \\\"%s\\\",\\n\"\n\t\t\t\t\t\t\t \" ssl.version AS \\\"%s\\\",\\n\"\n\t\t\t\t\t\t\t \" ssl.cipher AS \\\"%s\\\",\\n\"\n\t\t\t\t\t\t\t \" NULL AS \\\"%s\\\",\\n\",\n\t\t\t\t\t\t\t _(\"SSL Connection\"),\n\t\t\t\t\t\t\t _(\"SSL Protocol\"),\n\t\t\t\t\t\t\t _(\"SSL Cipher\"),\n\t\t\t\t\t\t\t _(\"SSL Compression\"));\n\t}\n\telse\n\t\tappendPQExpBuffer(&buf,\n\t\t\t\t\t\t \" NULL AS \\\"%s\\\",\\n\"\n\t\t\t\t\t\t \" NULL AS \\\"%s\\\",\\n\"\n\t\t\t\t\t\t \" NULL AS \\\"%s\\\",\\n\"\n\t\t\t\t\t\t \" NULL AS \\\"%s\\\",\\n\",\n\t\t\t\t\t\t _(\"SSL Connection\"),\n\t\t\t\t\t\t _(\"SSL Protocol\"),\n\t\t\t\t\t\t _(\"SSL Cipher\"),\n\t\t\t\t\t\t _(\"SSL Compression\"));\n\n Instead you can just do something like\n\n if (pset.version >= 140000)\n one thing;\n else if (pset.version > 90500)\n second thing;\n else\n third thing;\n\n This also appears where you add the GSSAPI columns; and it's also in the\n final part where you append the FROM clause, though it looks a bit\n different there.\n\n- You have three lines to output a semicolon at the end of the query\n based on version number. Remove the first two, and just have a final\n one where the semicolon is added unconditionally.\n\n- I don't think one <para> for each item in the docs is reasonable.\n There's too much vertical whitespace in the output. Maybe do this\n instead:\n\n [...]\n database connection. When <literal>+</literal> is appended,\n more details about the connection are displayed in table\n format:\n\n <simplelist>\n <member>\n <term>Database:</term> The name of the current\n database on this connection.\n </member>\n\n <member>\n <term>Authenticated User:</term> The authenticated\n user at the time of psql connection with the server.\n </member>\n\t \n ...\n </simplelist>\n\n\n- This text is wrong to start with \"Returns the\":\n\n System User: Returns the authentication method and the identity (if\n any) that the user presented during the authentication cycle before\n they were assigned a database role. It is represented as\n auth_method:identity or NULL if the user has not been authenticated.\n\n That minor point aside, I disagree with Sami about repeating the docs\n for system_user() here. I would just say \"The authentication data\n provided for this connection; see the function system_user() for more\n details.\" with a link to the appropriate section of the docs. Making\n us edit this doc if we ever modify the behavior of the function is not\n great.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"We're here to devour each other alive\" (Hobbes)\n\n\n",
"msg_date": "Mon, 1 Apr 2024 18:22:41 +0200",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "> That minor point aside, I disagree with Sami about repeating the docs\r\n> for system_user() here. I would just say \"The authentication data\r\n> provided for this connection; see the function system_user() for more\r\n> details.\" \r\n\r\n+1. FWIW; Up the thread [1], I did mention we should link to the functions page,\r\nbut did not have a very strong opinion on that. \r\n\r\nI do like your suggestion and the same should be done for \"Current User\" \r\nand \"Session User\" as well. \r\n\r\n[1] https://www.postgresql.org/message-id/640B2586-EECF-44C0-B474-CA8510F8EAFC%40amazon.com\r\n\r\nRegards,\r\n\r\nSami\r\n\r\n\r\n\r\n\r\n\r\n",
"msg_date": "Mon, 1 Apr 2024 17:45:10 +0000",
"msg_from": "\"Imseih (AWS), Sami\" <simseih@amazon.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Database:\n\nThe database name of the connection.\n\n\n\nAuthenticated User:\n\nThe authenticated database user of the connection.\n\n\n\nSocket Directory:\n\nThe Unix socket directory of the connection. NULL if host or hostaddr are specified.\n\n\n\nHost:\n\nThe host name or address of the connection. NULL if a Unix socket is used.\n\n\n\nServer Port:\n\nThe IP address of the connection. NULL if a Unix socket is used.\n\n\n\nServer Address:\n\nThe IP address of the host name. NULL if a Unix socket is used.\n\n\n\nClient Address:\n\nThe IP address of the client connected to this backend. NULL if a Unix socket is used.\n\n\n\nClient Port:\n\nThe port of the client connected to this backend. NULL if a Unix socket is used.\n\n\n\nBackend PID:\n\nThe process id of the backend for the connection.\n\n\n\nApplication name:\n\n<literal>psql<literal> is the default for a psql connection\n\nunless otherwise specified in the <xref linkend=\"guc-application-name\"/>\n\nconfiguration parameter.\n\n\n\n-----//-----\n\nHi Sami,\nI considered your suggestions and Álvaro's suggestions\nRegards,\nMaiquel Grassi.\n\n\n\n\n\n\n\n\nDatabase:\n\nThe database name of the connection.\n\n \nAuthenticated User:\nThe authenticated database user of the connection.\n \nSocket Directory:\nThe Unix socket directory of the connection. NULL if host or hostaddr are specified.\n \nHost:\nThe host name or address of the connection. NULL if a Unix socket is used.\n \nServer Port:\n\nThe IP address of the connection. NULL if a Unix socket is used.\n\n \nServer Address:\nThe IP address of the host name. NULL if a Unix socket is used.\n \nClient Address:\n\nThe IP address of the client connected to this backend. NULL if a Unix socket is used.\n\n \nClient Port:\nThe port of the client connected to this backend. NULL if a Unix socket is used.\n \nBackend PID:\nThe process id of the backend for the connection.\n \nApplication name:\n\n<literal>psql<literal> is the default for a psql connection\nunless otherwise specified in the <xref linkend=\"guc-application-name\"/>\nconfiguration parameter.\n\n \n-----//-----\n\nHi Sami,\nI considered your suggestions and Álvaro's suggestions\nRegards,\nMaiquel Grassi.",
"msg_date": "Mon, 1 Apr 2024 19:19:58 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Amigos, boa tarde!\n\n(v25)\n\n> if (pset.version >= 140000)\n> one thing;\n> else if (pset.version > 90500)\n> second thing;\n> else\n> third thing;\n>\n> This also appears where you add the GSSAPI columns; and it's also in the\n> final part where you append the FROM clause, though it looks a bit\n> different there.\n>\n> - You have three lines to output a semicolon at the end of the query\n> based on version number. Remove the first two, and just have a final\n> one where the semicolon is added unconditionally.\n\nAdjustment made.\n\n> - I don't think one <para> for each item in the docs is reasonable.\n> There's too much vertical whitespace in the output. Maybe do this\n> instead:\n>\n> [...]\n> database connection. When <literal>+</literal> is appended,\n> more details about the connection are displayed in table\n> format:\n>\n> <simplelist>\n> <member>\n> <term>Database:</term> The name of the current\n> database on this connection.\n> </member>\n>\n> <member>\n> <term>Authenticated User:</term> The authenticated\n> user at the time of psql connection with the server.\n> </member>\n>\n> ...\n> </simplelist>\n\nAdjustment made. But I think it needs a review glance.\n\n> - This text is wrong to start with \"Returns the\":\n>\n> System User: Returns the authentication method and the identity (if\n> any) that the user presented during the authentication cycle before\n> they were assigned a database role. It is represented as\n> auth_method:identity or NULL if the user has not been authenticated.\n>\n> That minor point aside, I disagree with Sami about repeating the docs\n> for system_user() here. I would just say \"The authentication data\n> provided for this connection; see the function system_user() for more\n> details.\" with a link to the appropriate section of the docs. Making\n> us edit this doc if we ever modify the behavior of the function is not\n> great.\n\nHere I considered your suggestion (Sami and Álvaro's). However, I haven't yet\nadded the links for the functions system_user(), current_user(), and session_user().\nI'm not sure how to do it. Any suggestion on how to create/add the link?\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Mon, 1 Apr 2024 19:51:57 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "> Here I considered your suggestion (Sami and Álvaro's). However, I haven't yet\r\n> added the links for the functions system_user(), current_user(), and session_user().\r\n> 'm not sure how to do it. Any suggestion on how to create/add the link?\r\n\r\nHere is an example [1] where the session information functions are referenced.\r\nThe public doc for this example is in [2].\r\n\r\nSomething similar can be done here. For example:\r\n\r\nThe session user's name; see the <function>session_user()</function> function in\r\n<xref linkend=\"functions-info-session-table\"/> for more details.\r\n\r\n\r\n[1] https://github.com/postgres/postgres/blob/master/doc/src/sgml/system-views.sgml#L1663-L1664\r\n[2] https://www.postgresql.org/docs/16/view-pg-locks.html\r\n\r\nRegards,\r\n\r\nSami\r\n\n\n\n\n\n\n\n\n\n\n\n> Here I considered your suggestion (Sami and Álvaro's). However, I haven't yet\n> added the links for the functions system_user(), current_user(), and session_user().\n> 'm not sure how to do it. Any suggestion on how to create/add the link?\n\n\nHere is an example [1] where the session information functions are referenced.\r\n\nThe public doc for this example is in [2].\n \nSomething similar can be done here. For example:\n \nThe session user's name; see the <function>session_user()</function> function in\r\n\n<xref linkend=\"functions-info-session-table\"/> for more details.\n \n \n[1] \r\nhttps://github.com/postgres/postgres/blob/master/doc/src/sgml/system-views.sgml#L1663-L1664\n[2] \r\nhttps://www.postgresql.org/docs/16/view-pg-locks.html\n \nRegards,\n\nSami",
"msg_date": "Mon, 1 Apr 2024 21:29:28 +0000",
"msg_from": "\"Imseih (AWS), Sami\" <simseih@amazon.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hello Sami,\n\n(v26)\n\n> Here is an example [1] where the session information functions are referenced.\n\n> The public doc for this example is in [2].\n\n\n> Something similar can be done here. For example:\n\n\n> The session user's name; see the <function>session_user()</function> function in\n\n> <xref linkend=\"functions-info-session-table\"/> for more details.\n\nI updated the patch.\n\nThank you for this help.\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Wed, 3 Apr 2024 10:01:08 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Building the docs fail for v26. The error is:\r\n\r\n\r\n\r\nref/psql-ref.sgml:1042: element member: validity error : Element term is not declared in member list of possible children\r\n\r\n </member>\r\n\r\n ^\r\n\r\n\r\n\r\nI am able to build up to v24 before the <para> was replaced with <listitem><member>\r\n\r\n\r\n\r\nI tested building with a modified structure as below; the <listitem> is a <para>\r\n\r\nthat has a <simplelist> within it. Each field is a simple list member and\r\n\r\nthe the name of the fields should be <literal>.\r\n\r\n\r\n\r\n <varlistentry id=\"app-psql-meta-command-conninfo\">\r\n\r\n <term><literal>\\conninfo[+]</literal></term>\r\n\r\n <listitem>\r\n\r\n <para>\r\n\r\n Outputs a string displaying information about the current\r\n\r\n database connection. When <literal>+</literal> is appended,\r\n\r\n more details about the connection are displayed in table\r\n\r\n format:\r\n\r\n <simplelist>\r\n\r\n <member><literal>Database:</literal>The database name of the connection.</member>\r\n\r\n <member><literal>Authenticated User:</literal>The authenticated database user of the connection.</member>\r\n\r\n <member><literal>Current User:</literal>The user name of the current execution context;\r\n\r\n see the <function>current_user()</function> function in\r\n\r\n <xref linkend=\"functions-info-session-table\"/> for more details.</member>\r\n\r\n </simplelist>\r\n\r\n </para>\r\n\r\n </listitem>\r\n\r\n </varlistentry>\r\n\r\n\r\n\r\nRegards,\r\n\r\n\r\n\r\nSami\r\n\n\n\n\n\n\n\n\n\n\nBuilding the docs fail for v26. The error is:\n \nref/psql-ref.sgml:1042: element member: validity error : Element term is not declared in member list of possible children\n \r\n</member>\n \r\n^\n \nI am able to build up to v24 before the <para> was replaced with <listitem><member>\r\n\n \nI tested building with a modified structure as below; the <listitem> is a <para>\r\n\nthat has a <simplelist> within it. Each field is a simple list member and\r\n\nthe the name of the fields should be <literal>.\n \n <varlistentry id=\"app-psql-meta-command-conninfo\">\n <term><literal>\\conninfo[+]</literal></term>\n <listitem>\n <para>\n Outputs a string displaying information about the current\n database connection. When <literal>+</literal> is appended,\n more details about the connection are displayed in table\n format:\n <simplelist>\n <member><literal>Database:</literal>The database name of the connection.</member>\n <member><literal>Authenticated User:</literal>The authenticated database user of the connection.</member>\n <member><literal>Current User:</literal>The user name of the current execution context;\n see the <function>current_user()</function> function in\n <xref linkend=\"functions-info-session-table\"/> for more details.</member>\n </simplelist>\n </para>\n </listitem>\n </varlistentry>\n \nRegards,\n \nSami",
"msg_date": "Wed, 3 Apr 2024 17:38:22 +0000",
"msg_from": "\"Imseih (AWS), Sami\" <simseih@amazon.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Building the docs fail for v26. The error is:\n\n\n\nref/psql-ref.sgml:1042: element member: validity error : Element term is not declared in member list of possible children\n\n </member>\n\n ^\n\n\n\nI am able to build up to v24 before the <para> was replaced with <listitem><member>\n\n\n\nI tested building with a modified structure as below; the <listitem> is a <para>\n\nthat has a <simplelist> within it. Each field is a simple list member and\n\nthe the name of the fields should be <literal>.\n\n\n\n <varlistentry id=\"app-psql-meta-command-conninfo\">\n\n <term><literal>\\conninfo[+]</literal></term>\n\n <listitem>\n\n <para>\n\n Outputs a string displaying information about the current\n\n database connection. When <literal>+</literal> is appended,\n\n more details about the connection are displayed in table\n\n format:\n\n <simplelist>\n\n <member><literal>Database:</literal>The database name of the connection.</member>\n\n <member><literal>Authenticated User:</literal>The authenticated database user of the connection.</member>\n\n <member><literal>Current User:</literal>The user name of the current execution context;\n\n see the <function>current_user()</function> function in\n\n <xref linkend=\"functions-info-session-table\"/> for more details.</member>\n\n </simplelist>\n\n </para>\n\n </listitem>\n\n </varlistentry>\n\n---//---\n\nHi Sami!\n(v27)\nI made the adjustment in the documentation.\nThank you for the time dedicated to this feature.\nRegards,\nMaiquel Grassi.",
"msg_date": "Thu, 4 Apr 2024 14:34:20 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi folks,\n\n(v28)\n\nI made a modification to a variable in the 'host' column in the archive 'describe.c'.\n\nTest:\n\n[postgres@localhost ~]$ /home/pgsql-17devel/bin/psql -x -p 5432\npsql (17devel, server 15.6)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5432\".\npostgres=# \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]----------------+---------\nDatabase | postgres\nAuthenticated User | postgres\nSocket Directory | /tmp\nHost |\nServer Port | 5432\nServer Address |\nClient Address |\nClient Port |\nBackend PID | 26728\nSystem User |\nCurrent User | postgres\nSession User | postgres\nApplication Name | psql\nSSL Connection | f\nSSL Protocol |\nSSL Cipher |\nSSL Compression |\nGSSAPI Authenticated | f\nGSSAPI Principal |\nGSSAPI Encrypted | f\nGSSAPI Credentials Delegated |\n\npostgres=# \\q\n[postgres@localhost ~]$ /home/pgsql-17devel/bin/psql -x -p 5000\npsql (17devel)\nType \"help\" for help.\n\npostgres=# \\conninfo\nYou are connected to database \"postgres\" as user \"postgres\" via socket in \"/tmp\" at port \"5000\".\npostgres=# \\conninfo+\nCurrent Connection Information\n-[ RECORD 1 ]----------------+---------\nDatabase | postgres\nAuthenticated User | postgres\nSocket Directory | /tmp\nHost |\nServer Port | 5000\nServer Address |\nClient Address |\nClient Port |\nBackend PID | 26730\nSystem User |\nCurrent User | postgres\nSession User | postgres\nApplication Name | psql\nSSL Connection | f\nSSL Protocol |\nSSL Cipher |\nSSL Compression |\nGSSAPI Authenticated | f\nGSSAPI Principal |\nGSSAPI Encrypted | f\nGSSAPI Credentials Delegated | f\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Thu, 4 Apr 2024 14:57:46 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "The existing \\conninfo command gets its values from libpq APIs. You are \nchanging all of this to make a server query, which is a totally \ndifferent thing. If we wanted to take a change like this, I don't think \nit should be reusing the \\conninfo command.\n\nBut I don't really see the point of this. The information you are \nquerying is already available in various system views. This proposal is \njust a shorthand for a collection of various random things some people \nlike to see. Like, by what reason is application name included as \nconnection info? Why not any other session settings? What about \nlong-term maintenance: By what logic should things be added to this?\n\n\n",
"msg_date": "Thu, 4 Apr 2024 17:19:53 +0200",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "The existing \\conninfo command gets its values from libpq APIs. You are\nchanging all of this to make a server query, which is a totally\ndifferent thing. If we wanted to take a change like this, I don't think\nit should be reusing the \\conninfo command.\n\nBut I don't really see the point of this. The information you are\nquerying is already available in various system views. This proposal is\njust a shorthand for a collection of various random things some people\nlike to see. Like, by what reason is application name included as\nconnection info? Why not any other session settings? What about\nlong-term maintenance: By what logic should things be added to this?\n\n--//--\n\nHello Peter, thank you for your participation.\nNo, \"they are not random things that random people like to see\", that's not true.\nHave you read the entire conversation from the beginning? We have already\ndiscussed it a bit and I have provided an explanation about the motivation to\nimplement this expansion of the \"\\conninfo\" command. The thing is, if you\nhave really been or worked as a DBA on a daily basis, taking care of many\ndatabases and PostgreSQL clusters, something like this additional command\nis the shortcut that every DBA needs. The application name was a suggestion\nfrom a member. If you think it's not necessary, we can remove it. Furthermore,\nif you believe that the patch is not well implemented, you, being a PostgreSQL guru,\ntell me how I can improve the current patch and we move towards v29. I'm not in\na hurry, I just want it to be implemented in the best possible shape.\n\nBest regards,\nMaiquel Grassi.\n\n\n\n\n\n\n\n\nThe existing \\conninfo command gets its values from libpq APIs. You are\nchanging all of this to make a server query, which is a totally\ndifferent thing. If we wanted to take a change like this, I don't think\nit should be reusing the \\conninfo command.\n\nBut I don't really see the point of this. The information you are\nquerying is already available in various system views. This proposal is\njust a shorthand for a collection of various random things some people\nlike to see. Like, by what reason is application name included as\nconnection info? Why not any other session settings? What about\nlong-term maintenance: By what logic should things be added to this?\n\n--//--\n\nHello Peter, thank you for your participation.\nNo, \"they are not random things that random people like to see\", that's not true.\nHave you read the entire conversation from the beginning? We have already\ndiscussed it a bit and I have provided an explanation about the motivation to\nimplement this expansion of the \"\\conninfo\" command. The thing is, if you\nhave really been or worked as a DBA on a daily basis, taking care of many\ndatabases and PostgreSQL clusters, something like this additional command\nis the shortcut that every DBA needs. The application name was a suggestion\nfrom a member. If you think it's not necessary, we can remove it. Furthermore,\nif you believe that the patch is not well implemented, you, being a PostgreSQL guru,\ntell me how I can improve the current patch and we move towards v29. I'm not in\na hurry, I just want it to be implemented in the best possible shape.\n\nBest regards,\nMaiquel Grassi.",
"msg_date": "Thu, 4 Apr 2024 15:42:29 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "On 2024-Apr-04, Peter Eisentraut wrote:\n\n> But I don't really see the point of this. The information you are querying\n> is already available in various system views. This proposal is just a\n> shorthand for a collection of various random things some people like to see.\n> Like, by what reason is application name included as connection info? Why\n> not any other session settings? What about long-term maintenance: By what\n> logic should things be added to this?\n\nUsability is precisely the point. You could also claim that we don't\nneed \\dconfig, since you could get the same thing by querying\npg_settings for non-default settings. But \\dconfig is very handy. I\nexpect \\conninfo+ to be equally useful. We don't give up command\nhistory just on the grounds that you can obtain the same effect by\nretyping the command.\n\n\nI'm not sure to what extent is it useful to make a distinction between\nthe values that the client knows from those that the server knows. If\nit is, then we can redefine \\conninfo+ to use the client values.\n\nThe point about application_name is a valid one. I guess it's there\nbecause it's commonly given from the client side rather than being set\nserver-side, even though it's still a GUC. Arguably we could remove it\nfrom \\conninfo+, and claim that nothing that shows up in \\dconfig should\nalso appear in \\conninfo+. Then users should get in the habit of using\nboth to obtain a full picture. This sounds to me a very good compromise\nactually.\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/\nTom: There seems to be something broken here.\nTeodor: I'm in sackcloth and ashes... Fixed.\n http://postgr.es/m/482D1632.8010507@sigaev.ru\n\n\n",
"msg_date": "Thu, 4 Apr 2024 17:53:37 +0200",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Maiquel Grassi <grassi@hotmail.com.br> writes:\n>> The existing \\conninfo command gets its values from libpq APIs. You are\n>> changing all of this to make a server query, which is a totally\n>> different thing. If we wanted to take a change like this, I don't think\n>> it should be reusing the \\conninfo command.\n\nFWIW, I agree with Peter's concern here, for a couple of reasons:\n\n* If \\conninfo involves a server query, then it will fail outright\nif the server is in an aborted transaction, or if there's something\nwrong with the connection --- which seems like one of the primary\ncases where you'd wish to use \\conninfo.\n\n* What if there's a discrepancy between what libpq thinks and what\nthe server thinks? (This is hardly unlikely for, say, host names.)\nIn the current situation you can use \\conninfo to investigate the\nclient-side parameters and then use a manual query to see what the\nserver thinks. If we replace \\conninfo with a server query then\nthere is no way at all to verify libpq parameters from the psql\ncommand line.\n\nSo I concur that \\conninfo should continue to report on libpq values\nand nothing else. We can certainly talk about expanding it within\nthat charter, if there's useful stuff it doesn't show now. But a\ncommand that retrieves settings from the server should be a distinct\nthing.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Thu, 04 Apr 2024 11:58:59 -0400",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": ">> The existing \\conninfo command gets its values from libpq APIs. You are\n>> changing all of this to make a server query, which is a totally\n>> different thing. If we wanted to take a change like this, I don't think\n>> it should be reusing the \\conninfo command.\n\nFWIW, I agree with Peter's concern here, for a couple of reasons:\n\n* If \\conninfo involves a server query, then it will fail outright\nif the server is in an aborted transaction, or if there's something\nwrong with the connection --- which seems like one of the primary\ncases where you'd wish to use \\conninfo.\n\n* What if there's a discrepancy between what libpq thinks and what\nthe server thinks? (This is hardly unlikely for, say, host names.)\nIn the current situation you can use \\conninfo to investigate the\nclient-side parameters and then use a manual query to see what the\nserver thinks. If we replace \\conninfo with a server query then\nthere is no way at all to verify libpq parameters from the psql\ncommand line.\n\nSo I concur that \\conninfo should continue to report on libpq values\nand nothing else. We can certainly talk about expanding it within\nthat charter, if there's useful stuff it doesn't show now. But a\ncommand that retrieves settings from the server should be a distinct\nthing.\n\n---//---\n\nWell, I can revert \\conninfo to its original state and keep \\conninfo+\nas it is, perhaps removing the application name, as I believe everything\nelse is important for a DBA/SysAdmin. Do you think we can proceed\nwith the patch this way? I am open to ideas that make \\conninfo not\nlimited to just four or five basic pieces of information and easily bring\neverything else to the screen.\n\nRegards,\nMaiquel Grassi.\n\n\n\n\n\n\n\n\n>> The existing \\conninfo command gets its values from libpq APIs. You are\n>> changing all of this to make a server query, which is a totally\n>> different thing. If we wanted to take a change like this, I don't think\n>> it should be reusing the \\conninfo command.\n\nFWIW, I agree with Peter's concern here, for a couple of reasons:\n\n* If \\conninfo involves a server query, then it will fail outright\nif the server is in an aborted transaction, or if there's something\nwrong with the connection --- which seems like one of the primary\ncases where you'd wish to use \\conninfo.\n\n* What if there's a discrepancy between what libpq thinks and what\nthe server thinks? (This is hardly unlikely for, say, host names.)\nIn the current situation you can use \\conninfo to investigate the\nclient-side parameters and then use a manual query to see what the\nserver thinks. If we replace \\conninfo with a server query then\nthere is no way at all to verify libpq parameters from the psql\ncommand line.\n\nSo I concur that \\conninfo should continue to report on libpq values\nand nothing else. We can certainly talk about expanding it within\nthat charter, if there's useful stuff it doesn't show now. But a\ncommand that retrieves settings from the server should be a distinct\nthing.\n\n---//---\n\nWell, I can revert \\conninfo to its original state and keep \\conninfo+\nas it is, perhaps removing the application name, as I believe everything\nelse is important for a DBA/SysAdmin. Do you think we can proceed\nwith the patch this way? I am open to ideas that make \\conninfo not\nlimited to just four or five basic pieces of information and easily bring\neverything else to the screen.\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Thu, 4 Apr 2024 16:15:39 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi!\n\n(v29)\n\nI left the command \\conninfo in its original form.\nI removed the 'Application Name' column from the \\conninfo+ command.\n\nThanks,\nMaiquel Grassi.",
"msg_date": "Thu, 4 Apr 2024 16:59:55 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "> The point about application_name is a valid one. I guess it's there\r\n> because it's commonly given from the client side rather than being set\r\n>server-side, even though it's still a GUC. Arguably we could remove it\r\n> from \\conninfo+, and claim that nothing that shows up in \\dconfig should\r\n> also appear in \\conninfo+. Then users should get in the habit of using\r\n> both to obtain a full picture. This sounds to me a very good compromise\r\n> actually.\r\n\r\nPerhaps another reason to remove \"application_name\" is because the\r\nvalue can be modified after the connection is established. If that is also\r\nanother good reason, the same can be said about \"Current User\"\r\nand \"Session User\" as those could be modified with SET commands.\r\n\r\nThis way conninfo could be only for attributes that will not change\r\nduring the lifetime of the connection.\r\n\r\n\r\nAlso, I just realized that pg_stat_ssl and pg_stat_gssapi will both return 0\r\nrows if there is a set role/set session authorization, this means \\conninfo+\r\nwill return empty.\r\n\r\npostgres=> select current_user;\r\n current_user \r\n--------------\r\n user1\r\n(1 row)\r\n\r\npostgres=> select * from pg_stat_ssl ;\r\n pid | ssl | version | cipher | bits | client_dn | client_serial | issuer_dn \r\n-------+-----+---------+-----------------------------+------+-----------+---------------+-----------\r\n 27223 | t | TLSv1.2 | ECDHE-RSA-AES256-GCM-SHA384 | 256 | | | \r\n(1 row)\r\n\r\npostgres=> set role = user2;\r\nSET\r\npostgres=> select * from pg_stat_ssl ;\r\n pid | ssl | version | cipher | bits | client_dn | client_serial | issuer_dn \r\n-----+-----+---------+--------+------+-----------+---------------+-----------\r\n(0 rows)\r\n\r\npostgres=> select current_user;\r\n current_user \r\n--------------\r\n user2\r\n(1 row)\r\n\r\npostgres=> reset role;\r\nRESET\r\npostgres=> select current_user;\r\n current_user \r\n--------------\r\n user1\r\n(1 row)\r\n\r\npostgres=> select * from pg_stat_ssl ;\r\n pid | ssl | version | cipher | bits | client_dn | client_serial | issuer_dn \r\n-------+-----+---------+-----------------------------+------+-----------+---------------+-----------\r\n 27223 | t | TLSv1.2 | ECDHE-RSA-AES256-GCM-SHA384 | 256 | | | \r\n(1 row)\r\n\r\n\r\nRegards, \r\n\r\nSami \r\n\r\n\r\n\r\n\r\n\r\n\r\n",
"msg_date": "Thu, 4 Apr 2024 19:20:41 +0000",
"msg_from": "\"Imseih (AWS), Sami\" <simseih@amazon.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "On 04.04.24 18:15, Maiquel Grassi wrote:\n> Well, I can revert \\conninfo to its original state and keep \\conninfo+\n> as it is, perhaps removing the application name, as I believe everything\n> else is important for a DBA/SysAdmin. Do you think we can proceed\n> with the patch this way? I am open to ideas that make \\conninfo not\n> limited to just four or five basic pieces of information and easily bring\n> everything else to the screen.\n\nThe original \\conninfo was designed to report values from the libpq API \nabout what libpq connected to. And the convention in psql is that \"+\" \nprovide more or less the same information but a bit more. So I think it \nis wrong to make \"\\conninfo+\" something fundamentally different than \n\"\\conninfo\".\n\nAnd even more so if it contains information that isn't really \n\"connection information\". For example, current_user() doesn't make \nsense here, I think.\n\nI mean, if you want to add a command \\some_useful_status_information, we \ncan talk about that, but let's leave \\conninfo to what it does.\n\nBut I think there are better ways to implement this kind of server-side \nstatus, for example, with a system view.\n\nOne problem in this patch is that it has no tests. Any change in any of \nthe involved functions or views will silently break this. (Note that \nplain \\conninfo doesn't have this problem to this extent because it only \nrelies on libpq function calls. Also, a system view would not have this \nproblem.)\n\n\n\n",
"msg_date": "Fri, 5 Apr 2024 16:50:18 +0200",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "> The original \\conninfo was designed to report values from the libpq API\r\n> about what libpq connected to. And the convention in psql is that \"+\"\r\n> provide more or less the same information but a bit more. So I think it\r\n> is wrong to make \"\\conninfo+\" something fundamentally different than\r\n> \"\\conninfo\".\r\n\r\nThat is a fair argument. Looking at this a bit more, it looks like we can\r\nenhance the GSSAPI output of conninfo to get the fields that GSSAPI fields that\r\nconninfo+ was aiming for\r\n\r\nRight now it just shows:\r\n\r\nprintf(_(\"GSSAPI-encrypted connection\\n\"));\r\n\r\nbut we can use libpq to get the other GSSAPI attributes in the output.\r\n\r\n> And even more so if it contains information that isn't really\r\n> \"connection information\". For example, current_user() doesn't make\r\n> sense here, I think.\r\n\r\n> I mean, if you want to add a command \\some_useful_status_information, we\r\n> can talk about that, but let's leave \\conninfo to what it does.\r\n\r\n> But I think there are better ways to implement this kind of server-side\r\n> status, for example, with a system view.\r\n\r\nWhat about a \\sessioninfo command that shows all the\r\ninformation for the current session, PID, app_name, current_user,\r\nsession_user, system_user, client_address, client_port, etc.\r\n\r\nThese will be the fields that we cannot gather if the connection is\r\nbroken for whatever reason.\r\n\r\nThe distinction here is \\sessioninfo are the details after the connection\r\nis established and could possibly be changed during the connection.\r\n\r\nRegards,\r\n\r\nSami\r\n\r\n\r\n",
"msg_date": "Fri, 5 Apr 2024 16:04:53 +0000",
"msg_from": "\"Imseih (AWS), Sami\" <simseih@amazon.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi,\n\nIs there someone willing to help me with this development and guide the patch so that it can be committed one day?\n\nRegards,\nMaiquel.\n\n\n\n\n\n\n\nHi,\n\nIs there someone willing to help me with this development and guide the patch so that it can be committed one day?\n\nRegards,\nMaiquel.",
"msg_date": "Wed, 29 May 2024 12:37:21 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "On Wed, May 29, 2024 at 12:37:21PM +0000, Maiquel Grassi wrote:\n> Is there someone willing to help me with this development and guide the\n> patch so that it can be committed one day?\n\n From a quick skim of the latest messages in this thread, it sounds like\nthere are a couple of folks who think \\conninfo (and consequently\n\\conninfo+) should only report values from the libpq API. I think they\nwould prefer server-side information to be provided via a system view or\nmaybe an entirely new psql meta-command.\n\nIIUC a new system view would more-or-less just gather information from\nother system views and functions. A view would be nice because it could be\nused outside psql, but I'm not sure to what extent we are comfortable\nadding system views built on other system views. Something like\n\\sessioninfo (as proposed by Sami) would look more similar to what you have\nin your latest patch, i.e., we'd teach psql about a complicated query for\ngathering all this disparate information.\n\nIMHO a good way to help move this forward is to try implementing it as a\nsystem view so that we can compare the two approaches. I've had luck in\nthe past with implementing something a couple different ways to help drive\nconsensus.\n\n-- \nnathan\n\n\n",
"msg_date": "Mon, 3 Jun 2024 13:30:21 -0500",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "From a quick skim of the latest messages in this thread, it sounds like\nthere are a couple of folks who think \\conninfo (and consequently\n\\conninfo+) should only report values from the libpq API. I think they\nwould prefer server-side information to be provided via a system view or\nmaybe an entirely new psql meta-command.\n\nIIUC a new system view would more-or-less just gather information from\nother system views and functions. A view would be nice because it could be\nused outside psql, but I'm not sure to what extent we are comfortable\nadding system views built on other system views. Something like\n\\sessioninfo (as proposed by Sami) would look more similar to what you have\nin your latest patch, i.e., we'd teach psql about a complicated query for\ngathering all this disparate information.\n\nIMHO a good way to help move this forward is to try implementing it as a\nsystem view so that we can compare the two approaches. I've had luck in\nthe past with implementing something a couple different ways to help drive\nconsensus.\n\n--//--\n\nGreat Nathan, we can follow that path of the view. I leave it open for anyone in the thread who has been following from the beginning to start the development of the view. Even you, if you have the interest and time to do it. At this exact moment, I am involved in a \"my baby born\" project, so I am unable to stop to look into this. If someone wants to start, I would appreciate it.\nRegards,\nMaiquel Grassi.\n\n\n\n\n\n\n\n\n From a quick skim of the latest messages in this thread, it sounds like\nthere are a couple of folks who think \\conninfo (and consequently\n\\conninfo+) should only report values from the libpq API. I think they\nwould prefer server-side information to be provided via a system view or\nmaybe an entirely new psql meta-command.\n\nIIUC a new system view would more-or-less just gather information from\nother system views and functions. A view would be nice because it could be\nused outside psql, but I'm not sure to what extent we are comfortable\nadding system views built on other system views. Something like\n\\sessioninfo (as proposed by Sami) would look more similar to what you have\nin your latest patch, i.e., we'd teach psql about a complicated query for\ngathering all this disparate information.\n\nIMHO a good way to help move this forward is to try implementing it as a\nsystem view so that we can compare the two approaches. I've had luck in\nthe past with implementing something a couple different ways to help drive\nconsensus.\n\n--//--\n\nGreat Nathan, we can follow that path of the view. I leave it open for anyone in the thread who has been following from the beginning to start the development of the view. Even you, if you have the interest and time to do it. At this exact moment, I am involved\n in a \"my baby born\" project, so I am unable to stop to look into this. If someone wants to start, I would appreciate it.\n\nRegards,\nMaiquel Grassi.",
"msg_date": "Wed, 5 Jun 2024 12:32:20 +0000",
"msg_from": "Maiquel Grassi <grassi@hotmail.com.br>",
"msg_from_op": true,
"msg_subject": "RE: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi,\n\nI have read the entire thread discussion. I understood the importance of\nthis enhancement related to /conninfo+ meta command. I really appreciate\nthe efforts of Maiquel and suggestions made by the reviewers. According to\nbest of my understanding, libpq API should be used instead of creating\nserver query for conninfo+ meta command. Building on the patch (v29)\nprovided by Maiquel, I made changes to retrieve some extra information\nrelated to connection from libpq API.\n\nExtra information includes:\n- Protocol Version\n- SSL Connection\n- GSSAPI Authenticated\n- Client Encoding\n- Server Encoding\n- Session User\n- Backend PID\n\nOutput of \\conninfo+:\n\n 1.\n\n $ bin/psql --port=5430 postgres -h localhost\n psql (18devel)\n Type \"help\" for help.\n\n postgres=# \\conninfo+\n You are connected to database \"postgres\" as user \"hunaid\" on host\n\"localhost\" (address \"127.0.0.1\") at port \"5430\".\n Protocol Version: 3\n SSL Connection: no\n GSSAPI Authenticated: no\n Client Encoding: UTF8\n Server Encoding: UTF8\n Session User: hunaid\n Backend PID: 163816\n\n\n\nI have also edited the documentation and added it to the patch. Please let\nme know if any changes are required.\n\nRegards,\nHunaid Sohail\n\nOn Wed, Jun 5, 2024 at 5:32 PM Maiquel Grassi <grassi@hotmail.com.br> wrote:\n\n> From a quick skim of the latest messages in this thread, it sounds like\n> there are a couple of folks who think \\conninfo (and consequently\n> \\conninfo+) should only report values from the libpq API. I think they\n> would prefer server-side information to be provided via a system view or\n> maybe an entirely new psql meta-command.\n>\n> IIUC a new system view would more-or-less just gather information from\n> other system views and functions. A view would be nice because it could be\n> used outside psql, but I'm not sure to what extent we are comfortable\n> adding system views built on other system views. Something like\n> \\sessioninfo (as proposed by Sami) would look more similar to what you have\n> in your latest patch, i.e., we'd teach psql about a complicated query for\n> gathering all this disparate information.\n>\n> IMHO a good way to help move this forward is to try implementing it as a\n> system view so that we can compare the two approaches. I've had luck in\n> the past with implementing something a couple different ways to help drive\n> consensus.\n>\n> --//--\n>\n> Great Nathan, we can follow that path of the view. I leave it open for\n> anyone in the thread who has been following from the beginning to start the\n> development of the view. Even you, if you have the interest and time to do\n> it. At this exact moment, I am involved in a \"my baby born\" project, so I\n> am unable to stop to look into this. If someone wants to start, I would\n> appreciate it.\n> Regards,\n> Maiquel Grassi.\n>",
"msg_date": "Fri, 2 Aug 2024 17:11:11 +0500",
"msg_from": "Hunaid Sohail <hunaidpgml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi Hunaid\n\nOn 02.08.24 14:11, Hunaid Sohail wrote:\n>\n> I have also edited the documentation and added it to the patch. Please\n> let me know if any changes are required.\n>\n\nI just wanted to review this patch again but v30 does not apply\n\n=== Applying patches on top of PostgreSQL commit ID d8df7ac5c04cd17bf13bd3123dcfcaf8007c6280 ===\n/etc/rc.d/jail: WARNING: Per-jail configuration via jail_* variables is obsolete. Please consider migrating to /etc/jail.conf.\n=== applying patch ./v30-0001-psql-meta-command-conninfo-plus.patch\npatch unexpectedly ends in middle of line\ngpatch: **** Only garbage was found in the patch input.\n\n\nI will set the status to \"Waiting on Author\".\n\n-- \nJim\n\n\n\n",
"msg_date": "Mon, 9 Sep 2024 15:22:46 +0200",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi,\n\nI have attached a rebased patch.\n\nRegards,\nHunaid Sohail\n\nOn Mon, Sep 9, 2024 at 6:22 PM Jim Jones <jim.jones@uni-muenster.de> wrote:\n\n> Hi Hunaid\n>\n> On 02.08.24 14:11, Hunaid Sohail wrote:\n> >\n> > I have also edited the documentation and added it to the patch. Please\n> > let me know if any changes are required.\n> >\n>\n> I just wanted to review this patch again but v30 does not apply\n>\n> === Applying patches on top of PostgreSQL commit ID\n> d8df7ac5c04cd17bf13bd3123dcfcaf8007c6280 ===\n> /etc/rc.d/jail: WARNING: Per-jail configuration via jail_* variables is\n> obsolete. Please consider migrating to /etc/jail.conf.\n> === applying patch ./v30-0001-psql-meta-command-conninfo-plus.patch\n> patch unexpectedly ends in middle of line\n> gpatch: **** Only garbage was found in the patch input.\n>\n>\n> I will set the status to \"Waiting on Author\".\n>\n> --\n> Jim\n>\n>",
"msg_date": "Tue, 10 Sep 2024 09:32:56 +0500",
"msg_from": "Hunaid Sohail <hunaidpgml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "\n\nOn 10.09.24 06:32, Hunaid Sohail wrote:\n>\n> I have attached a rebased patch.\n\nThanks.\n\nIs \\conninfo+ no longer supposed to return the results in tabular form?\nAt least it wasn't the case till v28.\n\n$ /usr/local/postgres-dev/bin/psql -d postgres -h 0 -c \"\\conninfo+\"\nYou are connected to database \"postgres\" as user \"jim\" on host \"0\"\n(address \"0.0.0.0\") at port \"5432\".\nProtocol Version: 3\nSSL Connection: no\nGSSAPI Authenticated: no\nClient Encoding: UTF8\nServer Encoding: UTF8\nSession User: jim\nBackend PID: 579041\n\n$ /usr/local/postgres-dev/bin/psql -d postgres -h 127.0.0.1 -c \"\\conninfo+\"\nYou are connected to database \"postgres\" as user \"jim\" on host\n\"127.0.0.1\" at port \"5432\".\nProtocol Version: 3\nSSL Connection: no\nGSSAPI Authenticated: no\nClient Encoding: UTF8\nServer Encoding: UTF8\nSession User: jim\nBackend PID: 579087\n\nSorry if I missed that in the thread.\n\nv31 has a couple of small indentation problems:\n\n/home/jim/patches/conninfo/v31-0001-Add-psql-meta-command-conninfo-plus.patch:87:\nindent with spaces.\n show_verbose = strchr(cmd, '+') ? true : false;\n/home/jim/patches/conninfo/v31-0001-Add-psql-meta-command-conninfo-plus.patch:106:\ntrailing whitespace.\n\nChecking patch doc/src/sgml/ref/psql-ref.sgml...\nChecking patch src/bin/psql/command.c...\nChecking patch src/bin/psql/help.c...\nApplied patch doc/src/sgml/ref/psql-ref.sgml cleanly.\nApplied patch src/bin/psql/command.c cleanly.\nApplied patch src/bin/psql/help.c cleanly.\nwarning: 2 lines add whitespace errors.\n\n\n-- \nJim\n\n\n\n",
"msg_date": "Tue, 10 Sep 2024 18:00:51 +0200",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "On 2024-Sep-10, Jim Jones wrote:\n\n> Is \\conninfo+ no longer supposed to return the results in tabular form?\n> At least it wasn't the case till v28.\n\nI suspect the reason it's no longer a table is that it was previously a\nquery (which is easily printed as a table by calling printQuery) and now\nit's just a client-side thing, and Hunaid didn't know how to handle that\nas a table. The good news is, it should be really easy to do\nprintTableInit(), then a bunch of printTableAddHeader() and\nprintTableAddCell(), end with printTable(). I think the tabular format\nis better for sure.\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — 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": "Tue, 10 Sep 2024 18:16:54 +0200",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi,\n\nOn Tue, Sep 10, 2024 at 9:16 PM Alvaro Herrera <alvherre@alvh.no-ip.org>\nwrote:\n\n> On 2024-Sep-10, Jim Jones wrote:\n>\n> > Is \\conninfo+ no longer supposed to return the results in tabular form?\n> > At least it wasn't the case till v28.\n>\n> I suspect the reason it's no longer a table is that it was previously a\n> query (which is easily printed as a table by calling printQuery) and now\n> it's just a client-side thing, and Hunaid didn't know how to handle that\n> as a table. The good news is, it should be really easy to do\n> printTableInit(), then a bunch of printTableAddHeader() and\n> printTableAddCell(), end with printTable(). I think the tabular format\n> is better for sure.\n>\n\nI have made the requested changes. Now output is returned in tabular form.\nIndentation/whitespace issues are fixed.\n\n$bin/psql --port=5430 postgres\npostgres=# \\conninfo+\nYou are connected to database \"postgres\" as user \"hunaid\" via socket in\n\"/tmp\" at port \"5430\".\n Connection Information\n Parameter | Value\n----------------------+--------\n Protocol Version | 3\n SSL Connection | no\n GSSAPI Authenticated | no\n Client Encoding | UTF8\n Server Encoding | UTF8\n Session User | hunaid\n Backend PID | 121800\n(7 rows)\n\nRegards,\nHunaid Sohail",
"msg_date": "Wed, 11 Sep 2024 13:16:21 +0500",
"msg_from": "Hunaid Sohail <hunaidpgml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "\nOn 11.09.24 10:16, Hunaid Sohail wrote:\n> I have made the requested changes. Now output is returned in tabular \n> form. Indentation/whitespace issues are fixed.\n>\n> $bin/psql --port=5430 postgres\n> postgres=# \\conninfo+\n> You are connected to database \"postgres\" as user \"hunaid\" via socket \n> in \"/tmp\" at port \"5430\".\n> Connection Information\n> Parameter | Value\n> ----------------------+--------\n> Protocol Version | 3\n> SSL Connection | no\n> GSSAPI Authenticated | no\n> Client Encoding | UTF8\n> Server Encoding | UTF8\n> Session User | hunaid\n> Backend PID | 121800\n> (7 rows)\n\nThanks for working on this.\n\nAny particular reason for the design change? In v28 it returned a table \nwith a single row and multiple columns --- one column per attribute. But \nnow it returns multiple rows. In this case, I was expecting 1 row with 7 \ncolumns instead of 7 rows with 2 columns.\n\nJim\n\n\n\n",
"msg_date": "Wed, 11 Sep 2024 12:03:05 +0200",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi Jim,\n\nOn Wed, Sep 11, 2024 at 3:03 PM Jim Jones <jim.jones@uni-muenster.de> wrote:\n\n> Thanks for working on this.\n>\n> Any particular reason for the design change? In v28 it returned a table\n> with a single row and multiple columns --- one column per attribute. But\n> now it returns multiple rows. In this case, I was expecting 1 row with 7\n> columns instead of 7 rows with 2 columns.\n>\n\nI am not sure which design you are referring to.\nI haven't applied the v28 patch but the original author in thread [1]\nprovided sample output. The output is in tabular form with 2 columns and\nmultiple rows.\n\n[1]\nhttps://www.postgresql.org/message-id/CP8P284MB249615AED23882E1E185C8ABEC3C2%40CP8P284MB2496.BRAP284.PROD.OUTLOOK.COM\n\n\nRegards,\nHunaid Sohail\n\nHi Jim,On Wed, Sep 11, 2024 at 3:03 PM Jim Jones <jim.jones@uni-muenster.de> wrote:\nThanks for working on this.\n\nAny particular reason for the design change? In v28 it returned a table \nwith a single row and multiple columns --- one column per attribute. But \nnow it returns multiple rows. In this case, I was expecting 1 row with 7 \ncolumns instead of 7 rows with 2 columns.I am not sure which design you are referring to.I haven't applied the v28 patch but the original author in thread [1] provided sample output. The output is in tabular form with 2 columns and multiple rows.[1] https://www.postgresql.org/message-id/CP8P284MB249615AED23882E1E185C8ABEC3C2%40CP8P284MB2496.BRAP284.PROD.OUTLOOK.COM Regards,Hunaid Sohail",
"msg_date": "Wed, 11 Sep 2024 16:35:20 +0500",
"msg_from": "Hunaid Sohail <hunaidpgml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "\n\nOn 11.09.24 13:35, Hunaid Sohail wrote:\n> Hi Jim,\n>\n> On Wed, Sep 11, 2024 at 3:03 PM Jim Jones <jim.jones@uni-muenster.de>\n> wrote:\n>\n> Thanks for working on this.\n>\n> Any particular reason for the design change? In v28 it returned a\n> table\n> with a single row and multiple columns --- one column per\n> attribute. But\n> now it returns multiple rows. In this case, I was expecting 1 row\n> with 7\n> columns instead of 7 rows with 2 columns.\n>\n>\n> I am not sure which design you are referring to.\n> I haven't applied the v28 patch but the original author in thread [1]\n> provided sample output. The output is in tabular form with 2 columns\n> and multiple rows.\n>\n> [1] https://www.postgresql.org/message-id/CP8P284MB249615AED23882E1E185C8ABEC3C2%40CP8P284MB2496.BRAP284.PROD.OUTLOOK.COM \n>\nIt may look like this, but it is a single record --- mind the header \"-[\nRECORD 1 ]----------------+---------\".\npsql was called in expanded mode:\n\n> $ /home/pgsql-17devel/bin/psql -x -p 5432\n\n\"-x\" or \"--expanded\"\n\nExample:\n\n$ psql postgres -xc \"SELECT 'foo' col1, 'bar' col2\"\n-[ RECORD 1 ]\ncol1 | foo\ncol2 | bar\n\n-- \nJim\n\n\n\n",
"msg_date": "Thu, 12 Sep 2024 13:08:01 +0200",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi,\n\nOn Thu, Sep 12, 2024 at 4:08 PM Jim Jones <jim.jones@uni-muenster.de> wrote:\n\n> It may look like this, but it is a single record --- mind the header \"-[\n> RECORD 1 ]----------------+---------\".\n> psql was called in expanded mode:\n>\n> > $ /home/pgsql-17devel/bin/psql -x -p 5432\n>\n> \"-x\" or \"--expanded\"\n>\n> Example:\n>\n> $ psql postgres -xc \"SELECT 'foo' col1, 'bar' col2\"\n> -[ RECORD 1 ]\n> col1 | foo\n> col2 | bar\n>\n\nI guess I missed the expanded mode. I have attached a new patch. Please\ncheck the output now.\n\n```\n$ bin/psql --port=5430 postgres\npsql (18devel)\nType \"help\" for help.\n\npostgres=# \\conninfo+\nYou are connected to database \"postgres\" as user \"hunaid\" via socket in\n\"/tmp\" at port \"5430\".\n Connection Information\n Protocol Version | SSL Connection | GSSAPI Authenticated | Client Encoding\n| Server Encoding | Session User | Backend P\nID\n------------------+----------------+----------------------+-----------------+-----------------+--------------+----------\n---\n 3 | no | no | UTF8\n | UTF8 | hunaid | 55598\n(1 row)\n\npostgres=# \\x\nExpanded display is on.\npostgres=# \\conninfo+\nYou are connected to database \"postgres\" as user \"hunaid\" via socket in\n\"/tmp\" at port \"5430\".\nConnection Information\n-[ RECORD 1 ]--------+-------\nProtocol Version | 3\nSSL Connection | no\nGSSAPI Authenticated | no\nClient Encoding | UTF8\nServer Encoding | UTF8\nSession User | hunaid\nBackend PID | 55598\n```\n\nRegards,\nHunaid Sohail",
"msg_date": "Fri, 13 Sep 2024 09:49:55 +0500",
"msg_from": "Hunaid Sohail <hunaidpgml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "\n\nOn 13.09.24 06:49, Hunaid Sohail wrote:\n>\n> $ bin/psql --port=5430 postgres\n> psql (18devel)\n> Type \"help\" for help.\n>\n> postgres=# \\conninfo+\n> You are connected to database \"postgres\" as user \"hunaid\" via socket\n> in \"/tmp\" at port \"5430\".\n> Connection Information\n> Protocol Version | SSL Connection | GSSAPI Authenticated | Client\n> Encoding | Server Encoding | Session User | Backend P\n> ID\n> ------------------+----------------+----------------------+-----------------+-----------------+--------------+----------\n> ---\n> 3 | no | no | UTF8 \n> | UTF8 | hunaid | 55598\n> (1 row)\n\nNice.\n\nI just noticed that messages' order has been slightly changed. The\nmessage \"You are connected to database \"postgres\" as user \"hunaid\" via\nsocket in \"/tmp\" at port \"5430\" used to be printed after the table, and\nnow it is printed before.\n\n$ /usr/local/postgres-dev/bin/psql -x \"\\\n hostaddr=0\n user=jim dbname=postgres\n port=54322\" -c \"\\conninfo+\"\n\nYou are connected to database \"postgres\" as user \"jim\" on host \"0\"\n(address \"0.0.0.0\") at port \"54322\".\nConnection Information\n-[ RECORD 1 ]--------+--------\nProtocol Version | 3\nSSL Connection | no\nGSSAPI Authenticated | no\nClient Encoding | UTF8\nServer Encoding | UTF8\nSession User | jim\nBackend PID | 2419033\n\nIt is IMHO a little strange because the \"SSL connection\" info keeps\nbeing printed in the end. I would personally prefer if they're printed\ntogether --- preferably after the table. But I'm not sure if there's any\nconvention for that.\n\n$ /usr/local/postgres-dev/bin/psql -x \"\\\n host=server.uni-muenster.de\n hostaddr=127.0.0.1\n user=jim dbname=postgres\n port=54322\n sslmode=verify-full\n sslrootcert=server-certificates/server.crt\n sslcert=jim-certificates/jim.crt\n sslkey=jim-certificates/jim.key\" -c \"\\conninfo+\"\n\nYou are connected to database \"postgres\" as user \"jim\" on host\n\"server.uni-muenster.de\" (address \"127.0.0.1\") at port \"54322\".\nConnection Information\n-[ RECORD 1 ]--------+--------\nProtocol Version | 3\nSSL Connection | yes\nGSSAPI Authenticated | no\nClient Encoding | UTF8\nServer Encoding | UTF8\nSession User | jim\nBackend PID | 2421556\n\nSSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\ncompression: off, ALPN: postgresql)\n\nAlso, there are a few compilation warnings regarding const qualifiers:\n\ncommand.c:810:49: warning: assignment discards ‘const’ qualifier from\npointer target type [-Wdiscarded-qualifiers]\n 810 | client_encoding =\nPQparameterStatus(pset.db, \"client_encoding\");\n | ^\ncommand.c:811:49: warning: assignment discards ‘const’ qualifier from\npointer target type [-Wdiscarded-qualifiers]\n 811 | server_encoding =\nPQparameterStatus(pset.db, \"server_encoding\");\n | ^\ncommand.c:812:46: warning: assignment discards ‘const’ qualifier from\npointer target type [-Wdiscarded-qualifiers]\n 812 | session_user =\nPQparameterStatus(pset.db, \"session_authorization\");\n\n\n-- \nJim\n\n\n\n",
"msg_date": "Fri, 13 Sep 2024 13:27:33 +0200",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi Jim,\n\nOn Fri, Sep 13, 2024 at 4:27 PM Jim Jones <jim.jones@uni-muenster.de> wrote:\n\n> I just noticed that messages' order has been slightly changed. The\n> message \"You are connected to database \"postgres\" as user \"hunaid\" via\n> socket in \"/tmp\" at port \"5430\" used to be printed after the table, and\n> now it is printed before.\n>\n> $ /usr/local/postgres-dev/bin/psql -x \"\\\n> hostaddr=0\n> user=jim dbname=postgres\n> port=54322\" -c \"\\conninfo+\"\n>\n> You are connected to database \"postgres\" as user \"jim\" on host \"0\"\n> (address \"0.0.0.0\") at port \"54322\".\n> Connection Information\n> -[ RECORD 1 ]--------+--------\n> Protocol Version | 3\n> SSL Connection | no\n> GSSAPI Authenticated | no\n> Client Encoding | UTF8\n> Server Encoding | UTF8\n> Session User | jim\n> Backend PID | 2419033\n>\n> It is IMHO a little strange because the \"SSL connection\" info keeps\n> being printed in the end. I would personally prefer if they're printed\n> together --- preferably after the table. But I'm not sure if there's any\n> convention for that.\n>\n\nI agree that both messages should be printed together. IMO the message\n\"You are connected to database...\" should be printed at the top, no?\nBecause it shows important info that the user may be interested to see\nfirst. Then we can combine the ssl message.\n\npostgres=# \\x\nExpanded display is on.\npostgres=# \\conninfo+\nYou are connected to database \"postgres\" as user \"hunaid\" on host\n\"localhost\" (address \"127.0.0.1\") at port \"5430\".\nSSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\ncompression: off, ALPN: postgresql)\nConnection Information\n-[ RECORD 1 ]--------+-------\nProtocol Version | 3\nSSL Connection | yes\nGSSAPI Authenticated | no\nClient Encoding | UTF8\nServer Encoding | UTF8\nSession User | hunaid\nBackend PID | 109092\n\n\n\n> Also, there are a few compilation warnings regarding const qualifiers:\n>\n\nNoted. I will fix them in the next patch.\n\nRegards,\nHunaid Sohail\n\nHi Jim,On Fri, Sep 13, 2024 at 4:27 PM Jim Jones <jim.jones@uni-muenster.de> wrote:I just noticed that messages' order has been slightly changed. The\nmessage \"You are connected to database \"postgres\" as user \"hunaid\" via\nsocket in \"/tmp\" at port \"5430\" used to be printed after the table, and\nnow it is printed before.\n\n$ /usr/local/postgres-dev/bin/psql -x \"\\\n hostaddr=0\n user=jim dbname=postgres\n port=54322\" -c \"\\conninfo+\"\n\nYou are connected to database \"postgres\" as user \"jim\" on host \"0\"\n(address \"0.0.0.0\") at port \"54322\".\nConnection Information\n-[ RECORD 1 ]--------+--------\nProtocol Version | 3\nSSL Connection | no\nGSSAPI Authenticated | no\nClient Encoding | UTF8\nServer Encoding | UTF8\nSession User | jim\nBackend PID | 2419033\n\nIt is IMHO a little strange because the \"SSL connection\" info keeps\nbeing printed in the end. I would personally prefer if they're printed\ntogether --- preferably after the table. But I'm not sure if there's any\nconvention for that.I agree that both messages should be printed together. IMO the message\"You are connected to database...\" should be printed at the top, no? Because it shows important info that the user may be interested to see first. Then we can combine the ssl message.postgres=# \\xExpanded display is on.postgres=# \\conninfo+You are connected to database \"postgres\" as user \"hunaid\" on host \"localhost\" (address \"127.0.0.1\") at port \"5430\".SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off, ALPN: postgresql)Connection Information-[ RECORD 1 ]--------+-------Protocol Version | 3SSL Connection | yesGSSAPI Authenticated | noClient Encoding | UTF8Server Encoding | UTF8Session User | hunaidBackend PID | 109092 \nAlso, there are a few compilation warnings regarding const qualifiers:Noted. I will fix them in the next patch.Regards,Hunaid Sohail",
"msg_date": "Sat, 14 Sep 2024 17:28:39 +0500",
"msg_from": "Hunaid Sohail <hunaidpgml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "On 2024-Sep-14, Hunaid Sohail wrote:\n\n> I agree that both messages should be printed together. IMO the message\n> \"You are connected to database...\" should be printed at the top, no?\n> Because it shows important info that the user may be interested to see\n> first. Then we can combine the ssl message.\n> \n> postgres=# \\x\n> Expanded display is on.\n> postgres=# \\conninfo+\n> You are connected to database \"postgres\" as user \"hunaid\" on host\n> \"localhost\" (address \"127.0.0.1\") at port \"5430\".\n> SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\n> compression: off, ALPN: postgresql)\n> Connection Information\n> -[ RECORD 1 ]--------+-------\n> Protocol Version | 3\n> SSL Connection | yes\n> GSSAPI Authenticated | no\n> Client Encoding | UTF8\n> Server Encoding | UTF8\n> Session User | hunaid\n> Backend PID | 109092\n\nI don't understand why this is is printing half the information in\nfree-form plain text and the other half in tabular format. All these\nitems that you have in the free-form text lines should be part of the\ntable, I think.\n\n-- \nÁlvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/\n#error \"Operator lives in the wrong universe\"\n (\"Use of cookies in real-time system development\", M. Gleixner, M. Mc Guire)\n\n\n",
"msg_date": "Sat, 14 Sep 2024 19:37:11 +0200",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> I don't understand why this is is printing half the information in\n> free-form plain text and the other half in tabular format. All these\n> items that you have in the free-form text lines should be part of the\n> table, I think.\n\n+1, that was my reaction as well. I can see the point of showing\nthose items the same way as plain \\conninfo does, but I think\nwe're better off just making \\conninfo+ produce a table and nothing\nelse.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Sat, 14 Sep 2024 13:50:00 -0400",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi,\n\nOn Sat, Sep 14, 2024 at 10:50 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> > I don't understand why this is is printing half the information in\n> > free-form plain text and the other half in tabular format. All these\n> > items that you have in the free-form text lines should be part of the\n> > table, I think.\n>\n> +1, that was my reaction as well. I can see the point of showing\n> those items the same way as plain \\conninfo does, but I think\n> we're better off just making \\conninfo+ produce a table and nothing\n> else.\n>\n\nI have attached a new patch that now prints all info in tabular format for\n\\conninfo+. I have also made the table output dynamic, so if the connection\nuses SSL, the columns in the table will expand accordingly.\n\n```\n$ bin/psql \"port=5430 sslmode=require dbname=postgres\" -x -h localhost\n\npostgres=# \\conninfo+\nConnection Information\n-[ RECORD 1 ]--------+-----------------------\nDatabase | postgres\nCurrent User | hunaid\nSession User | hunaid\nHost | localhost\nHost Address | 127.0.0.1\nPort | 5430\nProtocol Version | 3\nSSL Connection | yes\nSSL Protocol | TLSv1.3\nCipher | TLS_AES_256_GCM_SHA384\nCompression | off\nALPN | postgresql\nGSSAPI Authenticated | no\nClient Encoding | UTF8\nServer Encoding | UTF8\nBackend PID | 88803\n\n\n$ bin/psql \"port=5430 sslmode=disable dbname=postgres\" -x -h localhost\n\npostgres=# \\conninfo+\nConnection Information\n-[ RECORD 1 ]--------+----------\nDatabase | postgres\nCurrent User | hunaid\nSession User | hunaid\nHost | localhost\nHost Address | 127.0.0.1\nPort | 5430\nProtocol Version | 3\nSSL Connection | no\nGSSAPI Authenticated | no\nClient Encoding | UTF8\nServer Encoding | UTF8\nBackend PID | 88900\n\n\n$ bin/psql \"port=5430 sslmode=disable dbname=postgres\" -x\n\npostgres=# \\conninfo+\nConnection Information\n-[ RECORD 1 ]--------+---------\nDatabase | postgres\nCurrent User | hunaid\nSession User | hunaid\nSocket Directory | /tmp\nPort | 5430\nProtocol Version | 3\nSSL Connection | no\nGSSAPI Authenticated | no\nClient Encoding | UTF8\nServer Encoding | UTF8\nBackend PID | 89035\n```\n\nI have also updated the documentation.\n\nRegards,\nHunaid Sohail",
"msg_date": "Mon, 16 Sep 2024 11:51:04 +0500",
"msg_from": "Hunaid Sohail <hunaidpgml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "\n\nOn 16.09.24 08:51, Hunaid Sohail wrote:\n> I have attached a new patch that now prints all info in tabular format\n> for \\conninfo+. I have also made the table output dynamic, so if the\n> connection uses SSL, the columns in the table will expand accordingly.\n>\nIt looks much cleaner now.\n> I have also updated the documentation.\n\nThe CF bot is still giving some warnings:\n\ncommand.c:886:79: error: ‘alpn’ may be used uninitialized\n[-Werror=maybe-uninitialized]\n 886 | printTableAddCell(&cont,\n(alpn && alpn[0] != '\\0') ? alpn : _(\"none\"), false, false);\n \n| \n~~~~^~~\ncommand.c:803:50: note: ‘alpn’ was declared here\n 803 | *alpn;\n | ^~~~\ncommand.c:885:82: error: ‘compression’ may be used uninitialized\n[-Werror=maybe-uninitialized]\n 885 | printTableAddCell(&cont,\n(compression && strcmp(compression, \"off\") != 0) ? _(\"on\") : _(\"off\"),\nfalse, false);\n \n| \n^~~~~~~~~~~~~~~~~~~~~~~~~~\ncommand.c:802:50: note: ‘compression’ was declared here\n 802 | *compression,\n | ^~~~~~~~~~~\ncommand.c:884:41: error: ‘cipher’ may be used uninitialized\n[-Werror=maybe-uninitialized]\n 884 | printTableAddCell(&cont,\ncipher ? cipher : _(\"unknown\"), false, false);\n | \n^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ncommand.c:801:50: note: ‘cipher’ was declared here\n 801 | *cipher,\n | ^~~~~~\ncommand.c:883:41: error: ‘protocol’ may be used uninitialized\n[-Werror=maybe-uninitialized]\n 883 | printTableAddCell(&cont,\nprotocol ? protocol : _(\"unknown\"), false, false);\n | \n^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ncommand.c:800:42: note: ‘protocol’ was declared here\n 800 | char *protocol,\n | ^~~~~~~~\n\nI have a few questions regarding this example:\n\n$ /usr/local/postgres-dev/bin/psql -x \"\\\n host=server.uni-muenster.de\n hostaddr=192.168.178.27\n user=jim dbname=db port=5432\n sslmode=verify-full\n sslrootcert=server-certificates/server.crt\n sslcert=jim-certificates/jim.crt\n sslkey=jim-certificates/jim.key\"\n\npsql (18devel)\nSSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\ncompression: off, ALPN: postgresql)\nType \"help\" for help.\n\ndb=# SET ROLE foo;\nSET\n\ndb=> SELECT current_user, session_user;\n-[ RECORD 1 ]+----\ncurrent_user | foo\nsession_user | jim\n\ndb=> \\conninfo+\nConnection Information\n-[ RECORD 1 ]--------+-----------------------\nDatabase | db\nCurrent User | jim\nSession User | jim\nHost | server.uni-muenster.de\nHost Address | 192.168.178.27\nPort | 5432\nProtocol Version | 3\nSSL Connection | yes\nSSL Protocol | TLSv1.3\nCipher | TLS_AES_256_GCM_SHA384\nCompression | off\nALPN | postgresql\nGSSAPI Authenticated | no\nClient Encoding | UTF8\nServer Encoding | UTF8\nBackend PID | 315187\n\n\n* The value of \"Current User\" does not match the function current_user()\n--- as one might expcect. It is a little confusing, as there is no\nmention of \"Current User\" in the docs. In case this is the intended\nbehaviour, could you please add it to the docs?\n\n* \"SSL Connection\" says \"yes\", but the docs say: \"True if the current\nconnection to the server uses SSL, and false otherwise.\". Is it supposed\nto be like this? I haven't checked other similar doc entries..\n\n\n--\nJim\n\n\n",
"msg_date": "Mon, 16 Sep 2024 15:40:07 +0200",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "On 2024-Sep-16, Jim Jones wrote:\n\n> * The value of \"Current User\" does not match the function current_user()\n> --- as one might expcect. It is a little confusing, as there is no\n> mention of \"Current User\" in the docs. In case this is the intended\n> behaviour, could you please add it to the docs?\n\nIt is intended. As Peter said[1], what we wanted was to display\nclient-side info, so PQuser() is the right thing to do. Now maybe\n\"Current User\" is not the perfect column header, but at least the\ndefinition seems consistent with the desired end result. Now, I think\nthe current docs saying to look at session_user() are wrong, they should\npoint to the libpq docs for the function instead; something like \"The\nname of the current user, as returned by PQuser()\" and so on.\nOtherwise, in the cases where these things differ, it is going to be\nhard to explain.\n\n[1] https://postgr.es/m/f4fc729d-7903-4d58-995d-6cd146049992@eisentraut.org\n\n> * \"SSL Connection\" says \"yes\", but the docs say: \"True if the current\n> connection to the server uses SSL, and false otherwise.\". Is it supposed\n> to be like this? I haven't checked other similar doc entries..\n\nYeah, I think we should print what a boolean value would look like from\nSQL, so \"true\" rather than \"yes\".\n\n\nI think the code structure is hard to follow. It would be simpler if it\nwas a bunch of\n\n/* Database */\nprintTableAddHeader(&cont, _(\"Database\"), true, 'l');\nprintTableAddCell(&cont, db, false, false);\n...\n/* Port */\nprintTableAddHeader(&cont, _(\"Por\"), true, 'l');\nprintTableAddCell(&cont, PQport(pset.db), false, false);\n/* ... */\n\nAnd so on. I don't think the printTable() API forces you to set all\nheaders first followed by all cells.\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/\n\n\n",
"msg_date": "Mon, 16 Sep 2024 16:22:03 +0200",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> On 2024-Sep-16, Jim Jones wrote:\n>> * The value of \"Current User\" does not match the function current_user()\n>> --- as one might expcect. It is a little confusing, as there is no\n>> mention of \"Current User\" in the docs. In case this is the intended\n>> behaviour, could you please add it to the docs?\n\n> It is intended. As Peter said[1], what we wanted was to display\n> client-side info, so PQuser() is the right thing to do. Now maybe\n> \"Current User\" is not the perfect column header, but at least the\n> definition seems consistent with the desired end result.\n\nSeems like \"Session User\" would be closer to being accurate, since\nPQuser()'s result does not change when you do SET ROLE etc.\n\n> Now, I think\n> the current docs saying to look at session_user() are wrong, they should\n> point to the libpq docs for the function instead; something like \"The\n> name of the current user, as returned by PQuser()\" and so on.\n\nSure, but this does not excuse choosing a misleading column name\nwhen there are better choices readily available.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Mon, 16 Sep 2024 11:30:58 -0400",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi,\n\nOn Mon, Sep 16, 2024 at 8:31 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> > On 2024-Sep-16, Jim Jones wrote:\n> >> * The value of \"Current User\" does not match the function current_user()\n> >> --- as one might expcect. It is a little confusing, as there is no\n> >> mention of \"Current User\" in the docs. In case this is the intended\n> >> behaviour, could you please add it to the docs?\n>\n> > It is intended. As Peter said[1], what we wanted was to display\n> > client-side info, so PQuser() is the right thing to do. Now maybe\n> > \"Current User\" is not the perfect column header, but at least the\n> > definition seems consistent with the desired end result.\n>\n> Seems like \"Session User\" would be closer to being accurate, since\n> PQuser()'s result does not change when you do SET ROLE etc.\n>\n> > Now, I think\n> > the current docs saying to look at session_user() are wrong, they should\n> > point to the libpq docs for the function instead; something like \"The\n> > name of the current user, as returned by PQuser()\" and so on.\n>\n> Sure, but this does not excuse choosing a misleading column name\n> when there are better choices readily available.\n>\n\nMaybe we can rename \"Current User\" to \"Authenticated User\" just like the\nprevious author because it is a user returned by PQuser().\n\nFor the \"Session User\", I believe it is working as expected, since\nsession_user can be changed with SET SESSION AUTHORIZATION.\n\n```\n$ bin/psql \"port=5430 sslmode=disable dbname=postgres\" -x -h localhost\n\npostgres=# \\conninfo+\nConnection Information\n-[ RECORD 1 ]--------+----------\nDatabase | postgres\nCurrent User | hunaid\nSession User | hunaid\nHost | localhost\nHost Address | 127.0.0.1\nPort | 5430\nProtocol Version | 3\nSSL Connection | false\nGSSAPI Authenticated | false\nClient Encoding | UTF8\nServer Encoding | UTF8\nBackend PID | 1337\n\npostgres=# set SESSION AUTHORIZATION postgres;\nSET\npostgres=# \\conninfo+\nConnection Information\n-[ RECORD 1 ]--------+----------\nDatabase | postgres\nCurrent User | hunaid\nSession User | postgres\nHost | localhost\nHost Address | 127.0.0.1\nPort | 5430\nProtocol Version | 3\nSSL Connection | false\nGSSAPI Authenticated | false\nClient Encoding | UTF8\nServer Encoding | UTF8\nBackend PID | 1337\n```\n\nWe can update the docs as follows:\nAuthenticated User: The name of the user returned by PQuser().\nSession User: The session user's name.\n\nOpinions?\n\nRegards,\nHunaid Sohail\n\nHi,On Mon, Sep 16, 2024 at 8:31 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:Alvaro Herrera <alvherre@alvh.no-ip.org> writes:\n> On 2024-Sep-16, Jim Jones wrote:\n>> * The value of \"Current User\" does not match the function current_user()\n>> --- as one might expcect. It is a little confusing, as there is no\n>> mention of \"Current User\" in the docs. In case this is the intended\n>> behaviour, could you please add it to the docs?\n\n> It is intended. As Peter said[1], what we wanted was to display\n> client-side info, so PQuser() is the right thing to do. Now maybe\n> \"Current User\" is not the perfect column header, but at least the\n> definition seems consistent with the desired end result.\n\nSeems like \"Session User\" would be closer to being accurate, since\nPQuser()'s result does not change when you do SET ROLE etc.\n\n> Now, I think\n> the current docs saying to look at session_user() are wrong, they should\n> point to the libpq docs for the function instead; something like \"The\n> name of the current user, as returned by PQuser()\" and so on.\n\nSure, but this does not excuse choosing a misleading column name\nwhen there are better choices readily available.Maybe we can rename \"Current User\" to \"Authenticated User\" just like the previous author because it is a user returned by PQuser().For the \"Session User\", I believe it is working as expected, since session_user can be changed with SET SESSION AUTHORIZATION.```$ bin/psql \"port=5430 sslmode=disable dbname=postgres\" -x -h localhostpostgres=# \\conninfo+Connection Information-[ RECORD 1 ]--------+----------Database | postgresCurrent User | hunaidSession User | hunaidHost | localhostHost Address | 127.0.0.1Port | 5430Protocol Version | 3SSL Connection | falseGSSAPI Authenticated | falseClient Encoding | UTF8Server Encoding | UTF8Backend PID | 1337postgres=# set SESSION AUTHORIZATION postgres;SETpostgres=# \\conninfo+Connection Information-[ RECORD 1 ]--------+----------Database | postgresCurrent User | hunaidSession User | postgresHost | localhostHost Address | 127.0.0.1Port | 5430Protocol Version | 3SSL Connection | falseGSSAPI Authenticated | falseClient Encoding | UTF8Server Encoding | UTF8Backend PID | 1337```We can update the docs as follows:Authenticated User: The name of the user returned by PQuser().Session User: The session user's name.Opinions?Regards,Hunaid Sohail",
"msg_date": "Tue, 17 Sep 2024 16:53:02 +0500",
"msg_from": "Hunaid Sohail <hunaidpgml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi,\n\nThis patch renames \"Current User\" to \"Authenticated User\" as suggested by\nme in my last email. I have also updated the documentation accordingly.\n\nOn Tue, Sep 17, 2024 at 4:53 PM Hunaid Sohail <hunaidpgml@gmail.com> wrote:\n\n> We can update the docs as follows:\n> Authenticated User: The name of the user returned by PQuser().\n> Session User: The session user's name.\n>\n\nMoreover, as Álvaro suggested, I made some modifications to the code\nstructure and moved verbose code into a separate function.\n\nPlease let me know if you have any questions or further suggestions.\n\nRegards,\nHunaid Sohail",
"msg_date": "Thu, 26 Sep 2024 12:15:26 +0500",
"msg_from": "Hunaid Sohail <hunaidpgml@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
},
{
"msg_contents": "Hi\n\nOn 26.09.24 09:15, Hunaid Sohail wrote:\n> This patch renames \"Current User\" to \"Authenticated User\" as suggested\n> by me in my last email. I have also updated the documentation accordingly.\n\nCould you perhaps in the documentation elaborate a bit more on the\ndifference between \"Current User\" and \"Authenticated User\"? IMHO a\ncouple of words on how exactly they differ would be very helpful, as\nthey show the same user in many cases.\n\n> Authenticated User: The name of the user returned by PQuser()\n> Session User: The session user's name.\n\nAlthough a bit redundant, I'd argue that \"SSL Compression\" is better\nthan just \"Compression\".\n\nOther than that, it looks much better now:\n\n$ /usr/local/postgres-dev/bin/psql -x \"\\\n host=server.uni-muenster.de\n hostaddr=192.168.178.27\n user=jim dbname=db\n port=54322\n sslmode=verify-full\n sslrootcert=server-certificates/server.crt\n sslcert=jim-certificates/jim.crt\n sslkey=jim-certificates/jim.key\"\n\npsql (18devel)\nSSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,\ncompression: off, ALPN: postgresql)\nType \"help\" for help.\n\ndb=# SET client_encoding TO 'LATIN1';\nSET\n\ndb=# \\conninfo+\nConnection Information\n-[ RECORD 1 ]--------+-----------------------\nDatabase | db\nAuthenticated User | jim\nSession User | jim\nHost | server.uni-muenster.de\nHost Address | 192.168.178.27\nPort | 54322\nProtocol Version | 3\nSSL Connection | true\nSSL Protocol | TLSv1.3\nSSL Cipher | TLS_AES_256_GCM_SHA384\nCompression | off\nALPN | postgresql\nGSSAPI Authenticated | false\nClient Encoding | LATIN1\nServer Encoding | UTF8\nBackend PID | 874890\n\n\nThanks!\n\n\n",
"msg_date": "Mon, 30 Sep 2024 20:16:09 +0200",
"msg_from": "Jim Jones <jim.jones@uni-muenster.de>",
"msg_from_op": false,
"msg_subject": "Re: Psql meta-command conninfo+"
}
] |
[
{
"msg_contents": "The function pg_get_expr(), which is used in various system views and \ninformation schema views, does not appear to lock the table passed as \nthe second argument, and so appears to be liable to fail if there is a \nconcurrent drop of the table. There is a (probable) case of this being \ndiscussed at [0]. I also see various mentions of this issue in the \ncommit logs, mostly related to pg_dump.\n\nIs there a reason there is no locking? Performance?\n\nWhat workaround should we use if there are conflicts created by \nconcurrent regression tests? Just move the tests around a bit until the \nissue goes away?\n\n\n[0]: \nhttps://www.postgresql.org/message-id/flat/9ec24d7b-633d-463a-84c6-7acff769c9e8@eisentraut.org\n\n\n",
"msg_date": "Wed, 7 Feb 2024 09:18:29 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "pg_get_expr locking"
},
{
"msg_contents": "Peter Eisentraut <peter@eisentraut.org> writes:\n> The function pg_get_expr(), which is used in various system views and \n> information schema views, does not appear to lock the table passed as \n> the second argument, and so appears to be liable to fail if there is a \n> concurrent drop of the table. There is a (probable) case of this being \n> discussed at [0]. I also see various mentions of this issue in the \n> commit logs, mostly related to pg_dump.\n\n> Is there a reason there is no locking? Performance?\n\nI think we have a general rule that you shouldn't be able to take\nlocks on relations you have no privileges for, so pg_get_expr would\nneed to verify privileges if it locked the rel. At least for\npg_dump's purposes, that cure would be about as bad as the disease.\n\n> What workaround should we use if there are conflicts created by \n> concurrent regression tests? Just move the tests around a bit until the \n> issue goes away?\n\nWhy would a test be applying pg_get_expr to a table it doesn't\ncontrol?\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Wed, 07 Feb 2024 10:26:30 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: pg_get_expr locking"
},
{
"msg_contents": "On 07.02.24 16:26, Tom Lane wrote:\n>> What workaround should we use if there are conflicts created by\n>> concurrent regression tests? Just move the tests around a bit until the\n>> issue goes away?\n> \n> Why would a test be applying pg_get_expr to a table it doesn't\n> control?\n\nI think the situation is that one test (domain) runs pg_get_expr as part \nof an information_schema view, while at the same time another test \n(alter_table) drops a table that the pg_get_expr is just processing.\n\n\n\n",
"msg_date": "Thu, 8 Feb 2024 12:18:17 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: pg_get_expr locking"
},
{
"msg_contents": "Peter Eisentraut <peter@eisentraut.org> writes:\n> On 07.02.24 16:26, Tom Lane wrote:\n>> Why would a test be applying pg_get_expr to a table it doesn't\n>> control?\n\n> I think the situation is that one test (domain) runs pg_get_expr as part \n> of an information_schema view, while at the same time another test \n> (alter_table) drops a table that the pg_get_expr is just processing.\n\nThe test case that's failing is, IIUC,\n\n+SELECT * FROM information_schema.domain_constraints\n+ WHERE domain_name IN ('con', 'dom', 'pos_int', 'things')\n+ ORDER BY constraint_name;\n\nI see no use of pg_get_expr() in the domain_constraints view:\n\nCREATE VIEW domain_constraints AS\n SELECT CAST(current_database() AS sql_identifier) AS constraint_catalog,\n CAST(rs.nspname AS sql_identifier) AS constraint_schema,\n CAST(con.conname AS sql_identifier) AS constraint_name,\n CAST(current_database() AS sql_identifier) AS domain_catalog,\n CAST(n.nspname AS sql_identifier) AS domain_schema,\n CAST(t.typname AS sql_identifier) AS domain_name,\n CAST(CASE WHEN condeferrable THEN 'YES' ELSE 'NO' END\n AS yes_or_no) AS is_deferrable,\n CAST(CASE WHEN condeferred THEN 'YES' ELSE 'NO' END\n AS yes_or_no) AS initially_deferred\n FROM pg_namespace rs, pg_namespace n, pg_constraint con, pg_type t\n WHERE rs.oid = con.connamespace\n AND n.oid = t.typnamespace\n AND t.oid = con.contypid\n AND (pg_has_role(t.typowner, 'USAGE')\n OR has_type_privilege(t.oid, 'USAGE'));\n\nI'm a little suspicious that the failure is actually coming from\nsomewhere down inside has_type_privilege(), but I traced through\nthat quickly and don't see how it could reach such an error.\nIn any case I thought we'd hardened all those functions in 403ac226d.\nSo I'm still pretty mystified. Have you had any luck in making\nthe failure reproducible?\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Thu, 08 Feb 2024 11:59:51 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: pg_get_expr locking"
},
{
"msg_contents": "I wrote:\n> Peter Eisentraut <peter@eisentraut.org> writes:\n>> I think the situation is that one test (domain) runs pg_get_expr as part \n>> of an information_schema view, while at the same time another test \n>> (alter_table) drops a table that the pg_get_expr is just processing.\n\n> The test case that's failing is, IIUC,\n\n> +SELECT * FROM information_schema.domain_constraints\n> + WHERE domain_name IN ('con', 'dom', 'pos_int', 'things')\n> + ORDER BY constraint_name;\n\nOh, scratch that: there are two confusingly lookalike queries\nin the patch. The one that is failing is\n\nSELECT * FROM information_schema.check_constraints\n WHERE (constraint_schema, constraint_name)\n IN (SELECT constraint_schema, constraint_name\n FROM information_schema.domain_constraints\n WHERE domain_name IN ('con', 'dom', 'pos_int', 'things'))\n ORDER BY constraint_name;\n\nand we have trouble because the evaluation of pg_get_expr in\ncheck_constraints is done before the semijoin that would restrict\nit to just the desired objects.\n\nAfter looking at the code I'm less worried about the\npermissions-checking angle than I was before, because I see\nthat pg_get_expr already takes a transient AccessShareLock\non the rel, down inside set_relation_column_names. This is\nnot ideal from a permissions standpoint perhaps, but it's\nprobably OK considering we've done that for a long time.\nWe just need to hold that lock a little while longer.\n\nI propose the attached as a reasonably localized fix.\nWe could imagine a more aggressive refactoring that would\nallow passing down the Relation instead of re-opening it\nin set_relation_column_names, but I doubt it's worth the\ntrouble.\n\n\t\t\tregards, tom lane",
"msg_date": "Thu, 08 Feb 2024 15:20:59 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: pg_get_expr locking"
}
] |
[
{
"msg_contents": "Hi ,\n\npostgresql-42.7.1.jar\n\nTrying to use establish a connection using PKCS8 certificate created with\npassword.\n\n\n*openssl pkcs8 -topk8 -inform PEM -in client.key -outform DER -out\nclient.pk8 -passout pass:foobar*\n\nI set the properties as below:\n*...*\n\n*sslProperties.setProperty(\"sslkey\",\n\"client.pk8\");sslProperties.setProperty(\"sslpassword\",\"foobar\");*\n*...*\n\n*Connection connection = DriverManager.getConnection(jdbcUrl,\nsslProperties);*\n*....*\n*This is failing with the error:*\n\n\n\n\n*org.postgresql.util.PSQLException: SSL error: Connection reset at\norg.postgresql.ssl.MakeSSL.convert(MakeSSL.java:43) at\norg.postgresql.core.v3.ConnectionFactoryImpl.enableSSL(ConnectionFactoryImpl.java:584)\nat\norg.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:168)*\n*...*\n\nRegards,\nMadhu\n\nHi ,postgresql-42.7.1.jarTrying to use establish a connection using PKCS8 certificate created with password.openssl pkcs8 -topk8 -inform PEM -in client.key -outform DER -out client.pk8 -passout pass:foobarI set the properties as below:...sslProperties.setProperty(\"sslkey\", \"client.pk8\");sslProperties.setProperty(\"sslpassword\",\"foobar\");...Connection connection = DriverManager.getConnection(jdbcUrl, sslProperties);....This is failing with the error:org.postgresql.util.PSQLException: SSL error: Connection reset\tat org.postgresql.ssl.MakeSSL.convert(MakeSSL.java:43)\tat org.postgresql.core.v3.ConnectionFactoryImpl.enableSSL(ConnectionFactoryImpl.java:584)\tat org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:168)...Regards,Madhu",
"msg_date": "Wed, 7 Feb 2024 15:17:06 +0530",
"msg_from": "just madhu <justvmadhu@gmail.com>",
"msg_from_op": true,
"msg_subject": "pgjdbc is not working with PKCS8 certificates with password"
},
{
"msg_contents": "On further investigation,\n\n*With certificate generated as below. JDBC connection is successful.openssl\npkcs8 -topk8 -inform PEM -in client.key -outform DER -out client.pk8\n -passout pass:foobar * -v1 PBE-MD5-DES\n\nBut a connection from pgAdmin (connection failed:\n\\SSLCerts\\pk8_pass\\client_pass_PBE.pk8\": no start line) and psql(psql:\nerror: could not load private key file \"client_pass_PBE.pk8\": unsupported)\nis failing\n\nIs there a common way in which certificate with passwords can be created\nfor both libpq and jdbc ?\n\n\nOn Wed, Feb 7, 2024 at 3:17 PM just madhu <justvmadhu@gmail.com> wrote:\n\n> Hi ,\n>\n> postgresql-42.7.1.jar\n>\n> Trying to use establish a connection using PKCS8 certificate created with\n> password.\n>\n>\n> *openssl pkcs8 -topk8 -inform PEM -in client.key -outform DER -out\n> client.pk8 -passout pass:foobar*\n>\n> I set the properties as below:\n> *...*\n>\n> *sslProperties.setProperty(\"sslkey\",\n> \"client.pk8\");sslProperties.setProperty(\"sslpassword\",\"foobar\");*\n> *...*\n>\n> *Connection connection = DriverManager.getConnection(jdbcUrl,\n> sslProperties);*\n> *....*\n> *This is failing with the error:*\n>\n>\n>\n>\n> *org.postgresql.util.PSQLException: SSL error: Connection reset at\n> org.postgresql.ssl.MakeSSL.convert(MakeSSL.java:43) at\n> org.postgresql.core.v3.ConnectionFactoryImpl.enableSSL(ConnectionFactoryImpl.java:584)\n> at\n> org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:168)*\n> *...*\n>\n> Regards,\n> Madhu\n>\n>\n\nOn further investigation, With certificate generated as below. JDBC connection is successful.openssl pkcs8 -topk8 -inform PEM -in client.key -outform DER -out client.pk8 -passout pass:foobar -v1 PBE-MD5-DESBut a connection from pgAdmin (connection failed: \\SSLCerts\\pk8_pass\\client_pass_PBE.pk8\": no start line) and psql(psql: error: could not load private key file \"client_pass_PBE.pk8\": unsupported) is failingIs there a common way in which certificate with passwords can be created for both libpq and jdbc ?On Wed, Feb 7, 2024 at 3:17 PM just madhu <justvmadhu@gmail.com> wrote:Hi ,postgresql-42.7.1.jarTrying to use establish a connection using PKCS8 certificate created with password.openssl pkcs8 -topk8 -inform PEM -in client.key -outform DER -out client.pk8 -passout pass:foobarI set the properties as below:...sslProperties.setProperty(\"sslkey\", \"client.pk8\");sslProperties.setProperty(\"sslpassword\",\"foobar\");...Connection connection = DriverManager.getConnection(jdbcUrl, sslProperties);....This is failing with the error:org.postgresql.util.PSQLException: SSL error: Connection reset\tat org.postgresql.ssl.MakeSSL.convert(MakeSSL.java:43)\tat org.postgresql.core.v3.ConnectionFactoryImpl.enableSSL(ConnectionFactoryImpl.java:584)\tat org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:168)...Regards,Madhu",
"msg_date": "Wed, 7 Feb 2024 17:12:06 +0530",
"msg_from": "just madhu <justvmadhu@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: pgjdbc is not working with PKCS8 certificates with password"
},
{
"msg_contents": "On 2/7/24 06:42, just madhu wrote:\n> On further investigation,\n> /With certificate generated as below. JDBC connection is successful./\n> openssl pkcs8 -topk8 -inform PEM -in client.key -outform DER -out \n> client.pk8 -passout pass:foobar / -v1 PBE-MD5-DES\n> \n> But a connection from pgAdmin (connection failed: \n> \\SSLCerts\\pk8_pass\\client_pass_PBE.pk8\": no start line) and psql(psql: \n> error: could not load private key file \"client_pass_PBE.pk8\": \n> unsupported) is failing\n> \n> Is there a common way in which certificate with passwords can be \n> created for both libpq and jdbc ?\n\n\nYou may want to check with the pgjdbc project on github rather than (or \nin addition to?) here; see:\n\n https://github.com/pgjdbc/pgjdbc/issues\n\nJoe\n\n> On Wed, Feb 7, 2024 at 3:17 PM just madhu <justvmadhu@gmail.com \n> <mailto:justvmadhu@gmail.com>> wrote:\n> \n> Hi ,\n> \n> postgresql-42.7.1.jar\n> \n> Trying to use establish a connection using PKCS8 certificate created\n> with password.\n> \n> /openssl pkcs8 -topk8 -inform PEM -in client.key -outform DER -out\n> client.pk8 -passout pass:foobar\n> /\n> \n> I set the properties as below:\n> /.../\n> /sslProperties.setProperty(\"sslkey\", \"client.pk8\");\n> sslProperties.setProperty(\"sslpassword\",\"foobar\");/\n> /.../\n> /Connection connection = DriverManager.getConnection(jdbcUrl,\n> sslProperties);\n> /\n> /..../\n> /This is failing with the error:/\n> /org.postgresql.util.PSQLException: SSL error: Connection reset\n> at org.postgresql.ssl.MakeSSL.convert(MakeSSL.java:43)\n> at\n> org.postgresql.core.v3.ConnectionFactoryImpl.enableSSL(ConnectionFactoryImpl.java:584)\n> at\n> org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:168)\n> /\n> /.../\n> \n> Regards,\n> Madhu\n> \n\n-- \nJoe Conway\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com\n\n\n\n",
"msg_date": "Wed, 7 Feb 2024 09:52:02 -0500",
"msg_from": "Joe Conway <mail@joeconway.com>",
"msg_from_op": false,
"msg_subject": "Re: pgjdbc is not working with PKCS8 certificates with password"
},
{
"msg_contents": "I see that the generated certificate is not working in pgAdmin and psql.\nSo I wanted a way by which I could make it work there as well.\nAs ANS.1 DER is a supported format for libpq, I suppose that this\ncertificate should work here as well.\n\nAlso as suggested checking in pgjdbc as well.\n\nOn Wed, Feb 7, 2024 at 8:22 PM Joe Conway <mail@joeconway.com> wrote:\n\n> On 2/7/24 06:42, just madhu wrote:\n> > On further investigation,\n> > /With certificate generated as below. JDBC connection is successful./\n> > openssl pkcs8 -topk8 -inform PEM -in client.key -outform DER -out\n> > client.pk8 -passout pass:foobar / -v1 PBE-MD5-DES\n> >\n> > But a connection from pgAdmin (connection failed:\n> > \\SSLCerts\\pk8_pass\\client_pass_PBE.pk8\": no start line) and psql(psql:\n> > error: could not load private key file \"client_pass_PBE.pk8\":\n> > unsupported) is failing\n> >\n> > Is there a common way in which certificate with passwords can be\n> > created for both libpq and jdbc ?\n>\n>\n> You may want to check with the pgjdbc project on github rather than (or\n> in addition to?) here; see:\n>\n> https://github.com/pgjdbc/pgjdbc/issues\n>\n> Joe\n>\n> > On Wed, Feb 7, 2024 at 3:17 PM just madhu <justvmadhu@gmail.com\n> > <mailto:justvmadhu@gmail.com>> wrote:\n> >\n> > Hi ,\n> >\n> > postgresql-42.7.1.jar\n> >\n> > Trying to use establish a connection using PKCS8 certificate created\n> > with password.\n> >\n> > /openssl pkcs8 -topk8 -inform PEM -in client.key -outform DER -out\n> > client.pk8 -passout pass:foobar\n> > /\n> >\n> > I set the properties as below:\n> > /.../\n> > /sslProperties.setProperty(\"sslkey\", \"client.pk8\");\n> > sslProperties.setProperty(\"sslpassword\",\"foobar\");/\n> > /.../\n> > /Connection connection = DriverManager.getConnection(jdbcUrl,\n> > sslProperties);\n> > /\n> > /..../\n> > /This is failing with the error:/\n> > /org.postgresql.util.PSQLException: SSL error: Connection reset\n> > at org.postgresql.ssl.MakeSSL.convert(MakeSSL.java:43)\n> > at\n> >\n> org.postgresql.core.v3.ConnectionFactoryImpl.enableSSL(ConnectionFactoryImpl.java:584)\n> > at\n> >\n> org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:168)\n> > /\n> > /.../\n> >\n> > Regards,\n> > Madhu\n> >\n>\n> --\n> Joe Conway\n> PostgreSQL Contributors Team\n> RDS Open Source Databases\n> Amazon Web Services: https://aws.amazon.com\n>\n>\n\nI see that the generated certificate is not working in pgAdmin and psql. So I wanted a way by which I could make it work there as well.As ANS.1 DER is a supported format for libpq, I suppose that this certificate should work here as well.Also as suggested checking in pgjdbc as well.On Wed, Feb 7, 2024 at 8:22 PM Joe Conway <mail@joeconway.com> wrote:On 2/7/24 06:42, just madhu wrote:\n> On further investigation,\n> /With certificate generated as below. JDBC connection is successful./\n> openssl pkcs8 -topk8 -inform PEM -in client.key -outform DER -out \n> client.pk8 -passout pass:foobar / -v1 PBE-MD5-DES\n> \n> But a connection from pgAdmin (connection failed: \n> \\SSLCerts\\pk8_pass\\client_pass_PBE.pk8\": no start line) and psql(psql: \n> error: could not load private key file \"client_pass_PBE.pk8\": \n> unsupported) is failing\n> \n> Is there a common way in which certificate with passwords can be \n> created for both libpq and jdbc ?\n\n\nYou may want to check with the pgjdbc project on github rather than (or \nin addition to?) here; see:\n\n https://github.com/pgjdbc/pgjdbc/issues\n\nJoe\n\n> On Wed, Feb 7, 2024 at 3:17 PM just madhu <justvmadhu@gmail.com \n> <mailto:justvmadhu@gmail.com>> wrote:\n> \n> Hi ,\n> \n> postgresql-42.7.1.jar\n> \n> Trying to use establish a connection using PKCS8 certificate created\n> with password.\n> \n> /openssl pkcs8 -topk8 -inform PEM -in client.key -outform DER -out\n> client.pk8 -passout pass:foobar\n> /\n> \n> I set the properties as below:\n> /.../\n> /sslProperties.setProperty(\"sslkey\", \"client.pk8\");\n> sslProperties.setProperty(\"sslpassword\",\"foobar\");/\n> /.../\n> /Connection connection = DriverManager.getConnection(jdbcUrl,\n> sslProperties);\n> /\n> /..../\n> /This is failing with the error:/\n> /org.postgresql.util.PSQLException: SSL error: Connection reset\n> at org.postgresql.ssl.MakeSSL.convert(MakeSSL.java:43)\n> at\n> org.postgresql.core.v3.ConnectionFactoryImpl.enableSSL(ConnectionFactoryImpl.java:584)\n> at\n> org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:168)\n> /\n> /.../\n> \n> Regards,\n> Madhu\n> \n\n-- \nJoe Conway\nPostgreSQL Contributors Team\nRDS Open Source Databases\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Wed, 7 Feb 2024 20:53:20 +0530",
"msg_from": "just madhu <justvmadhu@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: pgjdbc is not working with PKCS8 certificates with password"
}
] |
[
{
"msg_contents": "I came across the Perl autodie pragma \n(https://perldoc.perl.org/autodie). This seems pretty useful; is this \nsomething we can use? Any drawbacks? Any minimum Perl version?\n\nAttached is a sample patch of the kind of thing I'd be interested in. \nThe existing error handling of file operations in Perl is pretty \ncumbersome, and this would simplify that.\n\nBtw., here is a sample error message from autodie:\n\nCan't open '../src/include/mb/pg_wchar.h' for reading: 'No such file or \ndirectory' at ../src/include/catalog/../../backend/catalog/genbki.pl \nline 391\n\nwhich seems as good or better than the stuff we produce manually.",
"msg_date": "Wed, 7 Feb 2024 15:05:16 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "What about Perl autodie?"
},
{
"msg_contents": "On Wed, Feb 7, 2024 at 9:05 AM Peter Eisentraut <peter@eisentraut.org>\nwrote:\n\n> I came across the Perl autodie pragma\n> (https://perldoc.perl.org/autodie). This seems pretty useful; is this\n> something we can use? Any drawbacks? Any minimum Perl version?\n\n\nBig +1\n\nNo drawbacks. I've been using it heavily for many, many years. Came out in\n5.10.1,\nwhich should be available everywhere at this point (2009 was the year of\nrelease)\n\nCheers,\nGreg\n\nOn Wed, Feb 7, 2024 at 9:05 AM Peter Eisentraut <peter@eisentraut.org> wrote:I came across the Perl autodie pragma \n(https://perldoc.perl.org/autodie). This seems pretty useful; is this \nsomething we can use? Any drawbacks? Any minimum Perl version?Big +1No drawbacks. I've been using it heavily for many, many years. Came out in 5.10.1, which should be available everywhere at this point (2009 was the year of release)Cheers,Greg",
"msg_date": "Wed, 7 Feb 2024 11:51:37 -0500",
"msg_from": "Greg Sabino Mullane <htamfids@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "On Wed, Feb 7, 2024 at 11:52 PM Greg Sabino Mullane <htamfids@gmail.com> wrote:\n>\n> No drawbacks. I've been using it heavily for many, many years. Came out in 5.10.1,\n> which should be available everywhere at this point (2009 was the year of release)\n\nWe moved our minimum to 5.14 fairly recently, so we're good on that point.\n\n\n",
"msg_date": "Thu, 8 Feb 2024 12:53:09 +0700",
"msg_from": "John Naylor <johncnaylorls@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "John Naylor <johncnaylorls@gmail.com> writes:\n> On Wed, Feb 7, 2024 at 11:52 PM Greg Sabino Mullane <htamfids@gmail.com> wrote:\n>> No drawbacks. I've been using it heavily for many, many years. Came out in 5.10.1,\n>> which should be available everywhere at this point (2009 was the year of release)\n\n> We moved our minimum to 5.14 fairly recently, so we're good on that point.\n\nYeah, but only recently. I'm a little worried about the value of this\nchange relative to the amount of code churn involved, and more to the\npoint I worry about the risk of future back-patches injecting bad code\ninto back branches that don't use autodie.\n\n(Back-patching the use of autodie doesn't seem feasible, since before\nv16 we supported perl 5.8.something.)\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Thu, 08 Feb 2024 01:03:23 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "On 08.02.24 07:03, Tom Lane wrote:\n> John Naylor <johncnaylorls@gmail.com> writes:\n>> On Wed, Feb 7, 2024 at 11:52 PM Greg Sabino Mullane <htamfids@gmail.com> wrote:\n>>> No drawbacks. I've been using it heavily for many, many years. Came out in 5.10.1,\n>>> which should be available everywhere at this point (2009 was the year of release)\n> \n>> We moved our minimum to 5.14 fairly recently, so we're good on that point.\n> \n> Yeah, but only recently. I'm a little worried about the value of this\n> change relative to the amount of code churn involved, and more to the\n> point I worry about the risk of future back-patches injecting bad code\n> into back branches that don't use autodie.\n> \n> (Back-patching the use of autodie doesn't seem feasible, since before\n> v16 we supported perl 5.8.something.)\n\nYeah, good points. I suppose we could start using it for completely new \nscripts.\n\n\n\n",
"msg_date": "Thu, 8 Feb 2024 08:01:00 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "> On 8 Feb 2024, at 08:01, Peter Eisentraut <peter@eisentraut.org> wrote:\n\n> I suppose we could start using it for completely new scripts.\n\n+1, it would be nice to eventually be able to move to it everywhere so starting\nnow with new scripts may make the eventual transition smoother.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Thu, 8 Feb 2024 09:13:10 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "Daniel Gustafsson <daniel@yesql.se> writes:\n>> On 8 Feb 2024, at 08:01, Peter Eisentraut <peter@eisentraut.org> wrote:\n>> I suppose we could start using it for completely new scripts.\n\n> +1, it would be nice to eventually be able to move to it everywhere so starting\n> now with new scripts may make the eventual transition smoother.\n\nI'm still concerned about people carelessly using autodie-reliant\ncode in places where they shouldn't. I offer two safer ways\nforward:\n\n1. Wait till v16 is the oldest supported branch, and then migrate\nboth HEAD and back branches to using autodie.\n\n2. Don't wait, migrate them all now. This would mean requiring\nPerl 5.10.1 or later to run the TAP tests, even in back branches.\n\nI think #2 might not be all that radical. We have nothing older\nthan 5.14.0 in the buildfarm, so we don't really have much grounds\nfor claiming that 5.8.3 will work today. And 5.10.1 came out in\n2009, so how likely is it that anyone cares anymore?\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Thu, 08 Feb 2024 10:53:06 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "> On 8 Feb 2024, at 16:53, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> 2. Don't wait, migrate them all now. This would mean requiring\n> Perl 5.10.1 or later to run the TAP tests, even in back branches.\n> \n> I think #2 might not be all that radical. We have nothing older\n> than 5.14.0 in the buildfarm, so we don't really have much grounds\n> for claiming that 5.8.3 will work today. And 5.10.1 came out in\n> 2009, so how likely is it that anyone cares anymore?\n\nI would vote for this option, if we don't run the trailing edge anywhere where\nbreakage is visible to developers then it is like you say, far from guaranteed\nto work.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Thu, 8 Feb 2024 17:08:01 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": ">\n> 2. Don't wait, migrate them all now. This would mean requiring\n> Perl 5.10.1 or later to run the TAP tests, even in back branches.\n>\n\n#2 please. For context, meson did not even exist in 2009.\n\nCheers,\nGreg\n\n2. Don't wait, migrate them all now. This would mean requiring\nPerl 5.10.1 or later to run the TAP tests, even in back branches.#2 please. For context, meson did not even exist in 2009.Cheers,Greg",
"msg_date": "Thu, 8 Feb 2024 11:10:12 -0500",
"msg_from": "Greg Sabino Mullane <htamfids@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "Daniel Gustafsson <daniel@yesql.se> writes:\n\n>> On 8 Feb 2024, at 16:53, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n>> 2. Don't wait, migrate them all now. This would mean requiring\n>> Perl 5.10.1 or later to run the TAP tests, even in back branches.\n>> \n>> I think #2 might not be all that radical. We have nothing older\n>> than 5.14.0 in the buildfarm, so we don't really have much grounds\n>> for claiming that 5.8.3 will work today. And 5.10.1 came out in\n>> 2009, so how likely is it that anyone cares anymore?\n>\n> I would vote for this option, if we don't run the trailing edge anywhere where\n> breakage is visible to developers then it is like you say, far from guaranteed\n> to work.\n\nThe oldest Perl I'm aware of on a still-supported (fsvo) OS is RHEL 6,\nwhich shipped 5.10.1 and has Extended Life-cycle Support until\n2024-06-30.\n\nFor comparison, last year the at the Perl Toolchain Summit in Lyon we\ndecided that toolchain modules (the modules needed to build, test and\ninstall CPAN distributions) are only required support versions of Perl\nup to 10 years old, i.e. currently 5.18 (but there's a one-time\nexcemption to keep it to 5.16 until RHEL 7 goes out of maintenance\nsupport on 2024-06-30).\n\n- ilmari\n\n\n",
"msg_date": "Thu, 08 Feb 2024 16:26:50 +0000",
"msg_from": "=?utf-8?Q?Dagfinn_Ilmari_Manns=C3=A5ker?= <ilmari@ilmari.org>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "\nOn 2024-02-08 Th 11:08, Daniel Gustafsson wrote:\n>> On 8 Feb 2024, at 16:53, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> 2. Don't wait, migrate them all now. This would mean requiring\n>> Perl 5.10.1 or later to run the TAP tests, even in back branches.\n>>\n>> I think #2 might not be all that radical. We have nothing older\n>> than 5.14.0 in the buildfarm, so we don't really have much grounds\n>> for claiming that 5.8.3 will work today. And 5.10.1 came out in\n>> 2009, so how likely is it that anyone cares anymore?\n> I would vote for this option, if we don't run the trailing edge anywhere where\n> breakage is visible to developers then it is like you say, far from guaranteed\n> to work.\n>\n\n+1 from me too. We kept 5.8 going for a while because it was what the \nMsys (v1) DTK perl was, but that doesn't matter any more I think.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n",
"msg_date": "Sat, 10 Feb 2024 11:05:41 -0500",
"msg_from": "Andrew Dunstan <andrew@dunslane.net>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "Andrew Dunstan <andrew@dunslane.net> writes:\n> On 2024-02-08 Th 11:08, Daniel Gustafsson wrote:\n>> On 8 Feb 2024, at 16:53, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>>> 2. Don't wait, migrate them all now. This would mean requiring\n>>> Perl 5.10.1 or later to run the TAP tests, even in back branches.\n>>> I think #2 might not be all that radical. We have nothing older\n>>> than 5.14.0 in the buildfarm, so we don't really have much grounds\n>>> for claiming that 5.8.3 will work today. And 5.10.1 came out in\n>>> 2009, so how likely is it that anyone cares anymore?\n\n>> I would vote for this option, if we don't run the trailing edge anywhere where\n>> breakage is visible to developers then it is like you say, far from guaranteed\n>> to work.\n\n> +1 from me too. We kept 5.8 going for a while because it was what the \n> Msys (v1) DTK perl was, but that doesn't matter any more I think.\n\nI've reconfigured longfin, which was using perl 5.14.0 on all\nbranches, to use 5.10.1 on the pre-v16 branches (and it did pass).\nThis seems like a good change even if we don't pull the trigger on\nthe above proposal --- although if we don't, maybe I should see\nif I can get 5.8.3 to build on that machine.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Sat, 10 Feb 2024 19:36:36 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "On 08.02.24 16:53, Tom Lane wrote:\n> Daniel Gustafsson <daniel@yesql.se> writes:\n>>> On 8 Feb 2024, at 08:01, Peter Eisentraut <peter@eisentraut.org> wrote:\n>>> I suppose we could start using it for completely new scripts.\n> \n>> +1, it would be nice to eventually be able to move to it everywhere so starting\n>> now with new scripts may make the eventual transition smoother.\n> \n> I'm still concerned about people carelessly using autodie-reliant\n> code in places where they shouldn't. I offer two safer ways\n> forward:\n> \n> 1. Wait till v16 is the oldest supported branch, and then migrate\n> both HEAD and back branches to using autodie.\n> \n> 2. Don't wait, migrate them all now. This would mean requiring\n> Perl 5.10.1 or later to run the TAP tests, even in back branches.\n> \n> I think #2 might not be all that radical. We have nothing older\n> than 5.14.0 in the buildfarm, so we don't really have much grounds\n> for claiming that 5.8.3 will work today. And 5.10.1 came out in\n> 2009, so how likely is it that anyone cares anymore?\n\nA gentler way might be to start using some perlcritic policies like \nInputOutput::RequireCheckedOpen or the more general \nInputOutput::RequireCheckedSyscalls and add explicit error checking at \nthe sites it points out. And then if we start using autodie in the \nfuture, any inappropriate backpatching of calls lacking error checks \nwould be caught.\n\n\n\n",
"msg_date": "Wed, 14 Feb 2024 17:52:32 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "\nOn 2024-02-14 We 11:52, Peter Eisentraut wrote:\n> On 08.02.24 16:53, Tom Lane wrote:\n>> Daniel Gustafsson <daniel@yesql.se> writes:\n>>>> On 8 Feb 2024, at 08:01, Peter Eisentraut <peter@eisentraut.org> \n>>>> wrote:\n>>>> I suppose we could start using it for completely new scripts.\n>>\n>>> +1, it would be nice to eventually be able to move to it everywhere \n>>> so starting\n>>> now with new scripts may make the eventual transition smoother.\n>>\n>> I'm still concerned about people carelessly using autodie-reliant\n>> code in places where they shouldn't. I offer two safer ways\n>> forward:\n>>\n>> 1. Wait till v16 is the oldest supported branch, and then migrate\n>> both HEAD and back branches to using autodie.\n>>\n>> 2. Don't wait, migrate them all now. This would mean requiring\n>> Perl 5.10.1 or later to run the TAP tests, even in back branches.\n>>\n>> I think #2 might not be all that radical. We have nothing older\n>> than 5.14.0 in the buildfarm, so we don't really have much grounds\n>> for claiming that 5.8.3 will work today. And 5.10.1 came out in\n>> 2009, so how likely is it that anyone cares anymore?\n>\n> A gentler way might be to start using some perlcritic policies like \n> InputOutput::RequireCheckedOpen or the more general \n> InputOutput::RequireCheckedSyscalls and add explicit error checking at \n> the sites it points out. And then if we start using autodie in the \n> future, any inappropriate backpatching of calls lacking error checks \n> would be caught.\n>\n>\n\nYeah, that should work.\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com\n\n\n\n",
"msg_date": "Sun, 18 Feb 2024 19:54:37 -0500",
"msg_from": "Andrew Dunstan <andrew@dunslane.net>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "> On 19 Feb 2024, at 01:54, Andrew Dunstan <andrew@dunslane.net> wrote:\n> On 2024-02-14 We 11:52, Peter Eisentraut wrote:\n\n>> A gentler way might be to start using some perlcritic policies like InputOutput::RequireCheckedOpen or the more general InputOutput::RequireCheckedSyscalls and add explicit error checking at the sites it points out. And then if we start using autodie in the future, any inappropriate backpatching of calls lacking error checks would be caught.\n> \n> Yeah, that should work.\n\nI didn't study the referenced rules but the concept seems sane, so definitely a\n+1 on that.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Mon, 19 Feb 2024 09:42:29 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "On 14.02.24 17:52, Peter Eisentraut wrote:\n> A gentler way might be to start using some perlcritic policies like \n> InputOutput::RequireCheckedOpen or the more general \n> InputOutput::RequireCheckedSyscalls and add explicit error checking at \n> the sites it points out.\n\nHere is a start for that. I added the required stanza to perlcriticrc \nand started with an explicit list of functions to check:\n\nfunctions = chmod flock open read rename seek symlink system\n\nand fixed all the issues it pointed out.\n\nI picked those functions because most existing code already checked \nthose, so the omissions are probably unintended, or in some cases also \nbecause I thought it would be important for test correctness (e.g., some \ntests using chmod).\n\nI didn't design any beautiful error messages, mostly just used \"or die \n$!\", which mostly matches existing code, and also this is \ndeveloper-level code, so having the system error plus source code \nreference should be ok.\n\nIn the second patch, I changed the perlcriticrc stanza to use an \nexclusion list instead of an explicit inclusion list. That way, you can \nsee what we are currently *not* checking. I'm undecided which way \naround is better, and exactly what functions we should be checking. (Of \ncourse, in principle, all of them, but since this is test and build \nsupport code, not production code, there are probably some reasonable \ncompromises to be made.)",
"msg_date": "Wed, 21 Feb 2024 08:26:36 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "On 21.02.24 08:26, Peter Eisentraut wrote:\n> On 14.02.24 17:52, Peter Eisentraut wrote:\n>> A gentler way might be to start using some perlcritic policies like \n>> InputOutput::RequireCheckedOpen or the more general \n>> InputOutput::RequireCheckedSyscalls and add explicit error checking at \n>> the sites it points out.\n> \n> Here is a start for that. I added the required stanza to perlcriticrc \n> and started with an explicit list of functions to check:\n> \n> functions = chmod flock open read rename seek symlink system\n> \n> and fixed all the issues it pointed out.\n> \n> I picked those functions because most existing code already checked \n> those, so the omissions are probably unintended, or in some cases also \n> because I thought it would be important for test correctness (e.g., some \n> tests using chmod).\n> \n> I didn't design any beautiful error messages, mostly just used \"or die \n> $!\", which mostly matches existing code, and also this is \n> developer-level code, so having the system error plus source code \n> reference should be ok.\n> \n> In the second patch, I changed the perlcriticrc stanza to use an \n> exclusion list instead of an explicit inclusion list. That way, you can \n> see what we are currently *not* checking. I'm undecided which way \n> around is better, and exactly what functions we should be checking. (Of \n> course, in principle, all of them, but since this is test and build \n> support code, not production code, there are probably some reasonable \n> compromises to be made.)\n\nAfter some pondering, I figured the exclude list is better. So here is \na squashed patch, also with a complete commit message.\n\nBtw., do we check perlcritic in an automated way, like on the buildfarm?",
"msg_date": "Mon, 18 Mar 2024 07:27:56 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "On Mon, Mar 18, 2024 at 2:28 AM Peter Eisentraut <peter@eisentraut.org>\nwrote:\n\n> On 21.02.24 08:26, Peter Eisentraut wrote:\n> > On 14.02.24 17:52, Peter Eisentraut wrote:\n> >> A gentler way might be to start using some perlcritic policies like\n> >> InputOutput::RequireCheckedOpen or the more general\n> >> InputOutput::RequireCheckedSyscalls and add explicit error checking at\n> >> the sites it points out.\n> >\n> > Here is a start for that. I added the required stanza to perlcriticrc\n> > and started with an explicit list of functions to check:\n> >\n> > functions = chmod flock open read rename seek symlink system\n> >\n> > and fixed all the issues it pointed out.\n> >\n> > I picked those functions because most existing code already checked\n> > those, so the omissions are probably unintended, or in some cases also\n> > because I thought it would be important for test correctness (e.g., some\n> > tests using chmod).\n> >\n> > I didn't design any beautiful error messages, mostly just used \"or die\n> > $!\", which mostly matches existing code, and also this is\n> > developer-level code, so having the system error plus source code\n> > reference should be ok.\n> >\n> > In the second patch, I changed the perlcriticrc stanza to use an\n> > exclusion list instead of an explicit inclusion list. That way, you can\n> > see what we are currently *not* checking. I'm undecided which way\n> > around is better, and exactly what functions we should be checking. (Of\n> > course, in principle, all of them, but since this is test and build\n> > support code, not production code, there are probably some reasonable\n> > compromises to be made.)\n>\n> After some pondering, I figured the exclude list is better. So here is\n> a squashed patch, also with a complete commit message.\n>\n> Btw., do we check perlcritic in an automated way, like on the buildfarm?\n\n\nYes. crake and koel do.\n\ncheers\n\nandrew\n\nOn Mon, Mar 18, 2024 at 2:28 AM Peter Eisentraut <peter@eisentraut.org> wrote:On 21.02.24 08:26, Peter Eisentraut wrote:\n> On 14.02.24 17:52, Peter Eisentraut wrote:\n>> A gentler way might be to start using some perlcritic policies like \n>> InputOutput::RequireCheckedOpen or the more general \n>> InputOutput::RequireCheckedSyscalls and add explicit error checking at \n>> the sites it points out.\n> \n> Here is a start for that. I added the required stanza to perlcriticrc \n> and started with an explicit list of functions to check:\n> \n> functions = chmod flock open read rename seek symlink system\n> \n> and fixed all the issues it pointed out.\n> \n> I picked those functions because most existing code already checked \n> those, so the omissions are probably unintended, or in some cases also \n> because I thought it would be important for test correctness (e.g., some \n> tests using chmod).\n> \n> I didn't design any beautiful error messages, mostly just used \"or die \n> $!\", which mostly matches existing code, and also this is \n> developer-level code, so having the system error plus source code \n> reference should be ok.\n> \n> In the second patch, I changed the perlcriticrc stanza to use an \n> exclusion list instead of an explicit inclusion list. That way, you can \n> see what we are currently *not* checking. I'm undecided which way \n> around is better, and exactly what functions we should be checking. (Of \n> course, in principle, all of them, but since this is test and build \n> support code, not production code, there are probably some reasonable \n> compromises to be made.)\n\nAfter some pondering, I figured the exclude list is better. So here is \na squashed patch, also with a complete commit message.\n\nBtw., do we check perlcritic in an automated way, like on the buildfarm?Yes. crake and koel do.cheersandrew",
"msg_date": "Mon, 18 Mar 2024 02:34:23 -0400",
"msg_from": "Andrew Dunstan <andrew@dunslane.net>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "> On 18 Mar 2024, at 07:27, Peter Eisentraut <peter@eisentraut.org> wrote:\n\n> After some pondering, I figured the exclude list is better. \n\nAgreed.\n\n> So here is a squashed patch, also with a complete commit message.\n\nLooks good from a read-through. It would have been nice to standardize on\nusing one of \"|| die\" and \"or die\" consistently but that's clearly not for this\nbody of work.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Mon, 18 Mar 2024 09:17:04 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "Daniel Gustafsson <daniel@yesql.se> writes:\n\n>> On 18 Mar 2024, at 07:27, Peter Eisentraut <peter@eisentraut.org> wrote:\n>\n>> After some pondering, I figured the exclude list is better. \n>\n> Agreed.\n>\n>> So here is a squashed patch, also with a complete commit message.\n>\n> Looks good from a read-through. It would have been nice to standardize on\n> using one of \"|| die\" and \"or die\" consistently but that's clearly not for this\n> body of work.\n\n\"or die\" is generally the preferred form, since || has higher precedence\nthan comma, so it's easy to make mistakes if you don't parenthesise the\nfunction args, like:\n\n open my $fh, '>', $filname || die \"can't open $filename: $!\";\n\nwhich will only fail if $filename is falsy (i.e. undef, \"\", or \"0\").\n\n- ilmari\n\n\n",
"msg_date": "Mon, 18 Mar 2024 13:18:43 +0000",
"msg_from": "=?utf-8?Q?Dagfinn_Ilmari_Manns=C3=A5ker?= <ilmari@ilmari.org>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "> On 18 Mar 2024, at 14:18, Dagfinn Ilmari Mannsåker <ilmari@ilmari.org> wrote:\n> Daniel Gustafsson <daniel@yesql.se> writes:\n\n>> It would have been nice to standardize on\n>> using one of \"|| die\" and \"or die\" consistently but that's clearly not for this\n>> body of work.\n> \n> \"or die\" is generally the preferred form, since || has higher precedence\n> than comma, so it's easy to make mistakes if you don't parenthesise the\n> function args, like:\n> \n> open my $fh, '>', $filname || die \"can't open $filename: $!\";\n> \n> which will only fail if $filename is falsy (i.e. undef, \"\", or \"0\").\n\nThanks for the clarification! Looking over the || die() codepaths we have, and\nwe'll add as part of this patchset, none are vulnerable to the above issue\nAFAICT.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Mon, 18 Mar 2024 14:35:38 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: What about Perl autodie?"
},
{
"msg_contents": "On 18.03.24 09:17, Daniel Gustafsson wrote:\n>> On 18 Mar 2024, at 07:27, Peter Eisentraut <peter@eisentraut.org> wrote:\n> \n>> After some pondering, I figured the exclude list is better.\n> \n> Agreed.\n> \n>> So here is a squashed patch, also with a complete commit message.\n> \n> Looks good from a read-through. It would have been nice to standardize on\n> using one of \"|| die\" and \"or die\" consistently but that's clearly not for this\n> body of work.\n\nCommitted.\n\nI was aware of the semantic difference between \"||\" and \"or\", and I had \ntried to keep it similar to surrounding code.\n\n\n\n",
"msg_date": "Tue, 19 Mar 2024 07:29:18 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: What about Perl autodie?"
}
] |
[
{
"msg_contents": "headerscheck started in 55ea1091884 (2019) essentially as an adjusted \ncopy of cpluspluscheck. Since then two scripts have not drifted far \napart. But there are occasionally mistakes keeping the two exclude \nlists updated together. I figure we can just combine the two scripts \ninto one, so it's easier to keep updated.\n\nThe attached patch adds an option --cplusplus to headerscheck, with \nwhich it does the same thing as cpluspluscheck, and cpluspluscheck is \nremoved. The top-level make targets stay the same.",
"msg_date": "Wed, 7 Feb 2024 17:01:40 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Combine headerscheck and cpluspluscheck scripts"
},
{
"msg_contents": "+1\n\n\n",
"msg_date": "Thu, 7 Mar 2024 13:37:36 +1300",
"msg_from": "Thomas Munro <thomas.munro@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Combine headerscheck and cpluspluscheck scripts"
},
{
"msg_contents": "On Thu, Mar 07, 2024 at 01:37:36PM +1300, Thomas Munro wrote:\n> +1\n\nLooking at the patch, nice cleanup.\n--\nMichael",
"msg_date": "Thu, 7 Mar 2024 16:30:11 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Combine headerscheck and cpluspluscheck scripts"
},
{
"msg_contents": "On 07.03.24 08:30, Michael Paquier wrote:\n> On Thu, Mar 07, 2024 at 01:37:36PM +1300, Thomas Munro wrote:\n>> +1\n> \n> Looking at the patch, nice cleanup.\n\nCommitted, thanks.\n\n\n\n",
"msg_date": "Sun, 10 Mar 2024 10:03:00 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: Combine headerscheck and cpluspluscheck scripts"
},
{
"msg_contents": "Hello, hackers,\n\nOn 10/03/2024 12:03, Peter Eisentraut wrote:\n> Committed, thanks.\n\nThis commit (7b8e2ae2f) have turned cpluspluscheck script into a \n--cplusplus option for headerscheck. I propose to update the \nsrc/tools/pginclude/README correspondingly, please see the attached patch.\n\n-- \nAnton Voloshin\nPostgres Professional, The Russian Postgres Company\nhttps://postgrespro.ru",
"msg_date": "Tue, 16 Apr 2024 18:17:14 +0300",
"msg_from": "Anton Voloshin <a.voloshin@postgrespro.ru>",
"msg_from_op": false,
"msg_subject": "Re: Combine headerscheck and cpluspluscheck scripts"
},
{
"msg_contents": "On 16.04.24 17:17, Anton Voloshin wrote:\n> On 10/03/2024 12:03, Peter Eisentraut wrote:\n>> Committed, thanks.\n> \n> This commit (7b8e2ae2f) have turned cpluspluscheck script into a \n> --cplusplus option for headerscheck. I propose to update the \n> src/tools/pginclude/README correspondingly, please see the attached patch.\n\nFixed, thanks!\n\n\n\n",
"msg_date": "Thu, 18 Apr 2024 11:37:58 +0200",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: Combine headerscheck and cpluspluscheck scripts"
}
] |
[
{
"msg_contents": "As part of the reserved page space/page features[1] work, there is a need\nto convert some of the existing constants into variables, since the size of\nthose will no longer be fixed at compile time. At FOSDEM, there was some\ninterest expressed about seeing what a cleanup patch like that would look\nlike.\n\nEnclosed is a series of cleanup patches for HEAD. This splits each of the\n4 constants that care about page size into Cluster-specific and -Limit\nvariants, the first intended to become a variable in time, and the second\nbeing the maximum value such a variable may take (largely used for static\nallocations).\n\nSince these patches define these symbols to have the same values\nthey previously had, there are no changes in functionality. These were\nlargely mechanical changes, and as such we should perhaps consider making\nthe same changes to back-branches to make it so context lines and the like\nwould be the same, simplifying maintainer's efforts when applying code in\nback branches that touch similar areas.\n\nThe script I have to make these changes is simple, and could be run against\nthe back branches with only the comments surrounding Calc() pieces needing\nto be adjusted once.\n\nThese were based on HEAD as a few minutes ago, 902900b308f, and pass all\ntests.\nThanks,\n\nDavid\n\n[1] https://commitfest.postgresql.org/47/3986/",
"msg_date": "Wed, 7 Feb 2024 10:57:48 -0600",
"msg_from": "David Christensen <david.christensen@crunchydata.com>",
"msg_from_op": true,
"msg_subject": "Constant Splitting/Refactoring"
},
{
"msg_contents": "This should target PG 18, but that status is not available in the CF app yet, so just making a note here.",
"msg_date": "Wed, 14 Feb 2024 16:46:02 +0000",
"msg_from": "David Christensen <david+pg@pgguru.net>",
"msg_from_op": false,
"msg_subject": "Re: Constant Splitting/Refactoring"
},
{
"msg_contents": "Here is a version 2 of this patch, rebased atop 97d85be365.\n\nAs before, this is a cleanup/prerequisite patch series for the page\nfeatures/reserved page size patches[1]. (Said patch series is going\nto be updated shortly.)\n\nThis splits each of the 4 constants that care about page size into\nCluster-specific and -Limit variants, the first intended to become a\nvariable in time, and the second being the maximum value such a\nvariable may take (largely used for static\nallocations).\n\nSince these patches define these symbols to have the same values they\npreviously had, there are no changes in functionality. These were\nlargely mechanical changes, and as such we should perhaps consider\nmaking the same changes to back-branches to make it so context lines\nand the like\nwould be the same, simplifying maintainer's efforts when applying code\nin back branches that touch similar areas.\n\nThe script I have to make these changes is simple, and could be run\nagainst the back branches with only the comments surrounding Calc()\npieces needing\nto be adjusted once.\n\nThanks,\n\nDavid\n\n[1] https://commitfest.postgresql.org/47/3986/",
"msg_date": "Wed, 13 Mar 2024 10:42:19 -0500",
"msg_from": "David Christensen <david.christensen@crunchydata.com>",
"msg_from_op": true,
"msg_subject": "Re: Constant Splitting/Refactoring"
},
{
"msg_contents": "On Wed, 13 Mar 2024 at 20:42, David Christensen\n<david.christensen@crunchydata.com> wrote:\n>\n> Here is a version 2 of this patch, rebased atop 97d85be365.\n>\n> As before, this is a cleanup/prerequisite patch series for the page\n> features/reserved page size patches[1]. (Said patch series is going\n> to be updated shortly.)\n>\n> This splits each of the 4 constants that care about page size into\n> Cluster-specific and -Limit variants, the first intended to become a\n> variable in time, and the second being the maximum value such a\n> variable may take (largely used for static\n> allocations).\n>\n> Since these patches define these symbols to have the same values they\n> previously had, there are no changes in functionality. These were\n> largely mechanical changes, and as such we should perhaps consider\n> making the same changes to back-branches to make it so context lines\n> and the like\n> would be the same, simplifying maintainer's efforts when applying code\n> in back branches that touch similar areas.\n>\n> The script I have to make these changes is simple, and could be run\n> against the back branches with only the comments surrounding Calc()\n> pieces needing\n> to be adjusted once.\n>\n> Thanks,\n>\n> David\n>\n> [1] https://commitfest.postgresql.org/47/3986/\n\nHi! Your patchset needs a rebase. Are you going to push it forward?\n\nAlso, It is better to have more informative commit messages in patches.\n-- \nBest regards,\nKirill Reshke\n\n\n",
"msg_date": "Sat, 10 Aug 2024 17:26:01 +0500",
"msg_from": "Kirill Reshke <reshkekirill@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Constant Splitting/Refactoring"
}
] |
[
{
"msg_contents": "Hello,\n\nWe recently noticed some behavior that seems reasonable but also\nsurprised our engineers based on the docs.\n\nIf we have this setup:\ncreate table items(i int);\ninsert into items(i) values (1);\ncreate publication test_pub for all tables;\n\nThen when we:\ndelete from items where i = 1;\n\nwe get:\nERROR: cannot delete from table \"items\" because it does not have a\nreplica identity and publishes deletes\nHINT: To enable deleting from the table, set REPLICA IDENTITY using\nALTER TABLE.\n\nFair enough. But if we do this:\nalter table items replica identity nothing;\n\nbecause the docs [1] say that NOTHING means \"Records no information\nabout the old row.\" We still get the same error when we try the DELETE\nagain.\n\nThe publication docs [2] say \"A published table must have a replica\nidentity configured in order to be able to replicate UPDATE and DELETE\noperations, so that appropriate rows to update or delete can be\nidentified on the subscriber side.\"\n\nWe interpreted the intersection of these two docs to imply that if you\nexplicitly configured NOTHING that the publication would simply not\nlog anything about the original row. Part of the confusion I think was\nfed by reading \"must have a replica identity set\" as \"have selected\none of the options via ALTER TABLE REPLICA IDENTITY\" -- i.e., as\nmeaning that a setting has been configured rather than being about a\nsubset of those possible configuration values/a specific key existing\non the table.\n\nI'm wondering if this might be a surprise to anyone else, and if so,\nis there a minor docs tweak that might avoid the confusion?\n\nThanks,\nJames Coleman\n\n1: https://www.postgresql.org/docs/current/sql-altertable.html#SQL-ALTERTABLE-REPLICA-IDENTITY\n2: https://www.postgresql.org/docs/current/logical-replication-publication.html\n\n\n",
"msg_date": "Wed, 7 Feb 2024 15:12:32 -0500",
"msg_from": "James Coleman <jtc331@gmail.com>",
"msg_from_op": true,
"msg_subject": "Question about behavior of deletes with REPLICA IDENTITY NOTHING"
},
{
"msg_contents": "On Wed, 2024-02-07 at 15:12 -0500, James Coleman wrote:\n> We recently noticed some behavior that seems reasonable but also\n> surprised our engineers based on the docs.\n> \n> If we have this setup:\n> create table items(i int);\n> insert into items(i) values (1);\n> create publication test_pub for all tables;\n> \n> Then when we:\n> delete from items where i = 1;\n> \n> we get:\n> ERROR: cannot delete from table \"items\" because it does not have a\n> replica identity and publishes deletes\n> HINT: To enable deleting from the table, set REPLICA IDENTITY using\n> ALTER TABLE.\n> \n> Fair enough. But if we do this:\n> alter table items replica identity nothing;\n> \n> because the docs [1] say that NOTHING means \"Records no information\n> about the old row.\" We still get the same error when we try the DELETE\n> again.\n\nWell, \"REPLICA IDENTITY NOTHING\" is the same as \"has no replica identity\".\nSo is \"REPLICA IDENTITY DEFAULT\" if there is no primary key, or\n\"REPLICA IDENTITY USING INDEX ...\" if the index is dropped.\n\nSee \"pg_class\": the column \"relreplident\" is not nullable.\n\nYours,\nLaurenz Albe\n\n\n",
"msg_date": "Wed, 07 Feb 2024 21:22:52 +0100",
"msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>",
"msg_from_op": false,
"msg_subject": "Re: Question about behavior of deletes with REPLICA IDENTITY NOTHING"
},
{
"msg_contents": "On Wed, Feb 7, 2024 at 3:22 PM Laurenz Albe <laurenz.albe@cybertec.at> wrote:\n>\n> On Wed, 2024-02-07 at 15:12 -0500, James Coleman wrote:\n> > We recently noticed some behavior that seems reasonable but also\n> > surprised our engineers based on the docs.\n> >\n> > If we have this setup:\n> > create table items(i int);\n> > insert into items(i) values (1);\n> > create publication test_pub for all tables;\n> >\n> > Then when we:\n> > delete from items where i = 1;\n> >\n> > we get:\n> > ERROR: cannot delete from table \"items\" because it does not have a\n> > replica identity and publishes deletes\n> > HINT: To enable deleting from the table, set REPLICA IDENTITY using\n> > ALTER TABLE.\n> >\n> > Fair enough. But if we do this:\n> > alter table items replica identity nothing;\n> >\n> > because the docs [1] say that NOTHING means \"Records no information\n> > about the old row.\" We still get the same error when we try the DELETE\n> > again.\n>\n> Well, \"REPLICA IDENTITY NOTHING\" is the same as \"has no replica identity\".\n> So is \"REPLICA IDENTITY DEFAULT\" if there is no primary key, or\n> \"REPLICA IDENTITY USING INDEX ...\" if the index is dropped.\n>\n> See \"pg_class\": the column \"relreplident\" is not nullable.\n\nRight, I think the confusing point for us is that the docs for NOTHING\n(\"Records no information about the old row\") imply you can decide you\ndon't have to record anything if you don't want to do so, but the\npublication feature is effectively overriding that and asserting that\nyou can't make that choice.\n\nRegards,\nJames Coleman\n\n\n",
"msg_date": "Wed, 7 Feb 2024 17:03:43 -0500",
"msg_from": "James Coleman <jtc331@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Question about behavior of deletes with REPLICA IDENTITY NOTHING"
},
{
"msg_contents": "On Thu, Feb 8, 2024 at 9:04 AM James Coleman <jtc331@gmail.com> wrote:\n>\n> On Wed, Feb 7, 2024 at 3:22 PM Laurenz Albe <laurenz.albe@cybertec.at> wrote:\n> >\n> > On Wed, 2024-02-07 at 15:12 -0500, James Coleman wrote:\n> > > We recently noticed some behavior that seems reasonable but also\n> > > surprised our engineers based on the docs.\n> > >\n> > > If we have this setup:\n> > > create table items(i int);\n> > > insert into items(i) values (1);\n> > > create publication test_pub for all tables;\n> > >\n> > > Then when we:\n> > > delete from items where i = 1;\n> > >\n> > > we get:\n> > > ERROR: cannot delete from table \"items\" because it does not have a\n> > > replica identity and publishes deletes\n> > > HINT: To enable deleting from the table, set REPLICA IDENTITY using\n> > > ALTER TABLE.\n> > >\n> > > Fair enough. But if we do this:\n> > > alter table items replica identity nothing;\n> > >\n> > > because the docs [1] say that NOTHING means \"Records no information\n> > > about the old row.\" We still get the same error when we try the DELETE\n> > > again.\n> >\n> > Well, \"REPLICA IDENTITY NOTHING\" is the same as \"has no replica identity\".\n> > So is \"REPLICA IDENTITY DEFAULT\" if there is no primary key, or\n> > \"REPLICA IDENTITY USING INDEX ...\" if the index is dropped.\n> >\n> > See \"pg_class\": the column \"relreplident\" is not nullable.\n>\n> Right, I think the confusing point for us is that the docs for NOTHING\n> (\"Records no information about the old row\") imply you can decide you\n> don't have to record anything if you don't want to do so, but the\n> publication feature is effectively overriding that and asserting that\n> you can't make that choice.\n>\n\nHi, I can see how the current docs could be interpreted in a way that\nwas not intended.\n\n~~~\n\nTo emphasise the DEFAULT behaviour that Laurenze described, I felt\nthere could be another sentence about DEFAULT, the same as there is\nalready for the USING INDEX case.\n\nBEFORE [1]\nRecords the old values of the columns of the primary key, if any. This\nis the default for non-system tables.\n\nSUGGESTION\nRecords the old values of the columns of the primary key, if any. This\nis the default for non-system tables. If there is no primary key, the\nbehavior is the same as NOTHING.\n\n~~~\n\nIf that is done, then would a publication docs tweak like the one\nbelow clarify things sufficiently?\n\nBEFORE [2]\nIf a table without a replica identity is added to a publication that\nreplicates UPDATE or DELETE operations then subsequent UPDATE or\nDELETE operations will cause an error on the publisher.\n\nSUGGESTION\nIf a table without a replica identity (or with replica identity\nbehavior equivalent to NOTHING) is added to a publication that\nreplicates UPDATE or DELETE operations then subsequent UPDATE or\nDELETE operations will cause an error on the publisher.\n\n======\n[1] https://www.postgresql.org/docs/current/sql-altertable.html#SQL-ALTERTABLE-REPLICA-IDENTITY\n[2] https://www.postgresql.org/docs/current/logical-replication-publication.html\n\nKind Regards,\nPeter Smith.\nFujitsu Australia\n\n\n",
"msg_date": "Thu, 8 Feb 2024 10:04:16 +1100",
"msg_from": "Peter Smith <smithpb2250@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Question about behavior of deletes with REPLICA IDENTITY NOTHING"
},
{
"msg_contents": "On Wed, Feb 7, 2024 at 6:04 PM Peter Smith <smithpb2250@gmail.com> wrote:\n>\n> On Thu, Feb 8, 2024 at 9:04 AM James Coleman <jtc331@gmail.com> wrote:\n> >\n> > On Wed, Feb 7, 2024 at 3:22 PM Laurenz Albe <laurenz.albe@cybertec.at> wrote:\n> > >\n> > > On Wed, 2024-02-07 at 15:12 -0500, James Coleman wrote:\n> > > > We recently noticed some behavior that seems reasonable but also\n> > > > surprised our engineers based on the docs.\n> > > >\n> > > > If we have this setup:\n> > > > create table items(i int);\n> > > > insert into items(i) values (1);\n> > > > create publication test_pub for all tables;\n> > > >\n> > > > Then when we:\n> > > > delete from items where i = 1;\n> > > >\n> > > > we get:\n> > > > ERROR: cannot delete from table \"items\" because it does not have a\n> > > > replica identity and publishes deletes\n> > > > HINT: To enable deleting from the table, set REPLICA IDENTITY using\n> > > > ALTER TABLE.\n> > > >\n> > > > Fair enough. But if we do this:\n> > > > alter table items replica identity nothing;\n> > > >\n> > > > because the docs [1] say that NOTHING means \"Records no information\n> > > > about the old row.\" We still get the same error when we try the DELETE\n> > > > again.\n> > >\n> > > Well, \"REPLICA IDENTITY NOTHING\" is the same as \"has no replica identity\".\n> > > So is \"REPLICA IDENTITY DEFAULT\" if there is no primary key, or\n> > > \"REPLICA IDENTITY USING INDEX ...\" if the index is dropped.\n> > >\n> > > See \"pg_class\": the column \"relreplident\" is not nullable.\n> >\n> > Right, I think the confusing point for us is that the docs for NOTHING\n> > (\"Records no information about the old row\") imply you can decide you\n> > don't have to record anything if you don't want to do so, but the\n> > publication feature is effectively overriding that and asserting that\n> > you can't make that choice.\n> >\n>\n> Hi, I can see how the current docs could be interpreted in a way that\n> was not intended.\n>\n> ~~~\n>\n> To emphasise the DEFAULT behaviour that Laurenze described, I felt\n> there could be another sentence about DEFAULT, the same as there is\n> already for the USING INDEX case.\n>\n> BEFORE [1]\n> Records the old values of the columns of the primary key, if any. This\n> is the default for non-system tables.\n>\n> SUGGESTION\n> Records the old values of the columns of the primary key, if any. This\n> is the default for non-system tables. If there is no primary key, the\n> behavior is the same as NOTHING.\n>\n> ~~~\n>\n> If that is done, then would a publication docs tweak like the one\n> below clarify things sufficiently?\n>\n> BEFORE [2]\n> If a table without a replica identity is added to a publication that\n> replicates UPDATE or DELETE operations then subsequent UPDATE or\n> DELETE operations will cause an error on the publisher.\n>\n> SUGGESTION\n> If a table without a replica identity (or with replica identity\n> behavior equivalent to NOTHING) is added to a publication that\n> replicates UPDATE or DELETE operations then subsequent UPDATE or\n> DELETE operations will cause an error on the publisher.\n>\n> ======\n> [1] https://www.postgresql.org/docs/current/sql-altertable.html#SQL-ALTERTABLE-REPLICA-IDENTITY\n> [2] https://www.postgresql.org/docs/current/logical-replication-publication.html\n>\n> Kind Regards,\n> Peter Smith.\n> Fujitsu Australia\n\nThanks for looking at this!\n\nYes, both of those changes together would make this unambiguous (and,\nI think, easier to mentally parse).\n\nThanks,\nJames Coleman\n\n\n",
"msg_date": "Wed, 7 Feb 2024 19:12:25 -0500",
"msg_from": "James Coleman <jtc331@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Question about behavior of deletes with REPLICA IDENTITY NOTHING"
},
{
"msg_contents": "On Thu, Feb 8, 2024 at 11:12 AM James Coleman <jtc331@gmail.com> wrote:\n>\n> On Wed, Feb 7, 2024 at 6:04 PM Peter Smith <smithpb2250@gmail.com> wrote:\n> >\n> > On Thu, Feb 8, 2024 at 9:04 AM James Coleman <jtc331@gmail.com> wrote:\n> > >\n> > > On Wed, Feb 7, 2024 at 3:22 PM Laurenz Albe <laurenz.albe@cybertec.at> wrote:\n> > > >\n> > > > On Wed, 2024-02-07 at 15:12 -0500, James Coleman wrote:\n> > > > > We recently noticed some behavior that seems reasonable but also\n> > > > > surprised our engineers based on the docs.\n> > > > >\n> > > > > If we have this setup:\n> > > > > create table items(i int);\n> > > > > insert into items(i) values (1);\n> > > > > create publication test_pub for all tables;\n> > > > >\n> > > > > Then when we:\n> > > > > delete from items where i = 1;\n> > > > >\n> > > > > we get:\n> > > > > ERROR: cannot delete from table \"items\" because it does not have a\n> > > > > replica identity and publishes deletes\n> > > > > HINT: To enable deleting from the table, set REPLICA IDENTITY using\n> > > > > ALTER TABLE.\n> > > > >\n> > > > > Fair enough. But if we do this:\n> > > > > alter table items replica identity nothing;\n> > > > >\n> > > > > because the docs [1] say that NOTHING means \"Records no information\n> > > > > about the old row.\" We still get the same error when we try the DELETE\n> > > > > again.\n> > > >\n> > > > Well, \"REPLICA IDENTITY NOTHING\" is the same as \"has no replica identity\".\n> > > > So is \"REPLICA IDENTITY DEFAULT\" if there is no primary key, or\n> > > > \"REPLICA IDENTITY USING INDEX ...\" if the index is dropped.\n> > > >\n> > > > See \"pg_class\": the column \"relreplident\" is not nullable.\n> > >\n> > > Right, I think the confusing point for us is that the docs for NOTHING\n> > > (\"Records no information about the old row\") imply you can decide you\n> > > don't have to record anything if you don't want to do so, but the\n> > > publication feature is effectively overriding that and asserting that\n> > > you can't make that choice.\n> > >\n> >\n> > Hi, I can see how the current docs could be interpreted in a way that\n> > was not intended.\n> >\n> > ~~~\n> >\n> > To emphasise the DEFAULT behaviour that Laurenze described, I felt\n> > there could be another sentence about DEFAULT, the same as there is\n> > already for the USING INDEX case.\n> >\n> > BEFORE [1]\n> > Records the old values of the columns of the primary key, if any. This\n> > is the default for non-system tables.\n> >\n> > SUGGESTION\n> > Records the old values of the columns of the primary key, if any. This\n> > is the default for non-system tables. If there is no primary key, the\n> > behavior is the same as NOTHING.\n> >\n> > ~~~\n> >\n> > If that is done, then would a publication docs tweak like the one\n> > below clarify things sufficiently?\n> >\n> > BEFORE [2]\n> > If a table without a replica identity is added to a publication that\n> > replicates UPDATE or DELETE operations then subsequent UPDATE or\n> > DELETE operations will cause an error on the publisher.\n> >\n> > SUGGESTION\n> > If a table without a replica identity (or with replica identity\n> > behavior equivalent to NOTHING) is added to a publication that\n> > replicates UPDATE or DELETE operations then subsequent UPDATE or\n> > DELETE operations will cause an error on the publisher.\n> >\n> > ======\n> > [1] https://www.postgresql.org/docs/current/sql-altertable.html#SQL-ALTERTABLE-REPLICA-IDENTITY\n> > [2] https://www.postgresql.org/docs/current/logical-replication-publication.html\n> >\n> > Kind Regards,\n> > Peter Smith.\n> > Fujitsu Australia\n>\n> Thanks for looking at this!\n>\n> Yes, both of those changes together would make this unambiguous (and,\n> I think, easier to mentally parse).\n>\n\nOK, here then is a patch to do like that.\n\n======\nKind Regards,\nPeter Smith.\nFujitsu Australia",
"msg_date": "Thu, 8 Feb 2024 13:40:33 +1100",
"msg_from": "Peter Smith <smithpb2250@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Question about behavior of deletes with REPLICA IDENTITY NOTHING"
},
{
"msg_contents": "On Thu, 2024-02-08 at 13:40 +1100, Peter Smith wrote:\n> - how to set the replica identity. If a table without a replica identity is\n> + how to set the replica identity. If a table without a replica identity\n> + (or with replica identity behavior the same as <literal>NOTHING</literal>) is\n> added to a publication that replicates <command>UPDATE</command>\n> or <command>DELETE</command> operations then\n> subsequent <command>UPDATE</command> or <command>DELETE</command>\n\nI had the impression that the root of the confusion was the perceived difference\nbetween \"REPLICA IDENTITY NOTHING\" and \"no replica identity\", and that change\ndoesn't improve that.\n\nHow about:\n\n If a table without a replica identity (explicitly set to <literal>NOTHING</literal>,\n or set to a primary key or index that doesn't exist) is added ...\n\n\nYours,\nLaurenz Albe\n\n\n",
"msg_date": "Thu, 08 Feb 2024 05:27:33 +0100",
"msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>",
"msg_from_op": false,
"msg_subject": "Re: Question about behavior of deletes with REPLICA IDENTITY NOTHING"
},
{
"msg_contents": "On Thu, Feb 8, 2024 at 9:57 AM Laurenz Albe <laurenz.albe@cybertec.at> wrote:\n>\n> On Thu, 2024-02-08 at 13:40 +1100, Peter Smith wrote:\n> > - how to set the replica identity. If a table without a replica identity is\n> > + how to set the replica identity. If a table without a replica identity\n> > + (or with replica identity behavior the same as <literal>NOTHING</literal>) is\n> > added to a publication that replicates <command>UPDATE</command>\n> > or <command>DELETE</command> operations then\n> > subsequent <command>UPDATE</command> or <command>DELETE</command>\n>\n> I had the impression that the root of the confusion was the perceived difference\n> between \"REPLICA IDENTITY NOTHING\" and \"no replica identity\", and that change\n> doesn't improve that.\n>\n> How about:\n>\n> If a table without a replica identity (explicitly set to <literal>NOTHING</literal>,\n> or set to a primary key or index that doesn't exist) is added ...\n\nAnother possibility is just to improve the documentation of various\noptions as follows.\n\nDEFAULT\n\nIf there is a primary key, record the old values of the columns of the\nprimary key. Otherwise it acts as NOTHING. This is the default for\nnon-system tables.\n\nUSING INDEX index_name\n\nRecords the old values of the columns covered by the named index, that\nmust be unique, not partial, not deferrable, and include only columns\nmarked NOT NULL. If this index is dropped, the behavior is the same as\nNOTHING.\n\nFULL\n\nRecords the old values of all columns in the row.\n\nNOTHING\n\nRecords no information about the old row. This is equivalent to having\nno replica identity. This is the default for system tables.\n\n\n-- \nBest Wishes,\nAshutosh Bapat\n\n\n",
"msg_date": "Thu, 8 Feb 2024 15:16:52 +0530",
"msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Question about behavior of deletes with REPLICA IDENTITY NOTHING"
},
{
"msg_contents": "On Wed, Feb 7, 2024 at 11:27 PM Laurenz Albe <laurenz.albe@cybertec.at> wrote:\n>\n> On Thu, 2024-02-08 at 13:40 +1100, Peter Smith wrote:\n> > - how to set the replica identity. If a table without a replica identity is\n> > + how to set the replica identity. If a table without a replica identity\n> > + (or with replica identity behavior the same as <literal>NOTHING</literal>) is\n> > added to a publication that replicates <command>UPDATE</command>\n> > or <command>DELETE</command> operations then\n> > subsequent <command>UPDATE</command> or <command>DELETE</command>\n>\n> I had the impression that the root of the confusion was the perceived difference\n> between \"REPLICA IDENTITY NOTHING\" and \"no replica identity\", and that change\n> doesn't improve that.\n>\n> How about:\n>\n> If a table without a replica identity (explicitly set to <literal>NOTHING</literal>,\n> or set to a primary key or index that doesn't exist) is added ...\n\nI think that would work also. I was reading the initial suggestion as\n\"(or with replica identity behavior the same as...\" as defining what\n\"without a replica identity\" meant, which would avoid the confusion.\nBut your proposal is more explicit and more succinct, so I think it's\nthe better option of the two.\n\nRegards,\nJames Coleman\n\n\n",
"msg_date": "Thu, 8 Feb 2024 08:53:10 -0500",
"msg_from": "James Coleman <jtc331@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Question about behavior of deletes with REPLICA IDENTITY NOTHING"
},
{
"msg_contents": "On Thu, Feb 8, 2024 at 4:47 AM Ashutosh Bapat\n<ashutosh.bapat.oss@gmail.com> wrote:\n>\n> On Thu, Feb 8, 2024 at 9:57 AM Laurenz Albe <laurenz.albe@cybertec.at> wrote:\n> >\n> > On Thu, 2024-02-08 at 13:40 +1100, Peter Smith wrote:\n> > > - how to set the replica identity. If a table without a replica identity is\n> > > + how to set the replica identity. If a table without a replica identity\n> > > + (or with replica identity behavior the same as <literal>NOTHING</literal>) is\n> > > added to a publication that replicates <command>UPDATE</command>\n> > > or <command>DELETE</command> operations then\n> > > subsequent <command>UPDATE</command> or <command>DELETE</command>\n> >\n> > I had the impression that the root of the confusion was the perceived difference\n> > between \"REPLICA IDENTITY NOTHING\" and \"no replica identity\", and that change\n> > doesn't improve that.\n> >\n> > How about:\n> >\n> > If a table without a replica identity (explicitly set to <literal>NOTHING</literal>,\n> > or set to a primary key or index that doesn't exist) is added ...\n>\n> Another possibility is just to improve the documentation of various\n> options as follows.\n>\n> DEFAULT\n>\n> If there is a primary key, record the old values of the columns of the\n> primary key. Otherwise it acts as NOTHING. This is the default for\n> non-system tables.\n>\n> USING INDEX index_name\n>\n> Records the old values of the columns covered by the named index, that\n> must be unique, not partial, not deferrable, and include only columns\n> marked NOT NULL. If this index is dropped, the behavior is the same as\n> NOTHING.\n>\n> FULL\n>\n> Records the old values of all columns in the row.\n>\n> NOTHING\n>\n> Records no information about the old row. This is equivalent to having\n> no replica identity. This is the default for system tables.\n\nThis is the simplest change, and it does solve the confusion, so I'd\nbe happy with it also. The other proposals have the benefit of having\nall the information necessary on the publications page rather than\nrequiring the user to refer to the ALTER TABLE REPLICA IDENTITY page\nto understand what's meant.\n\nRegards,\nJames Coleman\n\n\n",
"msg_date": "Thu, 8 Feb 2024 08:54:32 -0500",
"msg_from": "James Coleman <jtc331@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Question about behavior of deletes with REPLICA IDENTITY NOTHING"
}
] |
[
{
"msg_contents": "Hello,\n\nPlease look at errors, which produced by the following script, starting\nfrom 6566133c5:\nfor i in `seq 100`; do (echo \"CREATE USER u; DROP USER u;\"); done | psql >psql-1.log 2>&1 &\nfor i in `seq 100`; do (echo \"CREATE USER u; DROP USER u;\"); done | psql >psql-2.log 2>&1 &\nwait\n\nERROR: could not find tuple for role 16387\nERROR: could not find tuple for role 16390\nERROR: could not find tuple for role 16394\n...\n\nMaybe these errors are expected, but then I'm confused by the comment in\nDropRole():\n /*\n * Re-find the pg_authid tuple.\n *\n * Since we've taken a lock on the role OID, it shouldn't be possible\n * for the tuple to have been deleted -- or for that matter updated --\n * unless the user is manually modifying the system catalogs.\n */\n tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));\n if (!HeapTupleIsValid(tuple))\n elog(ERROR, \"could not find tuple for role %u\", roleid);\n\nBest regards,\nAlexander\n\n\n",
"msg_date": "Thu, 8 Feb 2024 09:00:01 +0300",
"msg_from": "Alexander Lakhin <exclusion@gmail.com>",
"msg_from_op": true,
"msg_subject": "A comment in DropRole() contradicts the actual behavior"
},
{
"msg_contents": "On Thu, Feb 08, 2024 at 09:00:01AM +0300, Alexander Lakhin wrote:\n> Hello,\n> \n> Please look at errors, which produced by the following script, starting\n> from 6566133c5:\n> for i in `seq 100`; do (echo \"CREATE USER u; DROP USER u;\"); done | psql >psql-1.log 2>&1 &\n> for i in `seq 100`; do (echo \"CREATE USER u; DROP USER u;\"); done | psql >psql-2.log 2>&1 &\n> wait\n> \n> ERROR: could not find tuple for role 16387\n> ERROR: could not find tuple for role 16390\n> ERROR: could not find tuple for role 16394\n> ...\n> \n> Maybe these errors are expected, but then I'm confused by the comment in\n> DropRole():\n\nWell, these errors should never happen, IMHO, so it seems to me that\nthe comment is right and that the code lacks locking, contrary to what\nthe comment tells.\n--\nMichael",
"msg_date": "Thu, 8 Feb 2024 16:39:23 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: A comment in DropRole() contradicts the actual behavior"
},
{
"msg_contents": "At Thu, 8 Feb 2024 16:39:23 +0900, Michael Paquier <michael@paquier.xyz> wrote in \n> On Thu, Feb 08, 2024 at 09:00:01AM +0300, Alexander Lakhin wrote:\n> > Hello,\n> > \n> > Please look at errors, which produced by the following script, starting\n> > from 6566133c5:\n> > for i in `seq 100`; do (echo \"CREATE USER u; DROP USER u;\"); done | psql >psql-1.log 2>&1 &\n> > for i in `seq 100`; do (echo \"CREATE USER u; DROP USER u;\"); done | psql >psql-2.log 2>&1 &\n> > wait\n> > \n> > ERROR: could not find tuple for role 16387\n> > ERROR: could not find tuple for role 16390\n> > ERROR: could not find tuple for role 16394\n> > ...\n> > \n> > Maybe these errors are expected, but then I'm confused by the comment in\n> > DropRole():\n> \n> Well, these errors should never happen, IMHO, so it seems to me that\n> the comment is right and that the code lacks locking, contrary to what\n> the comment tells.\n\nThe function acquires a lock, but it does not perform an existence\ncheck until it first attempts to fetch the tuple, believing in its\npresence. However, I doubt performing an additional existence check\nright after acquiring the lock is worthwhile.\n\nBy the way, I saw the following error with the provided script:\n\n> ERROR: duplicate key value violates unique constraint \"pg_authid_rolname_index\"\n> DETAIL: Key (rolname)=(u) already exists.\n> STATEMENT: CREATE USER u;\n\nThis seems to be another instance of a similar thinko.\n\nI vaguely think that we should just regard the absence as a concurrent\ndrop and either adjust or remove the message, then fix the\ncomment. The situation is slightly different for the duplication\ncase. We shouldn't ignore it but rather need to adjust the error\nmessage. As long as these behaviors don't lead to inconsistencies.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n",
"msg_date": "Thu, 08 Feb 2024 17:43:17 +0900 (JST)",
"msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: A comment in DropRole() contradicts the actual behavior"
}
] |
[
{
"msg_contents": "With the makefile rules, the output of genbki.pl was written to\nsrc/backend/catalog/, and then the header files were linked to\nsrc/include/catalog/.\n\nThis patch changes it so that the output files are written directly to\nsrc/include/catalog/. This makes the logic simpler, and it also makes\nthe behavior consistent with the meson build system. For example, a \nfile like schemapg.h is now mentioned only in\n\nsrc/include/catalog/{meson.build,Makefile,.gitignore}\n\nwhere before it was mentioned in (checks ...)\n\nsrc/backend/catalog/.gitignore\nsrc/backend/catalog/Makefile\nsrc/include/Makefile\nsrc/include/catalog/.gitignore\nsrc/include/catalog/meson.build\n\nAlso, the list of catalog files is now kept in parallel in\nsrc/include/catalog/{meson.build,Makefile}, while before the makefiles\nhad it in src/backend/catalog/Makefile.\n\nI think keeping the two build systems aligned this way will be useful \nfor longer-term maintenance.\n\n(There are other generated header files that are linked in a similar way \nand could perhaps be simplified. But they don't all work the same way. \nSome of the scripts also generate .c files, for example, so they need to \nput some stuff under src/backend/. So I restricted this patch to \nsrc/{backend,include}/catalog/, especially because it would be good to \nkeep the catalog lists aligned.)",
"msg_date": "Thu, 8 Feb 2024 08:58:53 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Put genbki.pl output into src/include/catalog/ directly"
},
{
"msg_contents": "Peter Eisentraut <peter@eisentraut.org> writes:\n> With the makefile rules, the output of genbki.pl was written to\n> src/backend/catalog/, and then the header files were linked to\n> src/include/catalog/.\n\n> This patch changes it so that the output files are written directly to\n> src/include/catalog/.\n\nDidn't read the patch, but +1 for concept.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Thu, 08 Feb 2024 11:38:02 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Put genbki.pl output into src/include/catalog/ directly"
},
{
"msg_contents": "On 2/8/24 8:58 AM, Peter Eisentraut wrote:\n> I think keeping the two build systems aligned this way will be useful \n> for longer-term maintenance.\n\nAgreed, so started reviewing the patch. Attached is a rebased version of \nthe patch to solve a conflict.\n\nAndreas",
"msg_date": "Wed, 13 Mar 2024 12:41:56 +0100",
"msg_from": "Andreas Karlsson <andreas@proxel.se>",
"msg_from_op": false,
"msg_subject": "Re: Put genbki.pl output into src/include/catalog/ directly"
},
{
"msg_contents": "On 3/13/24 12:41 PM, Andreas Karlsson wrote:\n> On 2/8/24 8:58 AM, Peter Eisentraut wrote:\n>> I think keeping the two build systems aligned this way will be useful \n>> for longer-term maintenance.\n> \n> Agreed, so started reviewing the patch. Attached is a rebased version of \n> the patch to solve a conflict.\n\nI have reviewed the patch now and would say it looks good. I like how we \nremove the symlinks plus make things more similar to the meson build so \nI think we should merge this.\n\nI tried building, running tests, running make clean, running make \ninstall and tried building with meson (plus checking that meson really \nchecks for the generated files and actually refuse to build). Everything \nworked as expected.\n\nThe code changes look clean and mostly consist of moving code. I \npersonally think this is ready for committer.\n\nAndreas\n\n\n",
"msg_date": "Thu, 14 Mar 2024 02:33:35 +0100",
"msg_from": "Andreas Karlsson <andreas@proxel.se>",
"msg_from_op": false,
"msg_subject": "Re: Put genbki.pl output into src/include/catalog/ directly"
},
{
"msg_contents": "On 14.03.24 02:33, Andreas Karlsson wrote:\n> On 3/13/24 12:41 PM, Andreas Karlsson wrote:\n>> On 2/8/24 8:58 AM, Peter Eisentraut wrote:\n>>> I think keeping the two build systems aligned this way will be useful \n>>> for longer-term maintenance.\n>>\n>> Agreed, so started reviewing the patch. Attached is a rebased version \n>> of the patch to solve a conflict.\n> \n> I have reviewed the patch now and would say it looks good. I like how we \n> remove the symlinks plus make things more similar to the meson build so \n> I think we should merge this.\n> \n> I tried building, running tests, running make clean, running make \n> install and tried building with meson (plus checking that meson really \n> checks for the generated files and actually refuse to build). Everything \n> worked as expected.\n> \n> The code changes look clean and mostly consist of moving code. I \n> personally think this is ready for committer.\n\nCommitted, thanks.\n\n\n\n",
"msg_date": "Thu, 14 Mar 2024 07:27:40 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: Put genbki.pl output into src/include/catalog/ directly"
}
] |
[
{
"msg_contents": "HI hackers\n When I read this text in this document there is a paragraph in it(\nhttps://www.interdb.jp/pg/pgsql08/03.html)\n/*\nThe BufMappingLock is split into partitions to reduce contention in the\nbuffer table (the default is 128 partitions). Each BufMappingLock partition\nguards a portion of the corresponding hash bucket slots.\n*/,\n\nPhysical servers with terabytes of RAM are now commonplace,I'm looking at\nthe comments inside the source code.I'm looking at the comments inside the\nsource code to see if they still match the current hardware capability? The\n comment says that in the future there may be a parameter,Iam a dba now\nand I try to think of implementing this parameter, but I'm not a\nprofessional kernel developer, I still want the community senior developer\nto implement this parameter\n\n/*\n * It's a bit odd to declare NUM_BUFFER_PARTITIONS and NUM_LOCK_PARTITIONS\n * here, but we need them to figure out offsets within MainLWLockArray, and\n * having this file include lock.h or bufmgr.h would be backwards.\n */\n\n/* Number of partitions of the shared buffer mapping hashtable */\n#define NUM_BUFFER_PARTITIONS 128\n\n/*\n * The number of partitions for locking purposes. This is set to match\n * NUM_BUFFER_PARTITIONS for now, on the basis that whatever's good enough\nfor\n * the buffer pool must be good enough for any other purpose. This could\n * become a runtime parameter in future.\n */\n#define DSHASH_NUM_PARTITIONS_LOG2 7\n#define DSHASH_NUM_PARTITIONS (1 << DSHASH_NUM_PARTITIONS_LOG2)\n\nHI hackers When I read this text in this document there is a paragraph in it(https://www.interdb.jp/pg/pgsql08/03.html)/*The BufMappingLock is split into partitions to reduce contention in the buffer table (the default is 128 partitions). Each BufMappingLock partition guards a portion of the corresponding hash bucket slots.*/,Physical servers with terabytes of RAM are now commonplace,I'm looking at the comments inside the source code.I'm looking at the comments inside the source code to see if they still match the current hardware capability? The comment says that in the future there may be a parameter,Iam a dba now and I try to think of implementing this parameter, but I'm not a professional kernel developer, I still want the community senior developer to implement this parameter/* * It's a bit odd to declare NUM_BUFFER_PARTITIONS and NUM_LOCK_PARTITIONS * here, but we need them to figure out offsets within MainLWLockArray, and * having this file include lock.h or bufmgr.h would be backwards. *//* Number of partitions of the shared buffer mapping hashtable */#define NUM_BUFFER_PARTITIONS 128/* * The number of partitions for locking purposes. This is set to match * NUM_BUFFER_PARTITIONS for now, on the basis that whatever's good enough for * the buffer pool must be good enough for any other purpose. This could * become a runtime parameter in future. */#define DSHASH_NUM_PARTITIONS_LOG2 7#define DSHASH_NUM_PARTITIONS (1 << DSHASH_NUM_PARTITIONS_LOG2)",
"msg_date": "Thu, 8 Feb 2024 18:17:36 +0800",
"msg_from": "wenhui qiu <qiuwenhuifx@gmail.com>",
"msg_from_op": true,
"msg_subject": "Thoughts about NUM_BUFFER_PARTITIONS"
},
{
"msg_contents": "On 08/02/2024 12:17, wenhui qiu wrote:\n> HI hackers\n> When I read this text in this document there is a paragraph in \n> it(https://www.interdb.jp/pg/pgsql08/03.html \n> <https://www.interdb.jp/pg/pgsql08/03.html>)\n> /*\n> The BufMappingLock is split into partitions to reduce contention in the \n> buffer table (the default is 128 partitions). Each BufMappingLock \n> partition guards a portion of the corresponding hash bucket slots.\n> */,\n> \n> Physical servers with terabytes of RAM are now commonplace,I'm looking \n> at the comments inside the source code.I'm looking at the comments \n> inside the source code to see if they still match the current hardware \n> capability?\n\nThe optimal number of partitions has more to do with the number of \nconcurrent processes using the buffer cache, rather than the size of the \ncache. The number of CPUs in servers has increased too, but not as much \nas RAM.\n\nBut yeah, it's a valid question if the settings still make sense with \nmodern hardware.\n\n> The comment says that in the future there may be a \n> parameter,Iam a dba now and I try to think of implementing this \n> parameter, but I'm not a professional kernel developer, I still want the \n> community senior developer to implement this parameter\n\nThe first thing to do would be to benchmark with different \nNUM_BUFFER_PARTITIONS settings, and see if there's benefit in having \nmore partitions.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)\n\n\n\n",
"msg_date": "Thu, 8 Feb 2024 13:26:42 +0200",
"msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>",
"msg_from_op": false,
"msg_subject": "Re: Thoughts about NUM_BUFFER_PARTITIONS"
},
{
"msg_contents": "Hi Heikki Linnakangas\n I think the larger shared buffer higher the probability of multiple\nbackend processes accessing the same bucket slot BufMappingLock\nsimultaneously, ( InitBufTable(NBuffers + NUM_BUFFER_PARTITIONS); When I\nhave free time, I want to do this test. I have seen some tests, but the\nresult report is in Chinese\n\n\nBest wishes\n\nHeikki Linnakangas <hlinnaka@iki.fi> 于2024年2月8日周四 19:26写道:\n\n> On 08/02/2024 12:17, wenhui qiu wrote:\n> > HI hackers\n> > When I read this text in this document there is a paragraph in\n> > it(https://www.interdb.jp/pg/pgsql08/03.html\n> > <https://www.interdb.jp/pg/pgsql08/03.html>)\n> > /*\n> > The BufMappingLock is split into partitions to reduce contention in the\n> > buffer table (the default is 128 partitions). Each BufMappingLock\n> > partition guards a portion of the corresponding hash bucket slots.\n> > */,\n> >\n> > Physical servers with terabytes of RAM are now commonplace,I'm looking\n> > at the comments inside the source code.I'm looking at the comments\n> > inside the source code to see if they still match the current hardware\n> > capability?\n>\n> The optimal number of partitions has more to do with the number of\n> concurrent processes using the buffer cache, rather than the size of the\n> cache. The number of CPUs in servers has increased too, but not as much\n> as RAM.\n>\n> But yeah, it's a valid question if the settings still make sense with\n> modern hardware.\n>\n> > The comment says that in the future there may be a\n> > parameter,Iam a dba now and I try to think of implementing this\n> > parameter, but I'm not a professional kernel developer, I still want the\n> > community senior developer to implement this parameter\n>\n> The first thing to do would be to benchmark with different\n> NUM_BUFFER_PARTITIONS settings, and see if there's benefit in having\n> more partitions.\n>\n> --\n> Heikki Linnakangas\n> Neon (https://neon.tech)\n>\n>\n\nHi Heikki Linnakangas I think the larger shared buffer higher the probability of multiple backend processes accessing the same bucket slot BufMappingLock simultaneously, (\n\n InitBufTable(NBuffers + NUM_BUFFER_PARTITIONS); When I have free time, I want to do this test. I have seen some tests, but the result report is in ChineseBest wishesHeikki Linnakangas <hlinnaka@iki.fi> 于2024年2月8日周四 19:26写道:On 08/02/2024 12:17, wenhui qiu wrote:\n> HI hackers\n> When I read this text in this document there is a paragraph in \n> it(https://www.interdb.jp/pg/pgsql08/03.html \n> <https://www.interdb.jp/pg/pgsql08/03.html>)\n> /*\n> The BufMappingLock is split into partitions to reduce contention in the \n> buffer table (the default is 128 partitions). Each BufMappingLock \n> partition guards a portion of the corresponding hash bucket slots.\n> */,\n> \n> Physical servers with terabytes of RAM are now commonplace,I'm looking \n> at the comments inside the source code.I'm looking at the comments \n> inside the source code to see if they still match the current hardware \n> capability?\n\nThe optimal number of partitions has more to do with the number of \nconcurrent processes using the buffer cache, rather than the size of the \ncache. The number of CPUs in servers has increased too, but not as much \nas RAM.\n\nBut yeah, it's a valid question if the settings still make sense with \nmodern hardware.\n\n> The comment says that in the future there may be a \n> parameter,Iam a dba now and I try to think of implementing this \n> parameter, but I'm not a professional kernel developer, I still want the \n> community senior developer to implement this parameter\n\nThe first thing to do would be to benchmark with different \nNUM_BUFFER_PARTITIONS settings, and see if there's benefit in having \nmore partitions.\n\n-- \nHeikki Linnakangas\nNeon (https://neon.tech)",
"msg_date": "Thu, 8 Feb 2024 21:27:36 +0800",
"msg_from": "wenhui qiu <qiuwenhuifx@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Thoughts about NUM_BUFFER_PARTITIONS"
},
{
"msg_contents": "On 2/8/24 14:27, wenhui qiu wrote:\n> Hi Heikki Linnakangas\n> I think the larger shared buffer higher the probability of multiple\n> backend processes accessing the same bucket slot BufMappingLock\n> simultaneously, ( InitBufTable(NBuffers + NUM_BUFFER_PARTITIONS); When I\n> have free time, I want to do this test. I have seen some tests, but the\n> result report is in Chinese\n> \n\nI think Heikki is right this is unrelated to the amount of RAM. The\npartitions are meant to reduce the number of lock collisions when\nmultiple processes try to map a buffer concurrently. But the machines\ngot much larger in this regard too - in 2006 the common CPUs had maybe\n2-4 cores, now it's common to have CPUs with ~100 cores, and systems\nwith multiple of them. OTOH the time spent holing the partition lock\nshould be pretty low, IIRC we pretty much just pin the buffer before\nreleasing it, and the backend should do plenty other expensive stuff. So\nwho knows how many backends end up doing the locking at the same time.\n\nOTOH, with 128 partitions it takes just 14 backends to have 50% chance\nof a conflict, so with enough cores ... But how many partitions would be\nenough? With 1024 partitions it still takes only 38 backends to get 50%\nchance of a collision. Better, but considering we now have hundreds of\ncores, not sure if sufficient.\n\n(Obviously, we probably want much lower probability of a collision, I\nonly used 50% to illustrate the changes).\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n",
"msg_date": "Sat, 10 Feb 2024 13:15:22 +0100",
"msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: Thoughts about NUM_BUFFER_PARTITIONS"
},
{
"msg_contents": "\r\n\r\n> On Feb 10, 2024, at 20:15, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\r\n> \r\n> On 2/8/24 14:27, wenhui qiu wrote:\r\n>> Hi Heikki Linnakangas\r\n>> I think the larger shared buffer higher the probability of multiple\r\n>> backend processes accessing the same bucket slot BufMappingLock\r\n>> simultaneously, ( InitBufTable(NBuffers + NUM_BUFFER_PARTITIONS); When I\r\n>> have free time, I want to do this test. I have seen some tests, but the\r\n>> result report is in Chinese\r\n>> \r\n> \r\n> I think Heikki is right this is unrelated to the amount of RAM. The\r\n> partitions are meant to reduce the number of lock collisions when\r\n> multiple processes try to map a buffer concurrently. But the machines\r\n> got much larger in this regard too - in 2006 the common CPUs had maybe\r\n> 2-4 cores, now it's common to have CPUs with ~100 cores, and systems\r\n> with multiple of them. OTOH the time spent holing the partition lock\r\n> should be pretty low, IIRC we pretty much just pin the buffer before\r\n> releasing it, and the backend should do plenty other expensive stuff. So\r\n> who knows how many backends end up doing the locking at the same time.\r\n> \r\n> OTOH, with 128 partitions it takes just 14 backends to have 50% chance\r\n> of a conflict, so with enough cores ... But how many partitions would be\r\n> enough? With 1024 partitions it still takes only 38 backends to get 50%\r\n> chance of a collision. Better, but considering we now have hundreds of\r\n> cores, not sure if sufficient.\r\n> \r\n> (Obviously, we probably want much lower probability of a collision, I\r\n> only used 50% to illustrate the changes).\r\n> \r\n\r\nI find it seems need to change MAX_SIMUL_LWLOCKS if we enlarge the NUM_BUFFER_PARTITIONS,\r\nI didn’t find any comments to describe the relation between MAX_SIMUL_LWLOCKS and\r\nNUM_BUFFER_PARTITIONS, am I missing someghing?",
"msg_date": "Sun, 18 Feb 2024 02:30:58 +0000",
"msg_from": "Li Japin <japinli@hotmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Thoughts about NUM_BUFFER_PARTITIONS"
},
{
"msg_contents": "On 2/18/24 03:30, Li Japin wrote:\n> \n> \n>> On Feb 10, 2024, at 20:15, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\n>>\n>> On 2/8/24 14:27, wenhui qiu wrote:\n>>> Hi Heikki Linnakangas\n>>> I think the larger shared buffer higher the probability of multiple\n>>> backend processes accessing the same bucket slot BufMappingLock\n>>> simultaneously, ( InitBufTable(NBuffers + NUM_BUFFER_PARTITIONS); When I\n>>> have free time, I want to do this test. I have seen some tests, but the\n>>> result report is in Chinese\n>>>\n>>\n>> I think Heikki is right this is unrelated to the amount of RAM. The\n>> partitions are meant to reduce the number of lock collisions when\n>> multiple processes try to map a buffer concurrently. But the machines\n>> got much larger in this regard too - in 2006 the common CPUs had maybe\n>> 2-4 cores, now it's common to have CPUs with ~100 cores, and systems\n>> with multiple of them. OTOH the time spent holing the partition lock\n>> should be pretty low, IIRC we pretty much just pin the buffer before\n>> releasing it, and the backend should do plenty other expensive stuff. So\n>> who knows how many backends end up doing the locking at the same time.\n>>\n>> OTOH, with 128 partitions it takes just 14 backends to have 50% chance\n>> of a conflict, so with enough cores ... But how many partitions would be\n>> enough? With 1024 partitions it still takes only 38 backends to get 50%\n>> chance of a collision. Better, but considering we now have hundreds of\n>> cores, not sure if sufficient.\n>>\n>> (Obviously, we probably want much lower probability of a collision, I\n>> only used 50% to illustrate the changes).\n>>\n> \n> I find it seems need to change MAX_SIMUL_LWLOCKS if we enlarge the NUM_BUFFER_PARTITIONS,\n> I didn’t find any comments to describe the relation between MAX_SIMUL_LWLOCKS and\n> NUM_BUFFER_PARTITIONS, am I missing someghing?\n\nIMHO the relationship is pretty simple - MAX_SIMUL_LWLOCKS needs to be\nhigher than NUM_BUFFER_PARTITIONS, so that the backend can acquire all\nthe partition locks if needed.\n\nThere's other places that acquire a bunch of locks, and all of them need\nto be careful not to exceed MAX_SIMUL_LWLOCKS. For example gist has\nGIST_MAX_SPLIT_PAGES.\n\n\nregards\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n",
"msg_date": "Sun, 18 Feb 2024 17:56:58 +0100",
"msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: Thoughts about NUM_BUFFER_PARTITIONS"
},
{
"msg_contents": "\nOn Mon, 19 Feb 2024 at 00:56, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\n> On 2/18/24 03:30, Li Japin wrote:\n>>\n>> I find it seems need to change MAX_SIMUL_LWLOCKS if we enlarge the NUM_BUFFER_PARTITIONS,\n>> I didn’t find any comments to describe the relation between MAX_SIMUL_LWLOCKS and\n>> NUM_BUFFER_PARTITIONS, am I missing someghing?\n>\n> IMHO the relationship is pretty simple - MAX_SIMUL_LWLOCKS needs to be\n> higher than NUM_BUFFER_PARTITIONS, so that the backend can acquire all\n> the partition locks if needed.\n>\n\nThanks for the explanation! Got it.\n\n> There's other places that acquire a bunch of locks, and all of them need\n> to be careful not to exceed MAX_SIMUL_LWLOCKS. For example gist has\n> GIST_MAX_SPLIT_PAGES.\n>\n>\n> regards\n\n\n",
"msg_date": "Mon, 19 Feb 2024 10:26:06 +0800",
"msg_from": "Japin Li <japinli@hotmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Thoughts about NUM_BUFFER_PARTITIONS"
},
{
"msg_contents": "Hi Japlin Li\n Thank you for such important information ! Got it\n\nJapin Li <japinli@hotmail.com> 于2024年2月19日周一 10:26写道:\n\n>\n> On Mon, 19 Feb 2024 at 00:56, Tomas Vondra <tomas.vondra@enterprisedb.com>\n> wrote:\n> > On 2/18/24 03:30, Li Japin wrote:\n> >>\n> >> I find it seems need to change MAX_SIMUL_LWLOCKS if we enlarge the\n> NUM_BUFFER_PARTITIONS,\n> >> I didn’t find any comments to describe the relation between\n> MAX_SIMUL_LWLOCKS and\n> >> NUM_BUFFER_PARTITIONS, am I missing someghing?\n> >\n> > IMHO the relationship is pretty simple - MAX_SIMUL_LWLOCKS needs to be\n> > higher than NUM_BUFFER_PARTITIONS, so that the backend can acquire all\n> > the partition locks if needed.\n> >\n>\n> Thanks for the explanation! Got it.\n>\n> > There's other places that acquire a bunch of locks, and all of them need\n> > to be careful not to exceed MAX_SIMUL_LWLOCKS. For example gist has\n> > GIST_MAX_SPLIT_PAGES.\n> >\n> >\n> > regards\n>\n\nHi Japlin Li Thank you for such important information ! Got it Japin Li <japinli@hotmail.com> 于2024年2月19日周一 10:26写道:\nOn Mon, 19 Feb 2024 at 00:56, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\n> On 2/18/24 03:30, Li Japin wrote:\n>>\n>> I find it seems need to change MAX_SIMUL_LWLOCKS if we enlarge the NUM_BUFFER_PARTITIONS,\n>> I didn’t find any comments to describe the relation between MAX_SIMUL_LWLOCKS and\n>> NUM_BUFFER_PARTITIONS, am I missing someghing?\n>\n> IMHO the relationship is pretty simple - MAX_SIMUL_LWLOCKS needs to be\n> higher than NUM_BUFFER_PARTITIONS, so that the backend can acquire all\n> the partition locks if needed.\n>\n\nThanks for the explanation! Got it.\n\n> There's other places that acquire a bunch of locks, and all of them need\n> to be careful not to exceed MAX_SIMUL_LWLOCKS. For example gist has\n> GIST_MAX_SPLIT_PAGES.\n>\n>\n> regards",
"msg_date": "Tue, 20 Feb 2024 09:36:45 +0800",
"msg_from": "wenhui qiu <qiuwenhuifx@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Thoughts about NUM_BUFFER_PARTITIONS"
},
{
"msg_contents": "Hi Heikki Linnakangas\n I saw git log found this commit:\nhttps://github.com/postgres/postgres/commit/3acc10c997f916f6a741d0b4876126b7b08e3892\n,I don't seem to see an email discussing this commit. As the commit log\ntells us, we don't know exactly how large a value is optimal, and I believe\nit's more flexible to make it as a parameter.Thank you very much\ntomas.vondra for explaining the relationship, i see that MAX_SIMUL_LWLOCKS\nwas just doubled in this commit, is there a more appropriate ratio between\nthem?\n\n\n\n```````````````````````````````````````````````````````````````````````````\ncommit 3acc10c997f916f6a741d0b4876126b7b08e3892\nAuthor: Robert Haas <rhaas@postgresql.org>\nDate: Thu Oct 2 13:58:50 2014 -0400\n\n Increase the number of buffer mapping partitions to 128.\n\n Testing by Amit Kapila, Andres Freund, and myself, with and without\n other patches that also aim to improve scalability, seems to indicate\n that this change is a significant win over the current value and over\n smaller values such as 64. It's not clear how high we can push this\n value before it starts to have negative side-effects elsewhere, but\n going this far looks OK.\n\n`````````````````````````````````````````````````````````\n\nwenhui qiu <qiuwenhuifx@gmail.com> 于2024年2月20日周二 09:36写道:\n\n> Hi Japlin Li\n> Thank you for such important information ! Got it\n>\n> Japin Li <japinli@hotmail.com> 于2024年2月19日周一 10:26写道:\n>\n>>\n>> On Mon, 19 Feb 2024 at 00:56, Tomas Vondra <tomas.vondra@enterprisedb.com>\n>> wrote:\n>> > On 2/18/24 03:30, Li Japin wrote:\n>> >>\n>> >> I find it seems need to change MAX_SIMUL_LWLOCKS if we enlarge the\n>> NUM_BUFFER_PARTITIONS,\n>> >> I didn’t find any comments to describe the relation between\n>> MAX_SIMUL_LWLOCKS and\n>> >> NUM_BUFFER_PARTITIONS, am I missing someghing?\n>> >\n>> > IMHO the relationship is pretty simple - MAX_SIMUL_LWLOCKS needs to be\n>> > higher than NUM_BUFFER_PARTITIONS, so that the backend can acquire all\n>> > the partition locks if needed.\n>> >\n>>\n>> Thanks for the explanation! Got it.\n>>\n>> > There's other places that acquire a bunch of locks, and all of them need\n>> > to be careful not to exceed MAX_SIMUL_LWLOCKS. For example gist has\n>> > GIST_MAX_SPLIT_PAGES.\n>> >\n>> >\n>> > regards\n>>\n>\n\nHi Heikki Linnakangas I saw git log found this commit:https://github.com/postgres/postgres/commit/3acc10c997f916f6a741d0b4876126b7b08e3892 ,I don't seem to see an email discussing this commit. As the commit log tells us, we don't know exactly how large a value is optimal, and I believe it's more flexible to make it as a parameter.Thank you very much tomas.vondra for explaining the relationship, i see that MAX_SIMUL_LWLOCKS was just doubled in this commit, is there a more appropriate ratio between them?```````````````````````````````````````````````````````````````````````````commit 3acc10c997f916f6a741d0b4876126b7b08e3892Author: Robert Haas <rhaas@postgresql.org>Date: Thu Oct 2 13:58:50 2014 -0400 Increase the number of buffer mapping partitions to 128. Testing by Amit Kapila, Andres Freund, and myself, with and without other patches that also aim to improve scalability, seems to indicate that this change is a significant win over the current value and over smaller values such as 64. It's not clear how high we can push this value before it starts to have negative side-effects elsewhere, but going this far looks OK.`````````````````````````````````````````````````````````wenhui qiu <qiuwenhuifx@gmail.com> 于2024年2月20日周二 09:36写道:Hi Japlin Li Thank you for such important information ! Got it Japin Li <japinli@hotmail.com> 于2024年2月19日周一 10:26写道:\nOn Mon, 19 Feb 2024 at 00:56, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\n> On 2/18/24 03:30, Li Japin wrote:\n>>\n>> I find it seems need to change MAX_SIMUL_LWLOCKS if we enlarge the NUM_BUFFER_PARTITIONS,\n>> I didn’t find any comments to describe the relation between MAX_SIMUL_LWLOCKS and\n>> NUM_BUFFER_PARTITIONS, am I missing someghing?\n>\n> IMHO the relationship is pretty simple - MAX_SIMUL_LWLOCKS needs to be\n> higher than NUM_BUFFER_PARTITIONS, so that the backend can acquire all\n> the partition locks if needed.\n>\n\nThanks for the explanation! Got it.\n\n> There's other places that acquire a bunch of locks, and all of them need\n> to be careful not to exceed MAX_SIMUL_LWLOCKS. For example gist has\n> GIST_MAX_SPLIT_PAGES.\n>\n>\n> regards",
"msg_date": "Tue, 20 Feb 2024 10:16:00 +0800",
"msg_from": "wenhui qiu <qiuwenhuifx@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Thoughts about NUM_BUFFER_PARTITIONS"
},
{
"msg_contents": "Hi,\n\nOn 2/20/24 03:16, wenhui qiu wrote:\n> Hi Heikki Linnakangas\n> I saw git log found this commit:\n> https://github.com/postgres/postgres/commit/3acc10c997f916f6a741d0b4876126b7b08e3892\n> ,I don't seem to see an email discussing this commit. As the commit log\n> tells us, we don't know exactly how large a value is optimal, and I believe\n> it's more flexible to make it as a parameter.Thank you very much\n> tomas.vondra for explaining the relationship, i see that MAX_SIMUL_LWLOCKS\n> was just doubled in this commit, is there a more appropriate ratio between\n> them?\n> \n\nI think the discussion for that commit is in [1] (and especially [2]).\n\nThat being said, I don't think MAX_SIMUL_LOCKS and NUM_BUFFER_PARTITIONS\nneed to be in any particular ratio. The only requirement is that there\nneeds to be enough slack, and 72 locks seemed to work quite fine until\nnow - I don't think we need to change that.\n\nWhat might be necessary is improving held_lwlocks - we treat is as LIFO,\nbut more as an expectation than a hard rule. I'm not sure how often we\nviolate that rule (if at all), but if we do then it's going to get more\nexpensive as we increase the number of locks. But I'm not sure this is\nactually a problem in practice, we usually hold very few LWLocks at the\nsame time.\n\nAs for making this a parameter, I'm rather opposed to the idea. If we\ndon't have a very clear idea how to set this limit, what's the chance\nusers with little knowledge of the internals will pick a good value?\nAdding yet another knob would just mean users start messing with it in\nrandom ways (typically increasing it to very high value, because \"more\nis better\"), causing more harm than good.\n\nAdding it as a GUC would also require making some parts dynamic (instead\nof just doing static allocation with compile-time constants). That's not\ngreat, but I'm not sure how significant the penalty might be.\n\n\nIMHO adding a GUC might be acceptable only if we fail to come up with a\ngood value (which is going to be a trade off), and if someone\ndemonstrates a clear benefit of increasing the value (which I don't\nthink happen in this thread yet).\n\n\nregards\n\n\n[1]\nhttps://www.postgresql.org/message-id/flat/CAA4eK1LSTcMwXNO8ovGh7c0UgCHzGbN%3D%2BPjggfzQDukKr3q_DA%40mail.gmail.com\n\n[2]\nhttps://www.postgresql.org/message-id/CA%2BTgmoY58dQi8Z%3DFDAu4ggxHV-HYV03-R9on1LSP9OJU_fy_zA%40mail.gmail.com\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n",
"msg_date": "Tue, 20 Feb 2024 14:55:25 +0100",
"msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: Thoughts about NUM_BUFFER_PARTITIONS"
},
{
"msg_contents": "Hi Tomas Vondra\n Thanks for the information! But I found postgres pro enterprise\nversion has been implemented ,However, it defaults to 16 and maxes out at\n128, and the maxes are the same as in PostgreSQL.I kindly hope that if the\ndevelopers can explain what the purpose of this is.May be 128 partitions is\nthe optimal value,It's a parameter to make it easier to adjust the number\nof partitions in the future when it's really not enough. and the code\ncomments also said that hope to implement the parameter in the future\n\n\n( https://postgrespro.com/docs/enterprise/16/runtime-config-locks )\n\n\nlog2_num_lock_partitions (integer) #\n<https://postgrespro.com/docs/enterprise/16/runtime-config-locks#GUC-LOG2-NUM-LOCK-PARTITIONS>\n\nThis controls how many partitions the shared lock tables are divided into.\nNumber of partitions is calculated by raising 2 to the power of this\nparameter. The default value is 4, which corresponds to 16 partitions, and\nthe maximum is 8. This parameter can only be set in the postgresql.conf file\nor on the server command line.\n\nBest wish\n\n\nOn Tue, 20 Feb 2024 at 21:55, Tomas Vondra <tomas.vondra@enterprisedb.com>\nwrote:\n\n> Hi,\n>\n> On 2/20/24 03:16, wenhui qiu wrote:\n> > Hi Heikki Linnakangas\n> > I saw git log found this commit:\n> >\n> https://github.com/postgres/postgres/commit/3acc10c997f916f6a741d0b4876126b7b08e3892\n> > ,I don't seem to see an email discussing this commit. As the commit log\n> > tells us, we don't know exactly how large a value is optimal, and I\n> believe\n> > it's more flexible to make it as a parameter.Thank you very much\n> > tomas.vondra for explaining the relationship, i see that\n> MAX_SIMUL_LWLOCKS\n> > was just doubled in this commit, is there a more appropriate ratio\n> between\n> > them?\n> >\n>\n> I think the discussion for that commit is in [1] (and especially [2]).\n>\n> That being said, I don't think MAX_SIMUL_LOCKS and NUM_BUFFER_PARTITIONS\n> need to be in any particular ratio. The only requirement is that there\n> needs to be enough slack, and 72 locks seemed to work quite fine until\n> now - I don't think we need to change that.\n>\n> What might be necessary is improving held_lwlocks - we treat is as LIFO,\n> but more as an expectation than a hard rule. I'm not sure how often we\n> violate that rule (if at all), but if we do then it's going to get more\n> expensive as we increase the number of locks. But I'm not sure this is\n> actually a problem in practice, we usually hold very few LWLocks at the\n> same time.\n>\n> As for making this a parameter, I'm rather opposed to the idea. If we\n> don't have a very clear idea how to set this limit, what's the chance\n> users with little knowledge of the internals will pick a good value?\n> Adding yet another knob would just mean users start messing with it in\n> random ways (typically increasing it to very high value, because \"more\n> is better\"), causing more harm than good.\n>\n> Adding it as a GUC would also require making some parts dynamic (instead\n> of just doing static allocation with compile-time constants). That's not\n> great, but I'm not sure how significant the penalty might be.\n>\n>\n> IMHO adding a GUC might be acceptable only if we fail to come up with a\n> good value (which is going to be a trade off), and if someone\n> demonstrates a clear benefit of increasing the value (which I don't\n> think happen in this thread yet).\n>\n>\n> regards\n>\n>\n> [1]\n>\n> https://www.postgresql.org/message-id/flat/CAA4eK1LSTcMwXNO8ovGh7c0UgCHzGbN%3D%2BPjggfzQDukKr3q_DA%40mail.gmail.com\n>\n> [2]\n>\n> https://www.postgresql.org/message-id/CA%2BTgmoY58dQi8Z%3DFDAu4ggxHV-HYV03-R9on1LSP9OJU_fy_zA%40mail.gmail.com\n>\n> --\n> Tomas Vondra\n> EnterpriseDB: http://www.enterprisedb.com\n> The Enterprise PostgreSQL Company\n>\n\nHi Tomas Vondra Thanks for the information! But I found postgres pro enterprise version has been implemented ,However, it defaults to 16 and maxes out at 128, and the maxes are the same as in PostgreSQL.I kindly hope that if the developers can explain what the purpose of this is.May be 128 partitions is the optimal value,It's a parameter to make it easier to adjust the number of partitions in the future when it's really not enough. and the code comments also said that hope to implement the parameter in the future( https://postgrespro.com/docs/enterprise/16/runtime-config-locks )log2_num_lock_partitions (integer) #This controls how many partitions the shared lock tables are divided into. Number of partitions is calculated by raising 2 to the power of this parameter. The default value is 4, which corresponds to 16 partitions, and the maximum is 8. This parameter can only be set in the postgresql.conf file or on the server command line.Best wish On Tue, 20 Feb 2024 at 21:55, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:Hi,\n\nOn 2/20/24 03:16, wenhui qiu wrote:\n> Hi Heikki Linnakangas\n> I saw git log found this commit:\n> https://github.com/postgres/postgres/commit/3acc10c997f916f6a741d0b4876126b7b08e3892\n> ,I don't seem to see an email discussing this commit. As the commit log\n> tells us, we don't know exactly how large a value is optimal, and I believe\n> it's more flexible to make it as a parameter.Thank you very much\n> tomas.vondra for explaining the relationship, i see that MAX_SIMUL_LWLOCKS\n> was just doubled in this commit, is there a more appropriate ratio between\n> them?\n> \n\nI think the discussion for that commit is in [1] (and especially [2]).\n\nThat being said, I don't think MAX_SIMUL_LOCKS and NUM_BUFFER_PARTITIONS\nneed to be in any particular ratio. The only requirement is that there\nneeds to be enough slack, and 72 locks seemed to work quite fine until\nnow - I don't think we need to change that.\n\nWhat might be necessary is improving held_lwlocks - we treat is as LIFO,\nbut more as an expectation than a hard rule. I'm not sure how often we\nviolate that rule (if at all), but if we do then it's going to get more\nexpensive as we increase the number of locks. But I'm not sure this is\nactually a problem in practice, we usually hold very few LWLocks at the\nsame time.\n\nAs for making this a parameter, I'm rather opposed to the idea. If we\ndon't have a very clear idea how to set this limit, what's the chance\nusers with little knowledge of the internals will pick a good value?\nAdding yet another knob would just mean users start messing with it in\nrandom ways (typically increasing it to very high value, because \"more\nis better\"), causing more harm than good.\n\nAdding it as a GUC would also require making some parts dynamic (instead\nof just doing static allocation with compile-time constants). That's not\ngreat, but I'm not sure how significant the penalty might be.\n\n\nIMHO adding a GUC might be acceptable only if we fail to come up with a\ngood value (which is going to be a trade off), and if someone\ndemonstrates a clear benefit of increasing the value (which I don't\nthink happen in this thread yet).\n\n\nregards\n\n\n[1]\nhttps://www.postgresql.org/message-id/flat/CAA4eK1LSTcMwXNO8ovGh7c0UgCHzGbN%3D%2BPjggfzQDukKr3q_DA%40mail.gmail.com\n\n[2]\nhttps://www.postgresql.org/message-id/CA%2BTgmoY58dQi8Z%3DFDAu4ggxHV-HYV03-R9on1LSP9OJU_fy_zA%40mail.gmail.com\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company",
"msg_date": "Fri, 23 Feb 2024 22:40:22 +0800",
"msg_from": "wenhui qiu <qiuwenhuifx@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Thoughts about NUM_BUFFER_PARTITIONS"
},
{
"msg_contents": "On 2/23/24 15:40, wenhui qiu wrote:\n> Hi Tomas Vondra\n> Thanks for the information! But I found postgres pro enterprise\n> version has been implemented ,However, it defaults to 16 and maxes out at\n> 128, and the maxes are the same as in PostgreSQL.I kindly hope that if the\n> developers can explain what the purpose of this is.May be 128 partitions is\n> the optimal value,It's a parameter to make it easier to adjust the number\n> of partitions in the future when it's really not enough. and the code\n> comments also said that hope to implement the parameter in the future\n> \n> \n> ( https://postgrespro.com/docs/enterprise/16/runtime-config-locks )\n> \n> \n> log2_num_lock_partitions (integer) #\n> <https://postgrespro.com/docs/enterprise/16/runtime-config-locks#GUC-LOG2-NUM-LOCK-PARTITIONS>\n> \n> This controls how many partitions the shared lock tables are divided into.\n> Number of partitions is calculated by raising 2 to the power of this\n> parameter. The default value is 4, which corresponds to 16 partitions, and\n> the maximum is 8. This parameter can only be set in the postgresql.conf file\n> or on the server command line.\n> \n> Best wish\n> \n\nHi,\n\nWell, if Postgres Pro implements this, I don't know what their reasoning\nwas exactly, but I guess they wanted to make it easier to experiment\nwith different values (without rebuild), or maybe they actually have\nsystems where they know higher values help ...\n\nNote: I'd point the maximum value 8 translates to 256, so no - it does\nnot max at the same value as PostgreSQL.\n\nAnyway, this value is inherently a trade off. If it wasn't, we'd set it\nto something super high from the start. But having more partitions of\nthe lock table has a cost too, because some parts need to acquire all\nthe partition locks (and that's O(N) where N = number of partitions).\n\nOf course, not having enough lock table partitions has a cost too,\nbecause it increases the chance of conflict between backends (who happen\nto need to operate on the same partition). This constant is not\nconstant, it changes over time - with 16 cores the collisions might have\nbeen rare, with 128 not so much. Also, with partitioning we may need\nmany more locks per query.\n\nThis means it's entirely possible it'd be good to have more than 128\npartitions of the lock table, but we only change this kind of stuff if\nwe have 2 things:\n\n1) clear demonstration of the benefits (e.g. a workload showing an\nimprovement with higher number of partitions)\n\n2) analysis of how this affects other workloads (e.g. cases that may\nneed to lock all the partitions etc)\n\nUltimately it's a trade off - we need to judge if the impact in (2) is\nworth the improvement in (1).\n\nNone of this was done in this thread. There's no demonstration of the\nbenefits, no analysis of the impact etc.\n\nAs for turning the parameter into a GUC, that has a cost too. Either\ndirect - a compiler can do far more optimizations with compile-time\nconstants than with values that may change during execution, for\nexample. Or indirect - if we can't give users any guidance how/when to\ntune the GUC, it can easily lead to misconfiguration (I can't even count\nhow many times I had to deal with systems where the values were \"tuned\"\nfollowing the logic that more is always better).\n\nWhich just leads back to (1) and (2) even for this case.\n\n\nregards\n\n\n-- \nTomas Vondra\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n",
"msg_date": "Fri, 23 Feb 2024 18:25:50 +0100",
"msg_from": "Tomas Vondra <tomas.vondra@enterprisedb.com>",
"msg_from_op": false,
"msg_subject": "Re: Thoughts about NUM_BUFFER_PARTITIONS"
},
{
"msg_contents": "One of our customers recently asked me to look into buffer mapping.\nFollowing is my POV on the problem of optimal NUM_BUFFER_PARTITIONS.\n\nI’ve found some dead code: BufMappingPartitionLockByIndex() is unused, and unused for a long time. See patch 1.\n\n> On 23 Feb 2024, at 22:25, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:\n> \n> Well, if Postgres Pro implements this, I don't know what their reasoning\n> was exactly, but I guess they wanted to make it easier to experiment\n> with different values (without rebuild), or maybe they actually have\n> systems where they know higher values help ...\n> \n> Note: I'd point the maximum value 8 translates to 256, so no - it does\n> not max at the same value as PostgreSQL.\n\nI’ve prototyped similar GUC for anyone willing to do such experiments. See patch 2, 4. Probably, I’ll do some experiments too, on customer's clusters and workloads :)\n\n> Anyway, this value is inherently a trade off. If it wasn't, we'd set it\n> to something super high from the start. But having more partitions of\n> the lock table has a cost too, because some parts need to acquire all\n> the partition locks (and that's O(N) where N = number of partitions).\n\nI’ve found none such cases, actually. Or, perhaps, I was not looking good enough.\npg_buffercache iterates over buffers and releases locks. See patch 3 to fix comments.\n\n> Of course, not having enough lock table partitions has a cost too,\n> because it increases the chance of conflict between backends (who happen\n> to need to operate on the same partition). This constant is not\n> constant, it changes over time - with 16 cores the collisions might have\n> been rare, with 128 not so much. Also, with partitioning we may need\n> many more locks per query.\n> \n> This means it's entirely possible it'd be good to have more than 128\n> partitions of the lock table, but we only change this kind of stuff if\n> we have 2 things:\n> \n> 1) clear demonstration of the benefits (e.g. a workload showing an\n> improvement with higher number of partitions)\n> \n> 2) analysis of how this affects other workloads (e.g. cases that may\n> need to lock all the partitions etc)\n> \n> Ultimately it's a trade off - we need to judge if the impact in (2) is\n> worth the improvement in (1).\n> \n> None of this was done in this thread. There's no demonstration of the\n> benefits, no analysis of the impact etc.\n> \n> As for turning the parameter into a GUC, that has a cost too. Either\n> direct - a compiler can do far more optimizations with compile-time\n> constants than with values that may change during execution, for\n> example.\n\nI think overhead of finding partition by hash is negligible small.\nnum_partitions in HTAB controls number of freelists. This might have some effect.\n\n> Or indirect - if we can't give users any guidance how/when to\n> tune the GUC, it can easily lead to misconfiguration (I can't even count\n> how many times I had to deal with systems where the values were \"tuned\"\n> following the logic that more is always better).\n\nYes, this argument IMHO is most important. By doing more such knobs we promote superstitious approach to tuning.\n\n\nBest regards, Andrey Borodin.",
"msg_date": "Mon, 5 Aug 2024 00:32:20 +0500",
"msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>",
"msg_from_op": false,
"msg_subject": "Re: Thoughts about NUM_BUFFER_PARTITIONS"
},
{
"msg_contents": "On Mon, Aug 05, 2024 at 12:32:20AM +0500, Andrey M. Borodin wrote:\n> I�ve found some dead code: BufMappingPartitionLockByIndex() is unused,\n> and unused for a long time. See patch 1.\n\nI don't see a reason to also get rid of BufTableHashPartition(), but\notherwise this looks reasonable to me. It would probably be a good idea to\nfirst check whether there are any external callers we can find.\n\n> I�ve prototyped similar GUC for anyone willing to do such experiments.\n> See patch 2, 4. Probably, I�ll do some experiments too, on customer's\n> clusters and workloads :)\n\nLike Tomas, I'm not too wild about making this a GUC. And as Heikki\npointed out upthread, a good first step would be to benchmark different\nNUM_BUFFER_PARTITIONS settings on modern hardware. I suspect the current\nsetting is much lower than optimal (e.g., I doubled it and saw a TPS boost\nfor read-only pgbench on an i5-13500T), but I don't think we fully\nunderstand the performance characteristics with different settings yet. If\nwe find that the ideal setting depends heavily on workload/hardware, then\nperhaps we can consider adding a GUC, but I don't think we are there yet.\n\n>> Anyway, this value is inherently a trade off. If it wasn't, we'd set it\n>> to something super high from the start. But having more partitions of\n>> the lock table has a cost too, because some parts need to acquire all\n>> the partition locks (and that's O(N) where N = number of partitions).\n> \n> I�ve found none such cases, actually. Or, perhaps, I was not looking good\n> enough. pg_buffercache iterates over buffers and releases locks. See\n> patch 3 to fix comments.\n\nYeah, I think 0003 is reasonable, too. pg_buffercache stopped acquiring\nall the partition locks in v10 (see commit 6e65454), which is also the\ncommit that removed all remaining uses of BufMappingPartitionLockByIndex().\nIn fact, I think BufMappingPartitionLockByIndex() was introduced just for\nthis pg_buffercache use-case (see commit ea9df81). \n\n-- \nnathan\n\n\n",
"msg_date": "Fri, 27 Sep 2024 14:07:33 -0500",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Thoughts about NUM_BUFFER_PARTITIONS"
}
] |
[
{
"msg_contents": "Hi,\n\nI found the comment on query_id_enabled looks inaccurate because this is\nnever set to true when compute_query_id is ON.\n\n /* True when compute_query_id is ON, or AUTO and a module requests them */\n bool query_id_enabled = false;\n\nShould we fix this as following (just fixing the place of a comma) ?\n\n/* True when compute_query_id is ON or AUTO, and a module requests them */\n\nAlso, I think the name is a bit confusing for the same reason, that is,\nquery_id_enabled may be false even when query id is computed in fact.\n\nActually, this does not matter because we use IsQueryIdEnabled to check\nif query id is enabled, instead of referring to a global variable\n(query_id_enabled or compute_query_id). But, just for making a code a bit\nmore readable, how about renaming this to query_id_required which seems to\nstand for the meaning more correctly?\n\nI attached a patch for above fixes. \n\nAlthough renaming might not be acceptable since changing global variables\nmay affect third party tools, I think the comment should be fixed at least.\n\nIMHO, it seems better to make this variable static not to be accessed directly.\nHowever, I left it as is because this is used in a static inline function.\n\nRegards,\nYugo Nagata\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>",
"msg_date": "Fri, 9 Feb 2024 15:38:23 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Small fix on query_id_enabled"
},
{
"msg_contents": "Hi,\n\nOn Fri, Feb 09, 2024 at 03:38:23PM +0900, Yugo NAGATA wrote:\n>\n> I found the comment on query_id_enabled looks inaccurate because this is\n> never set to true when compute_query_id is ON.\n>\n> /* True when compute_query_id is ON, or AUTO and a module requests them */\n> bool query_id_enabled = false;\n>\n> Should we fix this as following (just fixing the place of a comma) ?\n>\n> /* True when compute_query_id is ON or AUTO, and a module requests them */\n\nAgreed.\n\n> Also, I think the name is a bit confusing for the same reason, that is,\n> query_id_enabled may be false even when query id is computed in fact.\n>\n> Actually, this does not matter because we use IsQueryIdEnabled to check\n> if query id is enabled, instead of referring to a global variable\n> (query_id_enabled or compute_query_id). But, just for making a code a bit\n> more readable, how about renaming this to query_id_required which seems to\n> stand for the meaning more correctly?\n\n-1 for renaming to avoid breaking extensions that might access it. We should\nsimply document for compute_query_id and query_id_enabled declaration that one\nshould instead use IsQueryIdEnabled() if they're interested in whether the core\nqueryid are computed or not.\n\n\n",
"msg_date": "Fri, 9 Feb 2024 16:37:23 +0800",
"msg_from": "Julien Rouhaud <rjuju123@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Small fix on query_id_enabled"
},
{
"msg_contents": "On Fri, Feb 09, 2024 at 04:37:23PM +0800, Julien Rouhaud wrote:\n> On Fri, Feb 09, 2024 at 03:38:23PM +0900, Yugo NAGATA wrote:\n>> Also, I think the name is a bit confusing for the same reason, that is,\n>> query_id_enabled may be false even when query id is computed in fact.\n>>\n>> Actually, this does not matter because we use IsQueryIdEnabled to check\n>> if query id is enabled, instead of referring to a global variable\n>> (query_id_enabled or compute_query_id). But, just for making a code a bit\n>> more readable, how about renaming this to query_id_required which seems to\n>> stand for the meaning more correctly?\n> \n> -1 for renaming to avoid breaking extensions that might access it. We should\n> simply document for compute_query_id and query_id_enabled declaration that one\n> should instead use IsQueryIdEnabled() if they're interested in whether the core\n> queryid are computed or not.\n\nAgreed. A renaming would involve more pain than gain. Improving the\ncomments around how to all that would be good enough, my 2c.\n--\nMichael",
"msg_date": "Sat, 10 Feb 2024 10:19:15 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Small fix on query_id_enabled"
},
{
"msg_contents": "On Sat, 10 Feb 2024 10:19:15 +0900\nMichael Paquier <michael@paquier.xyz> wrote:\n\n> On Fri, Feb 09, 2024 at 04:37:23PM +0800, Julien Rouhaud wrote:\n> > On Fri, Feb 09, 2024 at 03:38:23PM +0900, Yugo NAGATA wrote:\n> >> Also, I think the name is a bit confusing for the same reason, that is,\n> >> query_id_enabled may be false even when query id is computed in fact.\n> >>\n> >> Actually, this does not matter because we use IsQueryIdEnabled to check\n> >> if query id is enabled, instead of referring to a global variable\n> >> (query_id_enabled or compute_query_id). But, just for making a code a bit\n> >> more readable, how about renaming this to query_id_required which seems to\n> >> stand for the meaning more correctly?\n> > \n> > -1 for renaming to avoid breaking extensions that might access it. We should\n> > simply document for compute_query_id and query_id_enabled declaration that one\n> > should instead use IsQueryIdEnabled() if they're interested in whether the core\n> > queryid are computed or not.\n> \n> Agreed. A renaming would involve more pain than gain. Improving the\n> comments around how to all that would be good enough, my 2c.\n\nThank you both for your comments.\n\nI agreed with not renaming it.\n\nI attached a updated patch that adds comments noting to use IsQueryIdEnabled()\ninstead of accessing the variables directly.\n\nRegards,\nYugo Nagata\n-- \nYugo NAGATA <nagata@sraoss.co.jp>",
"msg_date": "Tue, 13 Feb 2024 01:13:43 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: Small fix on query_id_enabled"
},
{
"msg_contents": "On Tue, Feb 13, 2024 at 01:13:43AM +0900, Yugo NAGATA wrote:\n> I attached an updated patch that adds comments noting to use IsQueryIdEnabled()\n> instead of accessing the variables directly.\n\nSounds good to me, thanks.\n--\nMichael",
"msg_date": "Tue, 13 Feb 2024 17:28:32 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Small fix on query_id_enabled"
},
{
"msg_contents": "On Tue, Feb 13, 2024 at 05:28:32PM +0900, Michael Paquier wrote:\n> On Tue, Feb 13, 2024 at 01:13:43AM +0900, Yugo NAGATA wrote:\n> > I attached an updated patch that adds comments noting to use IsQueryIdEnabled()\n> > instead of accessing the variables directly.\n>\n> Sounds good to me, thanks.\n\n +1!\n\n\n",
"msg_date": "Tue, 13 Feb 2024 23:23:47 +0800",
"msg_from": "Julien Rouhaud <rjuju123@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Small fix on query_id_enabled"
},
{
"msg_contents": "On Tue, Feb 13, 2024 at 11:23:47PM +0800, Julien Rouhaud wrote:\n> +1!\n\nOkay, applied as-is, then.\n--\nMichael",
"msg_date": "Wed, 14 Feb 2024 07:21:54 +0900",
"msg_from": "Michael Paquier <michael@paquier.xyz>",
"msg_from_op": false,
"msg_subject": "Re: Small fix on query_id_enabled"
},
{
"msg_contents": "On Wed, 14 Feb 2024 07:21:54 +0900\nMichael Paquier <michael@paquier.xyz> wrote:\n\n> On Tue, Feb 13, 2024 at 11:23:47PM +0800, Julien Rouhaud wrote:\n> > +1!\n> \n> Okay, applied as-is, then.\n\nThank you!\n\nRegards,\nYugo Nagata\n\n> --\n> Michael\n\n\n-- \nYugo NAGATA <nagata@sraoss.co.jp>\n\n\n",
"msg_date": "Wed, 14 Feb 2024 09:53:45 +0900",
"msg_from": "Yugo NAGATA <nagata@sraoss.co.jp>",
"msg_from_op": true,
"msg_subject": "Re: Small fix on query_id_enabled"
}
] |
[
{
"msg_contents": "Hi,\n\nWith a db setup with pgbench, we add an additional index:\nCREATE INDEX ON pgbench_accounts(abalance)\n\nAnd trigger several updates and vacuum to reach a stable amount of\ndirtied pages:\nUPDATE pgbench_accounts set abalance = abalance + 1 WHERE aid=1; CHECKPOINT;\nVACUUM (VERBOSE, INDEX_CLEANUP ON) pgbench_accounts\n\nThe vacuum will report the following:\nINFO: vacuuming \"postgres.public.pgbench_accounts\"\nINFO: launched 1 parallel vacuum worker for index vacuuming (planned: 1)\nINFO: finished vacuuming \"postgres.public.pgbench_accounts\": index scans: 1\n...\nbuffer usage: 122 hits, 165 misses, 4 dirtied\n\n4 pages were reported dirtied. However, we have 5 dirtied blocks at\nthe end of the vacuum when looking at pg_buffercache:\n\nSELECT c.relname, b.relfilenode\n FROM\npg_buffercache b LEFT JOIN pg_class c\n ON b.relfilenode =\npg_relation_filenode(c.oid)\n WHERE isdirty=true;\n relname | relfilenode\n-------------------------------+-------------\n pg_class | 1259\n pgbench_accounts | 16400\n pgbench_accounts | 16400\n pgbench_accounts_pkey | 16408\n pgbench_accounts_abalance_idx | 16480\n\nThe missing dirty block comes from the parallel worker vacuuming the\nabalance index. Running vacuum with parallel disabled will give the\ncorrect result.\n\nVacuum uses dedicated VacuumPage{Hit,Miss,Dirty} globals to track\nbuffer usage. However, those values are not collected at the end of\nparallel vacuum workers, leading to incorrect buffer count.\n\nThose vacuum specific globals are redundant with the existing\npgBufferUsage and only used in the verbose output. This patch removes\nthem and replaces them by pgBufferUsage which is already correctly\ncollected at the end of parallel workers, fixing the buffer count.\n\nRegards,\nAnthonin",
"msg_date": "Fri, 9 Feb 2024 10:09:43 +0100",
"msg_from": "Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>",
"msg_from_op": true,
"msg_subject": "Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "Hi,\n\nThank you for the report.\n\nOn Fri, Feb 9, 2024 at 6:10 PM Anthonin Bonnefoy\n<anthonin.bonnefoy@datadoghq.com> wrote:\n>\n> Hi,\n>\n> With a db setup with pgbench, we add an additional index:\n> CREATE INDEX ON pgbench_accounts(abalance)\n>\n> And trigger several updates and vacuum to reach a stable amount of\n> dirtied pages:\n> UPDATE pgbench_accounts set abalance = abalance + 1 WHERE aid=1; CHECKPOINT;\n> VACUUM (VERBOSE, INDEX_CLEANUP ON) pgbench_accounts\n>\n> The vacuum will report the following:\n> INFO: vacuuming \"postgres.public.pgbench_accounts\"\n> INFO: launched 1 parallel vacuum worker for index vacuuming (planned: 1)\n> INFO: finished vacuuming \"postgres.public.pgbench_accounts\": index scans: 1\n> ...\n> buffer usage: 122 hits, 165 misses, 4 dirtied\n>\n> 4 pages were reported dirtied. However, we have 5 dirtied blocks at\n> the end of the vacuum when looking at pg_buffercache:\n>\n> SELECT c.relname, b.relfilenode\n> FROM\n> pg_buffercache b LEFT JOIN pg_class c\n> ON b.relfilenode =\n> pg_relation_filenode(c.oid)\n> WHERE isdirty=true;\n> relname | relfilenode\n> -------------------------------+-------------\n> pg_class | 1259\n> pgbench_accounts | 16400\n> pgbench_accounts | 16400\n> pgbench_accounts_pkey | 16408\n> pgbench_accounts_abalance_idx | 16480\n>\n> The missing dirty block comes from the parallel worker vacuuming the\n> abalance index. Running vacuum with parallel disabled will give the\n> correct result.\n>\n> Vacuum uses dedicated VacuumPage{Hit,Miss,Dirty} globals to track\n> buffer usage. However, those values are not collected at the end of\n> parallel vacuum workers, leading to incorrect buffer count.\n\nTrue. I think we should fix it also on backbranches.\n\n>\n> Those vacuum specific globals are redundant with the existing\n> pgBufferUsage and only used in the verbose output. This patch removes\n> them and replaces them by pgBufferUsage which is already correctly\n> collected at the end of parallel workers, fixing the buffer count.\n\nIt seems to make sense to remove VacuumPageHit and friends, only on\nthe master branch, if we can use BufferUsage instead.\n\nAs for the proposed patch, the following part should handle the temp tables too:\n\n appendStringInfo(&buf, _(\"avg read rate: %.3f\nMB/s, avg write rate: %.3f MB/s\\n\"),\n read_rate, write_rate);\n appendStringInfo(&buf, _(\"buffer usage: %lld\nhits, %lld misses, %lld dirtied\\n\"),\n- (long long)\nAnalyzePageHit,\n- (long long)\nAnalyzePageMiss,\n- (long long)\nAnalyzePageDirty);\n+ (long long)\nbufferusage.shared_blks_hit,\n+ (long long)\nbufferusage.shared_blks_read,\n+ (long long)\nbufferusage.shared_blks_dirtied);\n appendStringInfo(&buf, _(\"system usage: %s\"),\npg_rusage_show(&ru0));\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Thu, 28 Mar 2024 12:06:57 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "Hi,\n\nThanks for the review.\n\nOn Thu, Mar 28, 2024 at 4:07 AM Masahiko Sawada <sawada.mshk@gmail.com>\nwrote:\n\n> As for the proposed patch, the following part should handle the temp\n> tables too:\n>\n\nTrue, I've missed the local blocks. I've updated the patch:\n- read_rate and write_rate now include local block usage\n- I've added a specific output for reporting local blocks instead of\ncombining them in the same output.\n\nRegards,\nAnthonin",
"msg_date": "Thu, 28 Mar 2024 11:12:40 +0100",
"msg_from": "Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>",
"msg_from_op": true,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "Hi, thank you for your work with this subject.\n\nWhile I was reviewing your code, I noticed that your patch conflicts \nwith another patch [0] that been committed.\n\n[0] \nhttps://www.postgresql.org/message-id/flat/CA%2BhUKGJkOiOCa%2Bmag4BF%2BzHo7qo%3Do9CFheB8%3Dg6uT5TUm2gkvA%40mail.gmail.com\n\nOn 28.03.2024 13:12, Anthonin Bonnefoy wrote:\n> Hi,\n>\n> Thanks for the review.\n> On Thu, Mar 28, 2024 at 4:07 AM Masahiko Sawada \n> <sawada.mshk@gmail.com> wrote:\n>\n> As for the proposed patch, the following part should handle the\n> temp tables too:\n>\n>\n> True, I've missed the local blocks. I've updated the patch:\n> - read_rate and write_rate now include local block usage\n> - I've added a specific output for reporting local blocks instead of \n> combining them in the same output.\n>\n> Regards,\n> Anthonin\n\n-- \nRegards,\nAlena Rybakina\nPostgres Professional:http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n\n\n\nHi, thank you for your work with this subject.\nWhile I was reviewing your code, I noticed that your patch\n conflicts with another patch [0] that been committed.\n[0]\nhttps://www.postgresql.org/message-id/flat/CA%2BhUKGJkOiOCa%2Bmag4BF%2BzHo7qo%3Do9CFheB8%3Dg6uT5TUm2gkvA%40mail.gmail.com\n\nOn 28.03.2024 13:12, Anthonin Bonnefoy\n wrote:\n\n\n\n\nHi, \n\n\nThanks for the review.\n \n\nOn Thu, Mar 28, 2024 at\n 4:07 AM Masahiko Sawada <sawada.mshk@gmail.com>\n wrote:\n\nAs\n for the proposed patch, the following part should handle the\n temp tables too:\n\n\n\nTrue, I've missed the local blocks. I've updated the\n patch:\n- read_rate and write_rate now include local block usage\n- I've added a specific output for reporting local blocks\n instead of combining them in the same output.\n\n\nRegards,\nAnthonin\n\n\n\n-- \nRegards,\nAlena Rybakina\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company",
"msg_date": "Sat, 20 Apr 2024 15:00:53 +0300",
"msg_from": "Alena Rybakina <lena.ribackina@yandex.ru>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "On Sat, Apr 20, 2024 at 2:00 PM Alena Rybakina <lena.ribackina@yandex.ru>\nwrote:\n\n> Hi, thank you for your work with this subject.\n>\n> While I was reviewing your code, I noticed that your patch conflicts with\n> another patch [0] that been committed.\n>\n> [0]\n> https://www.postgresql.org/message-id/flat/CA%2BhUKGJkOiOCa%2Bmag4BF%2BzHo7qo%3Do9CFheB8%3Dg6uT5TUm2gkvA%40mail.gmail.com\n>\n\nI've rebased the patch and also split the changes:\n1: Use pgBufferUsage in Vacuum and Analyze block reporting\n2: Stop tracking buffer usage in the now unused Vacuum{Hit,Miss,Dirty}\nvariables\n3: Remove declarations of Vacuum{Hit,Miss,Dirty}",
"msg_date": "Mon, 22 Apr 2024 10:07:33 +0200",
"msg_from": "Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>",
"msg_from_op": true,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "On Mon, Apr 22, 2024 at 5:07 PM Anthonin Bonnefoy\n<anthonin.bonnefoy@datadoghq.com> wrote:\n>\n> On Sat, Apr 20, 2024 at 2:00 PM Alena Rybakina <lena.ribackina@yandex.ru> wrote:\n>>\n>> Hi, thank you for your work with this subject.\n>>\n>> While I was reviewing your code, I noticed that your patch conflicts with another patch [0] that been committed.\n>>\n>> [0] https://www.postgresql.org/message-id/flat/CA%2BhUKGJkOiOCa%2Bmag4BF%2BzHo7qo%3Do9CFheB8%3Dg6uT5TUm2gkvA%40mail.gmail.com\n>\n>\n> I've rebased the patch and also split the changes:\n\nThank you for updating the patch!\n\n> 1: Use pgBufferUsage in Vacuum and Analyze block reporting\n\nI think that if the anayze command doesn't have the same issue, we\ndon't need to change it. Making the vacuum and the analyze consistent\nis a good point but I'd like to avoid doing unnecessary changes in\nback branches. I think the patch set would contain:\n\n(a) make lazy vacuum use BufferUsage instead of\nVacuumPage{Hit,Miss,Dirty}. (backpatched down to pg13).\n(b) make analyze use BufferUsage and remove VacuumPage{Hit,Miss,Dirty}\nvariables for consistency and simplicity (only for HEAD, if we agree).\n\nBTW I realized that VACUUM VERBOSE running on a temp table always\nshows the number of dirtied buffers being 0, which seems to be a bug.\nThe patch (a) will resolve it as well.\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Wed, 24 Apr 2024 15:34:47 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "Thanks for the review!\n\n\n> I think that if the anayze command doesn't have the same issue, we\n> don't need to change it.\n\nGood point, I've wrongly assumed that analyze was also impacted but there's\nno parallel analyze so the block count is correct.\n\n\n> (a) make lazy vacuum use BufferUsage instead of\n> VacuumPage{Hit,Miss,Dirty}. (backpatched down to pg13).\n> (b) make analyze use BufferUsage and remove VacuumPage{Hit,Miss,Dirty}\n> variables for consistency and simplicity (only for HEAD, if we agree).\n>\n I've isolated the fix in the first patch. I've kept the analyze change and\nremoval of VacuumPage* variables split for clarity sake.\n\nBTW I realized that VACUUM VERBOSE running on a temp table always\n> shows the number of dirtied buffers being 0, which seems to be a bug.\n> The patch (a) will resolve it as well.\n>\nIndeed, it visible with the following test:\n\nSET temp_buffers='1024';\nCREATE TEMPORARY TABLE vacuum_fix (aid int, bid int);\nINSERT INTO vacuum_fix SELECT *, * FROM generate_series(1, 1000000);\nVACUUM vacuum_fix;\nUPDATE vacuum_fix SET bid = bid+1;\nVACUUM (VERBOSE, INDEX_CLEANUP ON) vacuum_fix;\n\nPre-patch:\n avg read rate: 254.751 MB/s, avg write rate: 0.029 MB/s\n buffer usage: 8853 hits, 8856 misses, 1 dirtied\n WAL usage: 1 records, 1 full page images, 3049 bytes\nThe dirtied page is from pg_class (so not a local buffer)\n\nWith the fix:\n avg read rate: 250.230 MB/s, avg write rate: 250.230 MB/s\n buffer usage: 8853 hits, 8856 misses, 8856 dirtied\n WAL usage: 1 records, 1 full page images, 3049 bytes",
"msg_date": "Wed, 24 Apr 2024 11:19:26 +0200",
"msg_from": "Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>",
"msg_from_op": true,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "On 22.04.2024 11:07, Anthonin Bonnefoy wrote:\n> On Sat, Apr 20, 2024 at 2:00 PM Alena Rybakina \n> <lena.ribackina@yandex.ru> wrote:\n>\n> Hi, thank you for your work with this subject.\n>\n> While I was reviewing your code, I noticed that your patch\n> conflicts with another patch [0] that been committed.\n>\n> [0]\n> https://www.postgresql.org/message-id/flat/CA%2BhUKGJkOiOCa%2Bmag4BF%2BzHo7qo%3Do9CFheB8%3Dg6uT5TUm2gkvA%40mail.gmail.com\n>\n>\n> I've rebased the patch and also split the changes:\n> 1: Use pgBufferUsage in Vacuum and Analyze block reporting\n> 2: Stop tracking buffer usage in the now unused Vacuum{Hit,Miss,Dirty} \n> variables\n> 3: Remove declarations of Vacuum{Hit,Miss,Dirty}\n\nHi! Thank you for your work, and I have reviewed your corrections.\n\nI tested the main postgres branch with and without your fix using a \nscript that was written by me. It consists of five scenarios and I made \na comparison in the logs between the original version of the master \nbranch and the master branch with your patch:\n\n1. I added 1 million data to the table and deleted 10% of them. I ran \nvacuum verbose and didn't see any differences.\nbuffer usage: 12585 hits, 0 misses, 4 dirtied\n2. I opened another connection with a repeatable read transaction \nthrough the dblink extension and launched a query updating the records \nin the table under test. Later, I ran vacuum verbose again and also \ndidn't see any differences.\nbuffer usage: 19424 hits, 0 misses, 6 dirtied\n3. I commited transaction and ran vacuum verbose again. Everything is \nfine in the logs.\nbuffer usage: 22960 hits, 0 misses, 11456 dirtied\n4. I deleted all the data from the table and later started vacuum \nverbose again. The number of pages in the buffer matched with your patch \ntoo.\n5.I inserted 1 million data into the table and updated it, and I found \nthe difference between the original master version and the version with \nyour patch:\nwith your patch: buffer usage: 32315 hits, 606 misses, 1547 dirtied\noriginal version: buffer usage: 32348 hits, 573 misses, 1456 dirtied\nI suppose, something wasn't calculated.\n\nThe same script was run, but using vacuum verbose analyze, and I saw the \ndifference again in the fifth step:\nwith your patch: buffer usage: 32312 hits, 607 misses, 1566 dirtied\nmaster: buffer usage: 32346 hits, 573 misses, 1360 dirtied\n\nI have attached a test file (vacuum_check_logs.sql) and four log files: \ntwo with the vacuum verbose command (vacuum_log and \nvacuum_log_with_patch files) and two others with the vacuum verbose \nanalyze command (vacuum_analyze_test_with_patch and vacuum_analyze_test \nfiles). Both test approaches show logs with and without your changes.\n>> 1: Use pgBufferUsage in Vacuum and Analyze block reporting\n> I think that if the anayze command doesn't have the same issue, we\n> don't need to change it. Making the vacuum and the analyze consistent\n> is a good point but I'd like to avoid doing unnecessary changes in\n> back branches. I think the patch set would contain:\n>\n> (a) make lazy vacuum use BufferUsage instead of\n> VacuumPage{Hit,Miss,Dirty}. (backpatched down to pg13).\n> (b) make analyze use BufferUsage and remove VacuumPage{Hit,Miss,Dirty}\n> variables for consistency and simplicity (only for HEAD, if we agree).\n>\n> BTW I realized that VACUUM VERBOSE running on a temp table always\n> shows the number of dirtied buffers being 0, which seems to be a bug.\n> The patch (a) will resolve it as well.\n>\nI agree with that. I think we can leave these changes to the analysis \ncommand for master, but I also doubt the need to backport his changes to \nback versions.\n\n-- \nRegards,\nAlena Rybakina\nPostgres Professional:http://www.postgrespro.com\nThe Russian Postgres Company",
"msg_date": "Wed, 24 Apr 2024 17:01:19 +0300",
"msg_from": "Alena Rybakina <lena.ribackina@yandex.ru>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "On Wed, Apr 24, 2024 at 4:01 PM Alena Rybakina <lena.ribackina@yandex.ru>\nwrote:\n\n> I tested the main postgres branch with and without your fix using a script\n> that was written by me. It consists of five scenarios and I made a\n> comparison in the logs between the original version of the master branch\n> and the master branch with your patch:\n>\n Hi! Thanks for the tests.\n\nI have attached a test file (vacuum_check_logs.sql)\n>\nLooking at the script, you won't trigger the problem. The reporting issue\nwill only happen if there's a parallel index vacuum and it will only happen\nif there's at least 2 indexes [0]. You will need to create an additional\nindex.\n\nThe same script was run, but using vacuum verbose analyze, and I saw the\n> difference again in the fifth step:\n> with your patch: buffer usage: 32312 hits, 607 misses, 1566 dirtied\n> master: buffer usage: 32346 hits, 573 misses, 1360 dirtied\n>\nIsn't there a chance for the checkpointer to run during this time? That\ncould make the conditions between the two runs slightly different and\nexplain the change in buffer report.\n\n[0]\nhttps://github.com/postgres/postgres/blob/8a1b31e6e59631807a08a4e9465134c343bbdf5e/src/backend/access/heap/vacuumlazy.c#L2826-L2831\n\nOn Wed, Apr 24, 2024 at 4:01 PM Alena Rybakina <lena.ribackina@yandex.ru> wrote:I tested the main postgres branch with and without your fix using a script that was written by me. It consists of five scenarios and I made a comparison in the logs between the original version of the master branch and the master branch with your patch: Hi! Thanks for the tests.\n I have attached a test file (vacuum_check_logs.sql)Looking at the script, you won't trigger the problem. The reporting issue will only happen if there's a parallel index vacuum and it will only happen if there's at least 2 indexes [0]. You will need to create an additional index.The same script was run, but using vacuum verbose analyze, and I saw the difference again in the fifth step:with your patch: buffer usage: 32312 hits, 607 misses, 1566 dirtiedmaster: buffer usage: 32346 hits, 573 misses, 1360 dirtiedIsn't there a chance for the checkpointer to run during this time? That could make the conditions between the two runs slightly different and explain the change in buffer report.[0] https://github.com/postgres/postgres/blob/8a1b31e6e59631807a08a4e9465134c343bbdf5e/src/backend/access/heap/vacuumlazy.c#L2826-L2831",
"msg_date": "Thu, 25 Apr 2024 09:17:52 +0200",
"msg_from": "Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>",
"msg_from_op": true,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "Hi!\n\n> The same script was run, but using vacuum verbose analyze, and I\n> saw the difference again in the fifth step:\n> with your patch: buffer usage: 32312 hits, 607 misses, 1566 dirtied\n> master: buffer usage: 32346 hits, 573 misses, 1360 dirtied\n>\n> Isn't there a chance for the checkpointer to run during this time? \n> That could make the conditions between the two runs slightly different \n> and explain the change in buffer report.\n>\n> [0] \n> https://github.com/postgres/postgres/blob/8a1b31e6e59631807a08a4e9465134c343bbdf5e/src/backend/access/heap/vacuumlazy.c#L2826-L2831\n>\n> Looking at the script, you won't trigger the problem.\n\nThank you for the link I accounted it in my next experiments.\n\nI repeated the test without processing checkpoints with a single index, \nand the number of pages in the buffer used almost matched:\n\nmaster branch: buffer usage: 32315 hits, 606 misses, 4486 dirtied\n\nwith applied patch v4 version: buffer usage: 32315 hits, 606 misses, \n4489 dirtied\n\nI think you are right - the problem was interfering with the checkpoint \nprocess, by the way I checked the first version patch. To cut a long \nstory short, everything is fine now with one index.\n\nJust in case, I'll explain: I considered this case because your patch \ncould have impact influenced it too.\n\nOn 25.04.2024 10:17, Anthonin Bonnefoy wrote:\n>\n> On Wed, Apr 24, 2024 at 4:01 PM Alena Rybakina \n> <lena.ribackina@yandex.ru> wrote:\n>\n> I tested the main postgres branch with and without your fix using\n> a script that was written by me. It consists of five scenarios and\n> I made a comparison in the logs between the original version of\n> the master branch and the master branch with your patch:\n>\n> Hi! Thanks for the tests.\n>\n> I have attached a test file (vacuum_check_logs.sql)\n>\n> The reporting issue will only happen if there's a parallel index \n> vacuum and it will only happen if there's at least 2 indexes [0]. You \n> will need to create an additional index.\n\nSpeaking of the problem, I added another index and repeated the test and \nfound a significant difference:\n\n * I found it when I commited the transaction (3):\n\nmaster: 2964hits, 0misses, 0dirtied\n\nwith applied patch v4 version: buffer usage: 33013hits, 0misses, 3dirtied\n\n * When I deleted all the data from the table and later started vacuum\n verbose again (4):\n\nmaster: buffer usage: 51486hits, 0misses, 0dirtied\n\nwith applied patch v4 version:buffer usage: 77924hits, 0misses, 0dirtied\n\n * when I inserted 1 million data into the table and updated it (5):\n\nmaster:buffer usage: 27904hits, 5021misses, 1777dirtied\n\nwith applied patch v4 version:buffer usage: 41051hits, 9973misses, \n2564dirtied\n\nAs I see, the number of pages is significantly more than it was in the \nmaster branch and ,frankly, I couldn't fully figure out if it was a \nmistake or not.\n\nI attached a test script (vacuum_checks_logs.sql) with two indexes and \nno checkpoints, I also attached log files: the first one (vacuum_test) \nis the result of testing on the master branch, the second file with your \napplied patch (vacuum_test_v4).\n\n-- \nRegards,\nAlena Rybakina\nPostgres Professional:http://www.postgrespro.com\nThe Russian Postgres Company",
"msg_date": "Fri, 26 Apr 2024 15:12:45 +0300",
"msg_from": "Alena Rybakina <lena.ribackina@yandex.ru>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "On Fri, Apr 26, 2024 at 9:12 PM Alena Rybakina <lena.ribackina@yandex.ru> wrote:\n>\n> Hi!\n>>\n>> The same script was run, but using vacuum verbose analyze, and I saw the difference again in the fifth step:\n>> with your patch: buffer usage: 32312 hits, 607 misses, 1566 dirtied\n>> master: buffer usage: 32346 hits, 573 misses, 1360 dirtied\n>\n> Isn't there a chance for the checkpointer to run during this time? That could make the conditions between the two runs slightly different and explain the change in buffer report.\n>\n> [0] https://github.com/postgres/postgres/blob/8a1b31e6e59631807a08a4e9465134c343bbdf5e/src/backend/access/heap/vacuumlazy.c#L2826-L2831\n>\n> Looking at the script, you won't trigger the problem.\n>\n> Thank you for the link I accounted it in my next experiments.\n>\n> I repeated the test without processing checkpoints with a single index, and the number of pages in the buffer used almost matched:\n>\n> master branch: buffer usage: 32315 hits, 606 misses, 4486 dirtied\n>\n> with applied patch v4 version: buffer usage: 32315 hits, 606 misses, 4489 dirtied\n>\n> I think you are right - the problem was interfering with the checkpoint process, by the way I checked the first version patch. To cut a long story short, everything is fine now with one index.\n>\n> Just in case, I'll explain: I considered this case because your patch could have impact influenced it too.\n>\n> On 25.04.2024 10:17, Anthonin Bonnefoy wrote:\n>\n>\n> On Wed, Apr 24, 2024 at 4:01 PM Alena Rybakina <lena.ribackina@yandex.ru> wrote:\n>>\n>> I tested the main postgres branch with and without your fix using a script that was written by me. It consists of five scenarios and I made a comparison in the logs between the original version of the master branch and the master branch with your patch:\n>\n> Hi! Thanks for the tests.\n>\n>> I have attached a test file (vacuum_check_logs.sql)\n>\n> The reporting issue will only happen if there's a parallel index vacuum and it will only happen if there's at least 2 indexes [0]. You will need to create an additional index.\n>\n> Speaking of the problem, I added another index and repeated the test and found a significant difference:\n>\n> I found it when I commited the transaction (3):\n>\n> master: 2964 hits, 0 misses, 0 dirtied\n>\n> with applied patch v4 version: buffer usage: 33013 hits, 0 misses, 3 dirtied\n>\n> When I deleted all the data from the table and later started vacuum verbose again (4):\n>\n> master: buffer usage: 51486 hits, 0 misses, 0 dirtied\n>\n> with applied patch v4 version:buffer usage: 77924 hits, 0 misses, 0 dirtied\n>\n> when I inserted 1 million data into the table and updated it (5):\n>\n> master:buffer usage: 27904 hits, 5021 misses, 1777 dirtied\n>\n> with applied patch v4 version:buffer usage: 41051 hits, 9973 misses, 2564 dirtied\n>\n> As I see, the number of pages is significantly more than it was in the master branch and ,frankly, I couldn't fully figure out if it was a mistake or not.\n\nI think that the patch fixes the problem correctly.\n\nI've run pgindent and updated the commit message. I realized that\nparallel vacuum was introduced in pg13 but buffer usage reporting in\nVACUUM command was implemented in pg15. Therefore, in pg13 and pg14,\nVACUUM (PARALLEL) is available but VACUUM (PARALLEL, VERBOSE) doesn't\nshow the buffer usage report. Autovacuum does show the buffer usage\nreport but parallel autovacuum is not supported. Therefore, we should\nbackpatch it down to 15, not 13.\n\nI'm going to push the patch down to pg15, barring any objections.\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Tue, 30 Apr 2024 11:18:14 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "I've done some additional tests to validate the reported numbers. Using\npg_statio, it's possible to get the minimum number of block hits (Full\nscript attached).\n\n-- Save block hits before vacuum\nSELECT pg_stat_force_next_flush();\nSELECT heap_blks_hit, idx_blks_hit FROM pg_statio_all_tables where\nrelname='vestat' \\gset\nvacuum (verbose, index_cleanup on) vestat;\n-- Check the difference\nSELECT pg_stat_force_next_flush();\nSELECT heap_blks_hit - :heap_blks_hit as delta_heap_hit,\n idx_blks_hit - :idx_blks_hit as delta_idx_hit,\n heap_blks_hit - :heap_blks_hit + idx_blks_hit - :idx_blks_hit as sum\n FROM pg_statio_all_tables where relname='vestat';\n\nOutput:\n...\nbuffer usage: 14676 hits, 0 misses, 667 dirtied\nbuffer usage (new): 16081 hits, 0 misses, 667 dirtied\n...\n -[ RECORD 1 ]--+------\ndelta_heap_hit | 9747\ndelta_idx_hit | 6325\nsum | 16072\n\n From pg_statio, we had 16072 blocks for the relation + indexes.\nPre-patch, we are under reporting with 14676.\nPost-patch, we have 16081. The 9 additional block hits come from vacuum\naccessing catalog tables like pg_class or pg_class_oid_index.",
"msg_date": "Tue, 30 Apr 2024 08:33:50 +0200",
"msg_from": "Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>",
"msg_from_op": true,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "On Tue, Apr 30, 2024 at 3:34 PM Anthonin Bonnefoy\n<anthonin.bonnefoy@datadoghq.com> wrote:\n>\n> I've done some additional tests to validate the reported numbers. Using pg_statio, it's possible to get the minimum number of block hits (Full script attached).\n>\n> -- Save block hits before vacuum\n> SELECT pg_stat_force_next_flush();\n> SELECT heap_blks_hit, idx_blks_hit FROM pg_statio_all_tables where relname='vestat' \\gset\n> vacuum (verbose, index_cleanup on) vestat;\n> -- Check the difference\n> SELECT pg_stat_force_next_flush();\n> SELECT heap_blks_hit - :heap_blks_hit as delta_heap_hit,\n> idx_blks_hit - :idx_blks_hit as delta_idx_hit,\n> heap_blks_hit - :heap_blks_hit + idx_blks_hit - :idx_blks_hit as sum\n> FROM pg_statio_all_tables where relname='vestat';\n>\n> Output:\n> ...\n> buffer usage: 14676 hits, 0 misses, 667 dirtied\n> buffer usage (new): 16081 hits, 0 misses, 667 dirtied\n> ...\n> -[ RECORD 1 ]--+------\n> delta_heap_hit | 9747\n> delta_idx_hit | 6325\n> sum | 16072\n>\n> From pg_statio, we had 16072 blocks for the relation + indexes.\n> Pre-patch, we are under reporting with 14676.\n> Post-patch, we have 16081. The 9 additional block hits come from vacuum accessing catalog tables like pg_class or pg_class_oid_index.\n>\n\nThank you for further testing! I've pushed the patch.\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Wed, 1 May 2024 12:36:39 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "Hi!\n\nOn 30.04.2024 05:18, Masahiko Sawada wrote:\n> On Fri, Apr 26, 2024 at 9:12 PM Alena Rybakina<lena.ribackina@yandex.ru> wrote:\n>> Hi!\n>>> The same script was run, but using vacuum verbose analyze, and I saw the difference again in the fifth step:\n>>> with your patch: buffer usage: 32312 hits, 607 misses, 1566 dirtied\n>>> master: buffer usage: 32346 hits, 573 misses, 1360 dirtied\n>> Isn't there a chance for the checkpointer to run during this time? That could make the conditions between the two runs slightly different and explain the change in buffer report.\n>>\n>> [0]https://github.com/postgres/postgres/blob/8a1b31e6e59631807a08a4e9465134c343bbdf5e/src/backend/access/heap/vacuumlazy.c#L2826-L2831\n>>\n>> Looking at the script, you won't trigger the problem.\n>>\n>> Thank you for the link I accounted it in my next experiments.\n>>\n>> I repeated the test without processing checkpoints with a single index, and the number of pages in the buffer used almost matched:\n>>\n>> master branch: buffer usage: 32315 hits, 606 misses, 4486 dirtied\n>>\n>> with applied patch v4 version: buffer usage: 32315 hits, 606 misses, 4489 dirtied\n>>\n>> I think you are right - the problem was interfering with the checkpoint process, by the way I checked the first version patch. To cut a long story short, everything is fine now with one index.\n>>\n>> Just in case, I'll explain: I considered this case because your patch could have impact influenced it too.\n>>\n>> On 25.04.2024 10:17, Anthonin Bonnefoy wrote:\n>>\n>>\n>> On Wed, Apr 24, 2024 at 4:01 PM Alena Rybakina<lena.ribackina@yandex.ru> wrote:\n>>> I tested the main postgres branch with and without your fix using a script that was written by me. It consists of five scenarios and I made a comparison in the logs between the original version of the master branch and the master branch with your patch:\n>> Hi! Thanks for the tests.\n>>\n>>> I have attached a test file (vacuum_check_logs.sql)\n>> The reporting issue will only happen if there's a parallel index vacuum and it will only happen if there's at least 2 indexes [0]. You will need to create an additional index.\n>>\n>> Speaking of the problem, I added another index and repeated the test and found a significant difference:\n>>\n>> I found it when I commited the transaction (3):\n>>\n>> master: 2964 hits, 0 misses, 0 dirtied\n>>\n>> with applied patch v4 version: buffer usage: 33013 hits, 0 misses, 3 dirtied\n>>\n>> When I deleted all the data from the table and later started vacuum verbose again (4):\n>>\n>> master: buffer usage: 51486 hits, 0 misses, 0 dirtied\n>>\n>> with applied patch v4 version:buffer usage: 77924 hits, 0 misses, 0 dirtied\n>>\n>> when I inserted 1 million data into the table and updated it (5):\n>>\n>> master:buffer usage: 27904 hits, 5021 misses, 1777 dirtied\n>>\n>> with applied patch v4 version:buffer usage: 41051 hits, 9973 misses, 2564 dirtied\n>>\n>> As I see, the number of pages is significantly more than it was in the master branch and ,frankly, I couldn't fully figure out if it was a mistake or not.\n> I think that the patch fixes the problem correctly.\n>\n> I've run pgindent and updated the commit message. I realized that\n> parallel vacuum was introduced in pg13 but buffer usage reporting in\n> VACUUM command was implemented in pg15. Therefore, in pg13 and pg14,\n> VACUUM (PARALLEL) is available but VACUUM (PARALLEL, VERBOSE) doesn't\n> show the buffer usage report. Autovacuum does show the buffer usage\n> report but parallel autovacuum is not supported. Therefore, we should\n> backpatch it down to 15, not 13.\n>\n> I'm going to push the patch down to pg15, barring any objections.\n>\n> Regards,\nI agree with you about porting and I saw that the patch is working \ncorrectly.\n\n-- \nRegards,\nAlena Rybakina\nPostgres Professional:http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n\n\n\nHi!\n\nOn 30.04.2024 05:18, Masahiko Sawada\n wrote:\n\n\nOn Fri, Apr 26, 2024 at 9:12 PM Alena Rybakina <lena.ribackina@yandex.ru> wrote:\n\n\n\nHi!\n\n\n\nThe same script was run, but using vacuum verbose analyze, and I saw the difference again in the fifth step:\nwith your patch: buffer usage: 32312 hits, 607 misses, 1566 dirtied\nmaster: buffer usage: 32346 hits, 573 misses, 1360 dirtied\n\n\n\nIsn't there a chance for the checkpointer to run during this time? That could make the conditions between the two runs slightly different and explain the change in buffer report.\n\n[0] https://github.com/postgres/postgres/blob/8a1b31e6e59631807a08a4e9465134c343bbdf5e/src/backend/access/heap/vacuumlazy.c#L2826-L2831\n\nLooking at the script, you won't trigger the problem.\n\nThank you for the link I accounted it in my next experiments.\n\nI repeated the test without processing checkpoints with a single index, and the number of pages in the buffer used almost matched:\n\nmaster branch: buffer usage: 32315 hits, 606 misses, 4486 dirtied\n\nwith applied patch v4 version: buffer usage: 32315 hits, 606 misses, 4489 dirtied\n\nI think you are right - the problem was interfering with the checkpoint process, by the way I checked the first version patch. To cut a long story short, everything is fine now with one index.\n\nJust in case, I'll explain: I considered this case because your patch could have impact influenced it too.\n\nOn 25.04.2024 10:17, Anthonin Bonnefoy wrote:\n\n\nOn Wed, Apr 24, 2024 at 4:01 PM Alena Rybakina <lena.ribackina@yandex.ru> wrote:\n\n\n\nI tested the main postgres branch with and without your fix using a script that was written by me. It consists of five scenarios and I made a comparison in the logs between the original version of the master branch and the master branch with your patch:\n\n\n\n Hi! Thanks for the tests.\n\n\n\nI have attached a test file (vacuum_check_logs.sql)\n\n\n\nThe reporting issue will only happen if there's a parallel index vacuum and it will only happen if there's at least 2 indexes [0]. You will need to create an additional index.\n\nSpeaking of the problem, I added another index and repeated the test and found a significant difference:\n\nI found it when I commited the transaction (3):\n\nmaster: 2964 hits, 0 misses, 0 dirtied\n\nwith applied patch v4 version: buffer usage: 33013 hits, 0 misses, 3 dirtied\n\nWhen I deleted all the data from the table and later started vacuum verbose again (4):\n\nmaster: buffer usage: 51486 hits, 0 misses, 0 dirtied\n\nwith applied patch v4 version:buffer usage: 77924 hits, 0 misses, 0 dirtied\n\nwhen I inserted 1 million data into the table and updated it (5):\n\nmaster:buffer usage: 27904 hits, 5021 misses, 1777 dirtied\n\nwith applied patch v4 version:buffer usage: 41051 hits, 9973 misses, 2564 dirtied\n\nAs I see, the number of pages is significantly more than it was in the master branch and ,frankly, I couldn't fully figure out if it was a mistake or not.\n\n\n\nI think that the patch fixes the problem correctly.\n\nI've run pgindent and updated the commit message. I realized that\nparallel vacuum was introduced in pg13 but buffer usage reporting in\nVACUUM command was implemented in pg15. Therefore, in pg13 and pg14,\nVACUUM (PARALLEL) is available but VACUUM (PARALLEL, VERBOSE) doesn't\nshow the buffer usage report. Autovacuum does show the buffer usage\nreport but parallel autovacuum is not supported. Therefore, we should\nbackpatch it down to 15, not 13.\n\nI'm going to push the patch down to pg15, barring any objections.\n\nRegards,\n\n\nI agree with you about porting and I saw that the patch is working correctly.\n\n\n-- \nRegards,\nAlena Rybakina\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company",
"msg_date": "Wed, 1 May 2024 06:51:39 +0300",
"msg_from": "Alena Rybakina <lena.ribackina@yandex.ru>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "On Wed, May 1, 2024 at 5:37 AM Masahiko Sawada <sawada.mshk@gmail.com>\nwrote:\n\n> Thank you for further testing! I've pushed the patch.\n\nThanks!\n\nHere is the rebased version for the follow-up patch removing VacuumPage\nvariables. Though I'm not sure if I should create a dedicated mail thread\nsince the bug was fixed and the follow-up is more of a refactoring. What\ndo you think?",
"msg_date": "Fri, 3 May 2024 08:41:42 +0200",
"msg_from": "Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>",
"msg_from_op": true,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "On Fri, May 3, 2024 at 3:41 PM Anthonin Bonnefoy\n<anthonin.bonnefoy@datadoghq.com> wrote:\n>\n> On Wed, May 1, 2024 at 5:37 AM Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>>\n>> Thank you for further testing! I've pushed the patch.\n>\n> Thanks!\n>\n> Here is the rebased version for the follow-up patch removing VacuumPage variables. Though I'm not sure if I should create a dedicated mail thread since the bug was fixed and the follow-up is more of a refactoring. What do you think?\n\nI'd suggest starting a new thread or changing the subject as the\ncurrent subject no longer matches what we're discussing.\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Wed, 8 May 2024 22:46:52 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "Hi,\n\nThank you for working on this!\n\nOn Wed, 1 May 2024 at 06:37, Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> Thank you for further testing! I've pushed the patch.\n\nI realized a behaviour change while looking at 'Use pgBufferUsage for\nblock reporting in analyze' thread [1]. Since that change applies here\nas well, I thought it is better to mention it here.\n\nBefore this commit, VacuumPageMiss did not count the blocks if its\nread was already completed by other backends [2]. Now,\n'pgBufferUsage.local_blks_read + pgBufferUsage.shared_blks_read'\ncounts every block attempted to be read; possibly double counting if\nsomeone else has already completed the read. I do not know which\nbehaviour is correct but I wanted to mention this.\n\n[1] https://postgr.es/m/CAO6_Xqr__kTTCLkftqS0qSCm-J7_xbRG3Ge2rWhucxQJMJhcRA%40mail.gmail.com\n\n[2] In the WaitReadBuffers() function, see comment:\n /*\n * Skip this block if someone else has already completed it. If an\n * I/O is already in progress in another backend, this will wait for\n * the outcome: either done, or something went wrong and we will\n * retry.\n */\n\n-- \nRegards,\nNazir Bilal Yavuz\nMicrosoft\n\n\n",
"msg_date": "Fri, 10 May 2024 13:25:58 +0300",
"msg_from": "Nazir Bilal Yavuz <byavuz81@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "Hi! I could try to check it with the test, but I want to ask you about \ndetails, because I'm not sure that I completely understand the test case.\n\nYou mean that we need to have two backends and on one of them we deleted \nthe tuples before vacuum called the other, do you?\n\nOn 10.05.2024 13:25, Nazir Bilal Yavuz wrote:\n> Hi,\n>\n> Thank you for working on this!\n>\n> On Wed, 1 May 2024 at 06:37, Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>> Thank you for further testing! I've pushed the patch.\n> I realized a behaviour change while looking at 'Use pgBufferUsage for\n> block reporting in analyze' thread [1]. Since that change applies here\n> as well, I thought it is better to mention it here.\n>\n> Before this commit, VacuumPageMiss did not count the blocks if its\n> read was already completed by other backends [2]. Now,\n> 'pgBufferUsage.local_blks_read + pgBufferUsage.shared_blks_read'\n> counts every block attempted to be read; possibly double counting if\n> someone else has already completed the read. I do not know which\n> behaviour is correct but I wanted to mention this.\n>\n> [1] https://postgr.es/m/CAO6_Xqr__kTTCLkftqS0qSCm-J7_xbRG3Ge2rWhucxQJMJhcRA%40mail.gmail.com\n>\n> [2] In the WaitReadBuffers() function, see comment:\n> /*\n> * Skip this block if someone else has already completed it. If an\n> * I/O is already in progress in another backend, this will wait for\n> * the outcome: either done, or something went wrong and we will\n> * retry.\n> */\n>\n-- \nRegards,\nAlena Rybakina\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n",
"msg_date": "Fri, 10 May 2024 14:49:56 +0300",
"msg_from": "Alena Rybakina <lena.ribackina@yandex.ru>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "Hi,\n\nOn Fri, 10 May 2024 at 14:49, Alena Rybakina <lena.ribackina@yandex.ru> wrote:\n>\n> Hi! I could try to check it with the test, but I want to ask you about\n> details, because I'm not sure that I completely understand the test case.\n>\n> You mean that we need to have two backends and on one of them we deleted\n> the tuples before vacuum called the other, do you?\n>\n\nI think triggering a parallel vacuum is enough. I am able to see the\ndifferences with the following:\n\nYou can apply the attached diff file to see the differences between\nthe previous version and the patched version. Then, run this query:\n\nCREATE TABLE vacuum_fix (aid int, bid int, cid int) with\n(autovacuum_enabled=false);\nINSERT INTO vacuum_fix SELECT *, *, * FROM generate_series(1, 1000000);\nCREATE INDEX a_idx on vacuum_fix (aid);\nCREATE INDEX b_idx on vacuum_fix (bid);\nCREATE INDEX c_idx on vacuum_fix (cid);\nVACUUM vacuum_fix;\nUPDATE vacuum_fix SET aid = aid + 1;\nVACUUM (VERBOSE, PARALLEL 2) vacuum_fix ;\n\nAfter that I saw:\n\nINFO: vacuuming \"test.public.vacuum_fix\"\nINFO: launched 2 parallel vacuum workers for index vacuuming (planned: 2)\nINFO: finished vacuuming \"test.public.vacuum_fix\": index scans: 1\n...\n...\nbuffer usage: 29343 hits, 9580 misses in the previous version, 14165\nmisses in the patched version, 14262 dirtied\n\nPatched version counts 14165 misses but the previous version counts\n9580 misses in this specific example.\n\n--\nRegards,\nNazir Bilal Yavuz\nMicrosoft",
"msg_date": "Fri, 10 May 2024 16:21:20 +0300",
"msg_from": "Nazir Bilal Yavuz <byavuz81@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "Hi,\n\nOn Fri, 10 May 2024 at 16:21, Nazir Bilal Yavuz <byavuz81@gmail.com> wrote:\n>\n> Hi,\n>\n> On Fri, 10 May 2024 at 14:49, Alena Rybakina <lena.ribackina@yandex.ru> wrote:\n> >\n> > Hi! I could try to check it with the test, but I want to ask you about\n> > details, because I'm not sure that I completely understand the test case.\n> >\n> > You mean that we need to have two backends and on one of them we deleted\n> > the tuples before vacuum called the other, do you?\n> >\n>\n> I think triggering a parallel vacuum is enough. I am able to see the\n> differences with the following:\n>\n> You can apply the attached diff file to see the differences between\n> the previous version and the patched version. Then, run this query:\n>\n> CREATE TABLE vacuum_fix (aid int, bid int, cid int) with\n> (autovacuum_enabled=false);\n> INSERT INTO vacuum_fix SELECT *, *, * FROM generate_series(1, 1000000);\n> CREATE INDEX a_idx on vacuum_fix (aid);\n> CREATE INDEX b_idx on vacuum_fix (bid);\n> CREATE INDEX c_idx on vacuum_fix (cid);\n> VACUUM vacuum_fix;\n> UPDATE vacuum_fix SET aid = aid + 1;\n> VACUUM (VERBOSE, PARALLEL 2) vacuum_fix ;\n>\n> After that I saw:\n>\n> INFO: vacuuming \"test.public.vacuum_fix\"\n> INFO: launched 2 parallel vacuum workers for index vacuuming (planned: 2)\n> INFO: finished vacuuming \"test.public.vacuum_fix\": index scans: 1\n> ...\n> ...\n> buffer usage: 29343 hits, 9580 misses in the previous version, 14165\n> misses in the patched version, 14262 dirtied\n>\n> Patched version counts 14165 misses but the previous version counts\n> 9580 misses in this specific example.\n\nI am sorry that I showed the wrong thing, this is exactly what is\nfixed in this patch. Actually, I do not know how to trigger it;\ncurrently I am looking for it. I will share if anything comes to my\nmind.\n\n-- \nRegards,\nNazir Bilal Yavuz\nMicrosoft",
"msg_date": "Fri, 10 May 2024 16:55:47 +0300",
"msg_from": "Nazir Bilal Yavuz <byavuz81@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "Hi,\n\nOn Fri, 10 May 2024 at 16:55, Nazir Bilal Yavuz <byavuz81@gmail.com> wrote:\n>\n> Hi,\n>\n> On Fri, 10 May 2024 at 16:21, Nazir Bilal Yavuz <byavuz81@gmail.com> wrote:\n> >\n> > Hi,\n> >\n> > On Fri, 10 May 2024 at 14:49, Alena Rybakina <lena.ribackina@yandex.ru> wrote:\n> > >\n> > > Hi! I could try to check it with the test, but I want to ask you about\n> > > details, because I'm not sure that I completely understand the test case.\n> > >\n> > > You mean that we need to have two backends and on one of them we deleted\n> > > the tuples before vacuum called the other, do you?\n> > >\n\nThere should be some other backend(s) which will try to read the same\nbuffer with the ongoing VACUUM operation. I think it works now but the\nreproduction steps are a bit racy. See:\n\n1- Build Postgres with attached diff, it is the same\nsee_previous_output.diff that I shared two mails ago.\n\n2- Run Postgres, all settings are default.\n\n3- Use two client backends, let's name them as A and B client backends.\n\n4- On A client backend, run:\n\nCREATE TABLE vacuum_fix (aid int, bid int) with (autovacuum_enabled=false);\nINSERT INTO vacuum_fix SELECT *, * FROM generate_series(1, 20000000);\nVACUUM vacuum_fix;\nUPDATE vacuum_fix SET aid = aid + 1, bid = bid + 1;\n\n5- Now it will be a bit racy, SQL commands below need to be run at the\nsame time. The aim is for VACUUM on A client backend and SELECT on B\nclient backend to read the same buffers at the same time. So, some of\nthe buffers will be double counted.\n\nFirstly, run VACUUM on A client backend; immediately after running\nVACUUM, run SELECT on B backend.\n\nA client backend:\nVACUUM VERBOSE vacuum_fix;\n\nB client backend:\nSELECT * from vacuum_fix WHERE aid = -1;\n\nThis is the output of the VACUUM VERBOSE on my end:\n\nINFO: vacuuming \"test.public.vacuum_fix\"\nINFO: finished vacuuming \"test.public.vacuum_fix\": index scans: 0\npages: 0 removed, 176992 remain, 176992 scanned (100.00% of total)\n...\n...\nbuffer usage: 254181 hits, 99030 misses in the previous version, 99865\nmisses in the patched version, 106830 dirtied\n...\nVACUUM\nTime: 2578.217 ms (00:02.578)\n\nVACUUM does not run parallel, so this test case does not trigger what\nis fixed in this thread. As it can be seen, there is ~1000 buffers\ndifference.\n\nI am not sure if there is an easier way to reproduce this but I hope this helps.\n\n-- \nRegards,\nNazir Bilal Yavuz\nMicrosoft",
"msg_date": "Fri, 10 May 2024 18:55:27 +0300",
"msg_from": "Nazir Bilal Yavuz <byavuz81@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "On Fri, May 10, 2024 at 7:26 PM Nazir Bilal Yavuz <byavuz81@gmail.com> wrote:\n>\n> Hi,\n>\n> Thank you for working on this!\n>\n> On Wed, 1 May 2024 at 06:37, Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> >\n> > Thank you for further testing! I've pushed the patch.\n>\n> I realized a behaviour change while looking at 'Use pgBufferUsage for\n> block reporting in analyze' thread [1]. Since that change applies here\n> as well, I thought it is better to mention it here.\n>\n> Before this commit, VacuumPageMiss did not count the blocks if its\n> read was already completed by other backends [2]. Now,\n> 'pgBufferUsage.local_blks_read + pgBufferUsage.shared_blks_read'\n> counts every block attempted to be read; possibly double counting if\n> someone else has already completed the read.\n\nTrue. IIUC there is such a difference only in HEAD but not in v15 and\nv16. The following comment in WaitReadBuffers() says that it's a\ntraditional behavior that we count blocks as read even if someone else\nhas already completed its I/O:\n\n /*\n * We count all these blocks as read by this backend. This is traditional\n * behavior, but might turn out to be not true if we find that someone\n * else has beaten us and completed the read of some of these blocks. In\n * that case the system globally double-counts, but we traditionally don't\n * count this as a \"hit\", and we don't have a separate counter for \"miss,\n * but another backend completed the read\".\n */\n\nSo I think using pgBufferUsage for (parallel) vacuum is a legitimate\nusage and makes it more consistent with other parallel operations.\n\nRegards,\n\n-- \nMasahiko Sawada\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Sat, 11 May 2024 01:09:15 +0900",
"msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
},
{
"msg_contents": "Hi,\n\nOn Fri, 10 May 2024 at 19:09, Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n>\n> On Fri, May 10, 2024 at 7:26 PM Nazir Bilal Yavuz <byavuz81@gmail.com> wrote:\n> >\n> > Hi,\n> >\n> > Thank you for working on this!\n> >\n> > On Wed, 1 May 2024 at 06:37, Masahiko Sawada <sawada.mshk@gmail.com> wrote:\n> > >\n> > > Thank you for further testing! I've pushed the patch.\n> >\n> > I realized a behaviour change while looking at 'Use pgBufferUsage for\n> > block reporting in analyze' thread [1]. Since that change applies here\n> > as well, I thought it is better to mention it here.\n> >\n> > Before this commit, VacuumPageMiss did not count the blocks if its\n> > read was already completed by other backends [2]. Now,\n> > 'pgBufferUsage.local_blks_read + pgBufferUsage.shared_blks_read'\n> > counts every block attempted to be read; possibly double counting if\n> > someone else has already completed the read.\n>\n> True. IIUC there is such a difference only in HEAD but not in v15 and\n> v16. The following comment in WaitReadBuffers() says that it's a\n> traditional behavior that we count blocks as read even if someone else\n> has already completed its I/O:\n>\n> /*\n> * We count all these blocks as read by this backend. This is traditional\n> * behavior, but might turn out to be not true if we find that someone\n> * else has beaten us and completed the read of some of these blocks. In\n> * that case the system globally double-counts, but we traditionally don't\n> * count this as a \"hit\", and we don't have a separate counter for \"miss,\n> * but another backend completed the read\".\n> */\n>\n> So I think using pgBufferUsage for (parallel) vacuum is a legitimate\n> usage and makes it more consistent with other parallel operations.\n\nThat sounds logical. Thank you for the clarification.\n\n-- \nRegards,\nNazir Bilal Yavuz\nMicrosoft\n\n\n",
"msg_date": "Mon, 13 May 2024 16:10:39 +0300",
"msg_from": "Nazir Bilal Yavuz <byavuz81@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Fix parallel vacuum buffer usage reporting"
}
] |
[
{
"msg_contents": "Hello,\n\nThe patch attached fixes an oversight/inconsistency of disallowing the\npg_monitor system role to execute pg_current_logfile([text]).\n\npgwatch3=# create user joe;\nCREATE ROLE\npgwatch3=# set role joe;\nSET\npgwatch3=> select pg_current_logfile();\nERROR: permission denied for function pg_current_logfile\npgwatch3=> reset role;\nRESET\npgwatch3=# grant pg_monitor to joe;\nGRANT ROLE\npgwatch3=# set role joe;\nSET\npgwatch3=> select pg_current_logfile();\nERROR: permission denied for function pg_current_logfile\npgwatch3=> select * FROM pg_ls_logdir();\n name | size | modification\n----------------------------------+----------+------------------------\n postgresql-2024-02-08_130906.log | 652 | 2024-02-08 13:10:04+01\n(5 rows)\n\nBest regards,\nPavlo Golub",
"msg_date": "Fri, 9 Feb 2024 16:01:58 +0100",
"msg_from": "Pavlo Golub <pavlo.golub@cybertec.at>",
"msg_from_op": true,
"msg_subject": "[PATCH] allow pg_current_logfile() execution under pg_monitor role"
},
{
"msg_contents": "On Fri, Feb 09, 2024 at 04:01:58PM +0100, Pavlo Golub wrote:\n> The patch attached fixes an oversight/inconsistency of disallowing the\n> pg_monitor system role to execute pg_current_logfile([text]).\n\nI think this is reasonable. We allow pg_monitor to execute functions like\npg_ls_logdir(), so it doesn't seem like much of a stretch to expect it to\nhave privileges for pg_current_logfile(), too. Are there any other\nfunctions that pg_monitor ought to have privileges for?\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Fri, 9 Feb 2024 10:36:57 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: [PATCH] allow pg_current_logfile() execution under pg_monitor\n role"
},
{
"msg_contents": "> Are there any other\n>functions that pg_monitor ought to have privileges for?\n>\nNot that I'm aware of at the moment. This one was found by chance.\n\nKind regards,\nPavlo Golub\n\n Are there any other\nfunctions that pg_monitor ought to have privileges for?\nNot that I'm aware of at the moment. This one was found by chance.Kind regards,Pavlo Golub",
"msg_date": "Mon, 12 Feb 2024 12:27:54 +0000",
"msg_from": "\"Pavlo Golub\" <pavlo.golub@cybertec.at>",
"msg_from_op": false,
"msg_subject": "Re[2]: [PATCH] allow pg_current_logfile() execution under pg_monitor\n role"
},
{
"msg_contents": "On Mon, Feb 12, 2024 at 12:27:54PM +0000, Pavlo Golub wrote:\n>> Are there any other\n>> functions that pg_monitor ought to have privileges for?\n>> \n> Not that I'm aware of at the moment. This one was found by chance.\n\nOkay. I'll plan on committing this in the next few days.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Mon, 12 Feb 2024 09:49:45 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: [PATCH] allow pg_current_logfile() execution under pg_monitor\n role"
},
{
"msg_contents": "On Mon, Feb 12, 2024 at 09:49:45AM -0600, Nathan Bossart wrote:\n> Okay. I'll plan on committing this in the next few days.\n\nHere is what I have staged for commit.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com",
"msg_date": "Tue, 13 Feb 2024 15:29:28 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: [PATCH] allow pg_current_logfile() execution under pg_monitor\n role"
},
{
"msg_contents": "> On 13 Feb 2024, at 22:29, Nathan Bossart <nathandbossart@gmail.com> wrote:\n> \n> On Mon, Feb 12, 2024 at 09:49:45AM -0600, Nathan Bossart wrote:\n>> Okay. I'll plan on committing this in the next few days.\n> \n> Here is what I have staged for commit.\n\nLGTM.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Wed, 14 Feb 2024 08:59:06 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: [PATCH] allow pg_current_logfile() execution under pg_monitor\n role"
},
{
"msg_contents": "On Wed, Feb 14, 2024 at 08:59:06AM +0100, Daniel Gustafsson wrote:\n> LGTM.\n\nCommitted.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Wed, 14 Feb 2024 11:50:23 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: [PATCH] allow pg_current_logfile() execution under pg_monitor\n role"
},
{
"msg_contents": "\n\n>On Mon, Feb 12, 2024 at 09:49:45AM -0600, Nathan Bossart wrote:\n>> Okay. I'll plan on committing this in the next few days.\n>\n>Here is what I have staged for commit.\n>\nOh, thanks! I forgot, indeed, to update docs and catalog version! My \nbad!\nIn my defense, I was trying to find tests but I missed \nregress/sql/misc_functions.sql somehow.\nNow I will know. Thanks again!\n\nBest regards,\nPavlo Golub\n\n\n",
"msg_date": "Wed, 14 Feb 2024 18:05:41 +0000",
"msg_from": "\"Pavlo Golub\" <pavlo.golub@cybertec.at>",
"msg_from_op": false,
"msg_subject": "Re[2]: [PATCH] allow pg_current_logfile() execution under pg_monitor\n role"
},
{
"msg_contents": "\"Pavlo Golub\" <pavlo.golub@cybertec.at> writes:\n> Oh, thanks! I forgot, indeed, to update docs and catalog version! My \n> bad!\n\nDocs, yes, but don't include catversion bumps in submitted patches.\nThey'll just lead to merge problems when somebody else changes the\ncurrent catversion. We rely on the committer to remember to do this\n(which is an imperfect system, but...)\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Wed, 14 Feb 2024 13:45:31 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Re[2]: [PATCH] allow pg_current_logfile() execution under\n pg_monitor role"
},
{
"msg_contents": "On Wed, Feb 14, 2024, 19:45 Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> \"Pavlo Golub\" <pavlo.golub@cybertec.at> writes:\n> > Oh, thanks! I forgot, indeed, to update docs and catalog version! My\n> > bad!\n>\n> Docs, yes, but don't include catversion bumps in submitted patches.\n> They'll just lead to merge problems when somebody else changes the\n> current catversion. We rely on the committer to remember to do this\n> (which is an imperfect system, but...)\n>\n\nThanks for the clarification.\n\n\n> regards, tom lane\n>\n\nOn Wed, Feb 14, 2024, 19:45 Tom Lane <tgl@sss.pgh.pa.us> wrote:\"Pavlo Golub\" <pavlo.golub@cybertec.at> writes:\n> Oh, thanks! I forgot, indeed, to update docs and catalog version! My \n> bad!\n\nDocs, yes, but don't include catversion bumps in submitted patches.\nThey'll just lead to merge problems when somebody else changes the\ncurrent catversion. We rely on the committer to remember to do this\n(which is an imperfect system, but...)Thanks for the clarification. \n\n regards, tom lane",
"msg_date": "Wed, 14 Feb 2024 19:47:07 +0100",
"msg_from": "Pavlo Golub <pavlo.golub@cybertec.at>",
"msg_from_op": true,
"msg_subject": "Re: Re[2]: [PATCH] allow pg_current_logfile() execution under\n pg_monitor role"
},
{
"msg_contents": "On Wed, Feb 14, 2024 at 01:45:31PM -0500, Tom Lane wrote:\n> \"Pavlo Golub\" <pavlo.golub@cybertec.at> writes:\n>> Oh, thanks! I forgot, indeed, to update docs and catalog version! My \n>> bad!\n> \n> Docs, yes, but don't include catversion bumps in submitted patches.\n> They'll just lead to merge problems when somebody else changes the\n> current catversion. We rely on the committer to remember to do this\n> (which is an imperfect system, but...)\n\n+1, I only included it in the patch I posted so that I didn't forget it...\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Wed, 14 Feb 2024 12:49:56 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Re[2]: [PATCH] allow pg_current_logfile() execution under\n pg_monitor role"
}
] |
[
{
"msg_contents": "Hi,\n\nCurrently the documentation of upgrade for streaming replication\nsection says that logical replication slots will be copied\nirrespective of the version, but the logical replication slots are\ncopied only if the old primary is version 17.0 or later. The changes\nfor the same are in the attached patch.\n\nThanks and Regards,\nShubham Khanna.",
"msg_date": "Fri, 9 Feb 2024 21:32:05 +0530",
"msg_from": "Shubham Khanna <khannashubham1197@gmail.com>",
"msg_from_op": true,
"msg_subject": "Improve documentation of upgrade for streaming replication section."
},
{
"msg_contents": "On Fri, Feb 9, 2024 at 9:32 PM Shubham Khanna\n<khannashubham1197@gmail.com> wrote:\n>\n> Currently the documentation of upgrade for streaming replication\n> section says that logical replication slots will be copied\n> irrespective of the version, but the logical replication slots are\n> copied only if the old primary is version 17.0 or later. The changes\n> for the same are in the attached patch.\n>\n\nLGTM. I'll push this tomorrow unless I see any comments or objections\nfor the same.\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Mon, 12 Feb 2024 07:59:46 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Improve documentation of upgrade for streaming replication\n section."
},
{
"msg_contents": "On Mon, Feb 12, 2024 at 7:59 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Fri, Feb 9, 2024 at 9:32 PM Shubham Khanna\n> <khannashubham1197@gmail.com> wrote:\n> >\n> > Currently the documentation of upgrade for streaming replication\n> > section says that logical replication slots will be copied\n> > irrespective of the version, but the logical replication slots are\n> > copied only if the old primary is version 17.0 or later. The changes\n> > for the same are in the attached patch.\n> >\n>\n> LGTM. I'll push this tomorrow unless I see any comments or objections\n> for the same.\n>\n\nPushed!\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Tue, 13 Feb 2024 14:23:12 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Improve documentation of upgrade for streaming replication\n section."
}
] |
[
{
"msg_contents": "Hello Hackers,\n\nFolks, When tried to create a function with the same signature as procedure\nit fails.\n\npostgres=# create or replace procedure obj1(char) language plpgsql as $$\n begin select $1; end; $$;\nCREATE PROCEDURE\npostgres=# create or replace function obj1(char) returns void language sql\nas $$ select $1 $$;\nERROR: cannot change routine kind\nDETAIL: \"obj1\" is a procedure.\n\nany reason for failures?\nCan procedure or function can be defined with the same signature i.e. name\nand IN arguments ?\nas callable for both is different.?\n\nHello Hackers,Folks, When tried to create a function with the same signature as procedure it fails.postgres=# create or replace procedure obj1(char) language plpgsql as $$ begin select $1; end; $$;CREATE PROCEDUREpostgres=# create or replace function obj1(char) returns void language sql as $$ select $1 $$;ERROR: cannot change routine kindDETAIL: \"obj1\" is a procedure.any reason for failures?Can procedure or function can be defined with the same signature i.e. name and IN arguments ? as callable for both is different.?",
"msg_date": "Sat, 10 Feb 2024 01:35:18 +0530",
"msg_from": "Deepak M <mahtodeepak05@gmail.com>",
"msg_from_op": true,
"msg_subject": "Function and Procedure with same signature?"
},
{
"msg_contents": "On Fri, Feb 9, 2024, 12:05 Deepak M <mahtodeepak05@gmail.com> wrote:\n\n> Hello Hackers,\n>\n\nWrong list, this is for discussions regarding patches.\n\n\n\n> Folks, When tried to create a function with the same signature as\n> procedure it fails.\n>\n\nThat seems like a good hint you cannot do it. Specifically because they\nget defined in the same internal catalog within which names must be unique.\n\nDavid J.\n\nOn Fri, Feb 9, 2024, 12:05 Deepak M <mahtodeepak05@gmail.com> wrote:Hello Hackers,Wrong list, this is for discussions regarding patches.Folks, When tried to create a function with the same signature as procedure it fails.That seems like a good hint you cannot do it. Specifically because they get defined in the same internal catalog within which names must be unique.David J.",
"msg_date": "Fri, 9 Feb 2024 14:47:23 -0800",
"msg_from": "\"David G. Johnston\" <david.g.johnston@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Function and Procedure with same signature?"
},
{
"msg_contents": "\"David G. Johnston\" <david.g.johnston@gmail.com> writes:\n> On Fri, Feb 9, 2024, 12:05 Deepak M <mahtodeepak05@gmail.com> wrote:\n>> Folks, When tried to create a function with the same signature as\n>> procedure it fails.\n\n> That seems like a good hint you cannot do it. Specifically because they\n> get defined in the same internal catalog within which names must be unique.\n\nWorth noting perhaps that this is actually required by the SQL\nstandard: per spec, functions and procedures are both \"routines\"\nand share the same namespace, which is necessary so that commands\nlike DROP ROUTINE are well-defined.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Fri, 09 Feb 2024 18:38:02 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Function and Procedure with same signature?"
},
{
"msg_contents": "Hi Tom\n\nOn Sat, Feb 10, 2024 at 12:38 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> \"David G. Johnston\" <david.g.johnston@gmail.com> writes:\n> > On Fri, Feb 9, 2024, 12:05 Deepak M <mahtodeepak05@gmail.com> wrote:\n> >> Folks, When tried to create a function with the same signature as\n> >> procedure it fails.\n>\n> > That seems like a good hint you cannot do it. Specifically because they\n> > get defined in the same internal catalog within which names must be unique.\n\nThe fact that we currently enforce it this way seems like an\nimplementation deficiency that should be fixed.\n\nBringing this up again, as there seems to be no good reason to have\nthis restriction as there is no place in the call syntax where it\nwould be unclear if a FUNCTION or a PROCEDURE is used.\n\nAnd at least Oracle does allow this (and possibly others) so having\nthis unnecessary restriction in PostgreSQL makes migrations from\nOracle applications where this feature is used needlessly complicated.\n\n> Worth noting perhaps that this is actually required by the SQL\n> standard: per spec, functions and procedures are both \"routines\"\n> and share the same namespace,\n\nCan you point me to a place in the standard where it requires all\nkinds of ROUTINES to be using the same namespace ?\n\nAll I could find was that ROUTINES are either FUNCTIONS, PROCEDURES or\nMETHODS and then samples of their usage which made clear that all\nthree are different and usage is disjoint at syntax level.\n\nAs for DROP ROUTINE we could just raise an error and recommend using\nmore specific DROP FUNCTION or DROP PROCEDURE if there is ambiguity.\n\n--------------\nBest Regards\nHannu\n\n\n",
"msg_date": "Thu, 7 Mar 2024 10:54:50 +0100",
"msg_from": "Hannu Krosing <hannuk@google.com>",
"msg_from_op": false,
"msg_subject": "Re: Function and Procedure with same signature?"
},
{
"msg_contents": "Hannu Krosing <hannuk@google.com> writes:\n> On Sat, Feb 10, 2024 at 12:38 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Worth noting perhaps that this is actually required by the SQL\n>> standard: per spec, functions and procedures are both \"routines\"\n>> and share the same namespace,\n\n> Can you point me to a place in the standard where it requires all\n> kinds of ROUTINES to be using the same namespace ?\n\n[ digs around a bit... ] Well, the spec is vaguer about this than\nI thought. It is clear on one thing: 11.60 <SQL-invoked routine>\nconformance rules include\n\n 2) Without Feature T341, “Overloading of SQL-invoked functions and\n SQL-invoked procedures”, conforming SQL language shall not\n contain a <schema routine> in which the schema identified by the\n explicit or implicit <schema name> of the <schema qualified\n routine name> includes a routine descriptor whose routine name is\n <schema qualified routine name>.\n\n(\"<schema routine>\" means a CREATE FUNCTION or CREATE PROCEDURE\nstatement.)\n\nThat is, basic SQL doesn't allow you to have two routines with the\nsame qualified name at all, whether they have different types and\nparameter lists or not. Now the above text is the entire definition\nof T341, and it doesn't say just what an implementation that claims\nfeature T341 is expected to allow. Looking through the rest of 11.60,\nwe find\n\n 9) u) The schema identified by the explicit or implicit <schema\n name> of the <specific name> shall not include a routine\n descriptor whose specific name is equivalent to <specific name> or\n a user-defined type descriptor that includes a method\n specification descriptor whose specific name is equivalent to\n <specific name>.\n\nwhich evidently is describing the base case (with no mention of T341).\nWe also find\n\n 20) Case:\n\n a) If R is an SQL-invoked procedure, then S shall not include\n another SQL-invoked procedure whose <schema qualified routine\n name> is equivalent to RN and whose number of SQL parameters is\n PN.\n\nwhich is a weird halfway measure indeed, and there's no\nacknowledgement that this contradicts 9u. The other arm of the case\nis pretty impenetrable prose, but what it appears to be saying is that\nyou can't create two functions of the same name and same number of\nparameters if that would create any call-time ambiguity, that is that\na call could be written that might refer to either. So I guess these\nparas are meant to explain what should happen if T341 is implemented,\nbut it's far from clear, and certainly their restrictions on\noverloading are much stronger than what we allow.\n\nIf you look in 10.6 <specific routine designator> (which is what is\nreferenced by 11.62 <drop routine statement>) you find\n\n 4) If <routine type> specifies ROUTINE, then there shall be\n exactly one SQL-invoked routine in the schema identified by SCN\n whose <schema qualified routine name> is RN such that, for all i,\n 1 (one) ≤ i ≤ the number of arguments, when the Syntax Rules of\n Subclause 9.25, “Data type identity”, are applied with the\n declared type of its i-th SQL parameter as TYPE1 and the i-th\n <data type> in the <data type list> of MN as TYPE2, those Syntax\n Rules are satisfied. The <specific routine designator> identifies\n that SQL-invoked routine.\n\nIt could be argued that this doesn't prohibit having both a function\nand a procedure with the same data type list, only that you can't\nwrite ROUTINE when trying to drop or alter one. But I think that's\njust motivated reasoning. The paragraphs for <routine type> being\nFUNCTION or PROCEDURE are exactly like the above except they say\n\"exactly one function\" or \"exactly one procedure\". If you argue that\nthis text means we must allow functions and procedures with the same\nparameter lists, then you are also arguing that we must allow multiple\nfunctions with the same parameter lists, and it's just the user's\ntough luck if they need to drop one of them.\n\nA related point is that our tolerance for overloading routine\nnames isn't unlimited: we don't allow duplicate names with the\nsame list of input parameters, even if the output parameters are\ndifferent. This is not something that the SQL spec cares to\naddress, but there are good ambiguity-avoidance reasons for it.\nI think limiting overloading so that a ROUTINE specification is\nunambiguous is also a good thing.\n\nI remain unexcited about changing our definition of this.\n\"Oracle allows it\" is not something that has any weight in\nmy view: they have made a bunch of bad design decisions\nas well as good ones, and I think this is a bad one.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Thu, 07 Mar 2024 11:46:32 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: Function and Procedure with same signature?"
},
{
"msg_contents": "On Thu, Mar 7, 2024 at 5:46 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Hannu Krosing <hannuk@google.com> writes:\n> > On Sat, Feb 10, 2024 at 12:38 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >> Worth noting perhaps that this is actually required by the SQL\n> >> standard: per spec, functions and procedures are both \"routines\"\n> >> and share the same namespace,\n>\n> > Can you point me to a place in the standard where it requires all\n> > kinds of ROUTINES to be using the same namespace ?\n>\n> [ digs around a bit... ] Well, the spec is vaguer about this than\n> I thought. It is clear on one thing: 11.60 <SQL-invoked routine>\n> conformance rules include\n...\n\nThanks for thorough analysis of the standard.\n\nI went and looked at more what other relevant database do in this\nspace based on their documentation\n\nTl;DR\n\n* MS SQL Server\n - no overloading allowed anywhere\n* MySQL\n - no overloading\n* Oracle\n - no overloading at top level\n - overloading and independent namespaces for functions and procedures\n* Teradata\n - function overloading allowed\n - not clear from documentation if this also applies procedures\n - function overloading docs does not mention possible clashes with\nprocedure names anywhere\n* DB2\n - function overloading fully supported\n - procedure overloading supported, but only for distinct NUMBER OF ARGUMENTS\n\nI'll try to get access to a Teradata instance to verify the above\n\nSo at high level most other Serious Databases\n - do support function overloading\n - keep functions and procedures in separated namespaces\n\nI still think that PostgreSQL having functions and procedures share\nthe same namespace is an unneeded and unjustified restriction\n\n\nI plan to do some hands-on testing on Teradata and DB2 to understand it\n\nBut my current thinking is that we should not be more restrictive than\nothers unless there is a strong technical reason for it. And currently\nI do not see any.\n\n> It could be argued that this doesn't prohibit having both a function\n> and a procedure with the same data type list, only that you can't\n> write ROUTINE when trying to drop or alter one. But I think that's\n> just motivated reasoning. The paragraphs for <routine type> being\n> FUNCTION or PROCEDURE are exactly like the above except they say\n> \"exactly one function\" or \"exactly one procedure\". If you argue that\n> this text means we must allow functions and procedures with the same\n> parameter lists, then you are also arguing that we must allow multiple\n> functions with the same parameter lists, and it's just the user's\n> tough luck if they need to drop one of them.\n\nThe main issue is not dropping them, but inability to determine which\none to call.\n\nWe already have this in case of two overloaded functions with same\ninitial argument types and the rest having defaults - when\n\n---\nhannuk=# create function get(i int, out o int) begin atomic select i; end;\nCREATE FUNCTION\nhannuk=# create function get(i int, j int default 0, out o int) begin\natomic select i+j; end;\nCREATE FUNCTION\nhannuk=# select get(1);\nERROR: function get(integer) is not unique\nLINE 1: select get(1);\n ^\nHINT: Could not choose a best candidate function. You might need to\nadd explicit type casts.\n---\n\n> A related point is that our tolerance for overloading routine\n> names isn't unlimited: we don't allow duplicate names with the\n> same list of input parameters, even if the output parameters are\n> different.\n\nThis again has a good reason, as there would be many cases where you\ncould not decide which one to call\n\nNot allowing overloading based on only return types is common across\nall OO languages.\n\nMy point is that this does not apply to FUNCTION vs. PROCEDURE as it\nis very clear from the CALL syntax which one is meant.\n\n> This is not something that the SQL spec cares to\n> address, but there are good ambiguity-avoidance reasons for it.\n> I think limiting overloading so that a ROUTINE specification is\n> unambiguous is also a good thing.\n\nI think ROUTINE being unambiguous is not e very good goal.\n\nWhat if next version of standard introduces DROP DATABASE OBJECT ?\n\n> I remain unexcited about changing our definition of this.\n> \"Oracle allows it\" is not something that has any weight in\n> my view: they have made a bunch of bad design decisions\n> as well as good ones, and I think this is a bad one.\n\nFully agree that \"Oracle allows it\" is a non-argument.\n\nMy main point is that there is no strong reason to have objects which\nare distinct at syntax level to be in the same namespace.\n\n# Oracle is actually much more restrictive in top level object namespace -\n\nAll of the following share the same namespace - [Packages, Private\nsynonyms, Sequences, Stand-alone procedures, Stand-alone stored\nfunctions, Tables, User-defined operators, User-defined types, Views].\n(I guess this makes parser easier to write)\n\nThe equivalent in postgreSQL would be [extensions, schemas, tables,\nprocedures, functions and a few more] all sharing the namespace.\n\nWhere Oracle *does* allow overloading is \"packaged functions and\nprocedures\" which are probably using a separate parser altogether.\n\nMy (wildly speculative) explanation of the above is that when creating\nthe top-level syntax requirements it was easiest to just not allow any\nneed to complex determination as the aim was to get the whole thing\nout quickly.\n\nLater, when adding the package support there was more time to pay\nattention to eas-of-use for developers, so overloading and\nnon-name-basesd distinction between objects, including functions and\nprocedures was added.\n\n# DB2- I also checked wher DB2 does and it has a different set of rules\n\n1. FUNCTIONS and METHODS share a namespace in a way that when\noverloading the \"type instance\" of a method is moved to first argument\nof function and then the uniqueness of argument list is checked.\n\n2. PROCEDURES can be overloaded but you can not have two procedures\nwith same NUMBER OF ARGUMENTS irrespective of types\n\nbut there is no mention anywhere about signatures having to be\ndifferent between FUNCTIONS and PROCEDURES.\n\n\n",
"msg_date": "Mon, 11 Mar 2024 12:55:13 +0100",
"msg_from": "Hannu Krosing <hannuk@google.com>",
"msg_from_op": false,
"msg_subject": "Re: Function and Procedure with same signature?"
},
{
"msg_contents": "Hi Peter and Tom\n\nFollowing up on our conversation art pgcon.dev\n\nIf I understood correctly Peter has some old patch for splitting the\nnamespaces which could be resurrected to try to move forward on this ?\n\nCan you share what you did there ?\n\nAlso, while at it we should extend the function lookup to support full\n\"method call syntax\" in general, up from one-argument case so that\n\nSELECT function(a_thing, arg2, arg 2, ...)\n\ncould also be called as\n\nSELECT a_thing.function(arg2, arg 2, ...)\n\n\n--\nHannu\n\n\n\nOn Mon, Mar 11, 2024 at 12:55 PM Hannu Krosing <hannuk@google.com> wrote:\n>\n> On Thu, Mar 7, 2024 at 5:46 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >\n> > Hannu Krosing <hannuk@google.com> writes:\n> > > On Sat, Feb 10, 2024 at 12:38 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > >> Worth noting perhaps that this is actually required by the SQL\n> > >> standard: per spec, functions and procedures are both \"routines\"\n> > >> and share the same namespace,\n> >\n> > > Can you point me to a place in the standard where it requires all\n> > > kinds of ROUTINES to be using the same namespace ?\n> >\n> > [ digs around a bit... ] Well, the spec is vaguer about this than\n> > I thought. It is clear on one thing: 11.60 <SQL-invoked routine>\n> > conformance rules include\n> ...\n>\n> Thanks for thorough analysis of the standard.\n>\n> I went and looked at more what other relevant database do in this\n> space based on their documentation\n>\n> Tl;DR\n>\n> * MS SQL Server\n> - no overloading allowed anywhere\n> * MySQL\n> - no overloading\n> * Oracle\n> - no overloading at top level\n> - overloading and independent namespaces for functions and procedures\n> * Teradata\n> - function overloading allowed\n> - not clear from documentation if this also applies procedures\n> - function overloading docs does not mention possible clashes with\n> procedure names anywhere\n> * DB2\n> - function overloading fully supported\n> - procedure overloading supported, but only for distinct NUMBER OF ARGUMENTS\n>\n> I'll try to get access to a Teradata instance to verify the above\n>\n> So at high level most other Serious Databases\n> - do support function overloading\n> - keep functions and procedures in separated namespaces\n>\n> I still think that PostgreSQL having functions and procedures share\n> the same namespace is an unneeded and unjustified restriction\n>\n>\n> I plan to do some hands-on testing on Teradata and DB2 to understand it\n>\n> But my current thinking is that we should not be more restrictive than\n> others unless there is a strong technical reason for it. And currently\n> I do not see any.\n>\n> > It could be argued that this doesn't prohibit having both a function\n> > and a procedure with the same data type list, only that you can't\n> > write ROUTINE when trying to drop or alter one. But I think that's\n> > just motivated reasoning. The paragraphs for <routine type> being\n> > FUNCTION or PROCEDURE are exactly like the above except they say\n> > \"exactly one function\" or \"exactly one procedure\". If you argue that\n> > this text means we must allow functions and procedures with the same\n> > parameter lists, then you are also arguing that we must allow multiple\n> > functions with the same parameter lists, and it's just the user's\n> > tough luck if they need to drop one of them.\n>\n> The main issue is not dropping them, but inability to determine which\n> one to call.\n>\n> We already have this in case of two overloaded functions with same\n> initial argument types and the rest having defaults - when\n>\n> ---\n> hannuk=# create function get(i int, out o int) begin atomic select i; end;\n> CREATE FUNCTION\n> hannuk=# create function get(i int, j int default 0, out o int) begin\n> atomic select i+j; end;\n> CREATE FUNCTION\n> hannuk=# select get(1);\n> ERROR: function get(integer) is not unique\n> LINE 1: select get(1);\n> ^\n> HINT: Could not choose a best candidate function. You might need to\n> add explicit type casts.\n> ---\n>\n> > A related point is that our tolerance for overloading routine\n> > names isn't unlimited: we don't allow duplicate names with the\n> > same list of input parameters, even if the output parameters are\n> > different.\n>\n> This again has a good reason, as there would be many cases where you\n> could not decide which one to call\n>\n> Not allowing overloading based on only return types is common across\n> all OO languages.\n>\n> My point is that this does not apply to FUNCTION vs. PROCEDURE as it\n> is very clear from the CALL syntax which one is meant.\n>\n> > This is not something that the SQL spec cares to\n> > address, but there are good ambiguity-avoidance reasons for it.\n> > I think limiting overloading so that a ROUTINE specification is\n> > unambiguous is also a good thing.\n>\n> I think ROUTINE being unambiguous is not e very good goal.\n>\n> What if next version of standard introduces DROP DATABASE OBJECT ?\n>\n> > I remain unexcited about changing our definition of this.\n> > \"Oracle allows it\" is not something that has any weight in\n> > my view: they have made a bunch of bad design decisions\n> > as well as good ones, and I think this is a bad one.\n>\n> Fully agree that \"Oracle allows it\" is a non-argument.\n>\n> My main point is that there is no strong reason to have objects which\n> are distinct at syntax level to be in the same namespace.\n>\n> # Oracle is actually much more restrictive in top level object namespace -\n>\n> All of the following share the same namespace - [Packages, Private\n> synonyms, Sequences, Stand-alone procedures, Stand-alone stored\n> functions, Tables, User-defined operators, User-defined types, Views].\n> (I guess this makes parser easier to write)\n>\n> The equivalent in postgreSQL would be [extensions, schemas, tables,\n> procedures, functions and a few more] all sharing the namespace.\n>\n> Where Oracle *does* allow overloading is \"packaged functions and\n> procedures\" which are probably using a separate parser altogether.\n>\n> My (wildly speculative) explanation of the above is that when creating\n> the top-level syntax requirements it was easiest to just not allow any\n> need to complex determination as the aim was to get the whole thing\n> out quickly.\n>\n> Later, when adding the package support there was more time to pay\n> attention to eas-of-use for developers, so overloading and\n> non-name-basesd distinction between objects, including functions and\n> procedures was added.\n>\n> # DB2- I also checked wher DB2 does and it has a different set of rules\n>\n> 1. FUNCTIONS and METHODS share a namespace in a way that when\n> overloading the \"type instance\" of a method is moved to first argument\n> of function and then the uniqueness of argument list is checked.\n>\n> 2. PROCEDURES can be overloaded but you can not have two procedures\n> with same NUMBER OF ARGUMENTS irrespective of types\n>\n> but there is no mention anywhere about signatures having to be\n> different between FUNCTIONS and PROCEDURES.\n\n\n",
"msg_date": "Thu, 6 Jun 2024 13:09:38 +0200",
"msg_from": "Hannu Krosing <hannuk@google.com>",
"msg_from_op": false,
"msg_subject": "Re: Function and Procedure with same signature?"
}
] |
[
{
"msg_contents": "I played with include-what-you-use (IWYU), \"a tool for use with clang to \nanalyze #includes in C and C++ source files\".[0] I came across this via \nclangd (the language server), because clangd (via the editor) kept \nsuggesting a bunch of #includes to remove. And I suppose it was right.\n\nSo as a test, I ran IWYU over the backend *.c files and removed all the \n#includes it suggested. (Note that IWYU also suggests to *add* a bunch \nof #includes, in fact that is its main purpose; I didn't do this here.) \nIn some cases, a more specific #include replaces another less specific \none. (To keep the patch from exploding in size, I ignored for now all \nthe suggestions to replace catalog/pg_somecatalog.h with \ncatalog/pg_somecatalog_d.h.) This ended up with the attached patch, \nwhich has\n\n 432 files changed, 233 insertions(+), 1023 deletions(-)\n\nI tested this with various compilation options (assert, WAL_DEBUG, \nLOCK_DEBUG, different geqo variants, etc.) to make sure a header wasn't \njust used for some conditional code section. Also, again, this patch \ntouches just *.c files, so nothing declared from header files changes in \nhidden ways.\n\nAlso, as a small example, in src/backend/access/transam/rmgr.c you'll \nsee some IWYU pragma annotations to handle a special case there.\n\nThe purpose of this patch is twofold: One, it's of course a nice \ncleanup. Two, this is a test how well IWYU might work for us. If we \nfind either by human interpretation that a change doesn't make sense, or \nsomething breaks on some platform, then that would be useful feedback \n(perhaps to addressed by more pragma annotations or more test coverage).\n\n(Interestingly, IWYU has been mentioned in src/tools/pginclude/README \nsince 2012. Has anyone else played with it? Was it not mature enough \nback then?)\n\n[0]: https://include-what-you-use.org/",
"msg_date": "Sat, 10 Feb 2024 08:40:43 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "backend *.c #include cleanup (IWYU)"
},
{
"msg_contents": "On Sat, Feb 10, 2024 at 08:40:43AM +0100, Peter Eisentraut wrote:\n> The purpose of this patch is twofold: One, it's of course a nice cleanup.\n> Two, this is a test how well IWYU might work for us. If we find either by\n> human interpretation that a change doesn't make sense, or something breaks\n> on some platform, then that would be useful feedback (perhaps to addressed\n> by more pragma annotations or more test coverage).\n> \n> (Interestingly, IWYU has been mentioned in src/tools/pginclude/README since\n> 2012. Has anyone else played with it? Was it not mature enough back then?)\n\nI haven't played with it at all, but the topic reminds me of this thread:\n\n\thttps://postgr.es/m/flat/CALDaNm1B9naPDTm3ox1m_yZvOm3KA5S4kZQSWWAeLHAQ%3D3gV1Q%40mail.gmail.com\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Sat, 10 Feb 2024 14:13:09 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: backend *.c #include cleanup (IWYU)"
},
{
"msg_contents": "On 10.02.24 21:13, Nathan Bossart wrote:\n>> (Interestingly, IWYU has been mentioned in src/tools/pginclude/README since\n>> 2012. Has anyone else played with it? Was it not mature enough back then?)\n> I haven't played with it at all, but the topic reminds me of this thread:\n> \n> \thttps://postgr.es/m/flat/CALDaNm1B9naPDTm3ox1m_yZvOm3KA5S4kZQSWWAeLHAQ%3D3gV1Q%40mail.gmail.com\n\nApproaches like that as well as the in-tree pgrminclude work by \"I \nremoved the #include and it still compiled fine\", which can be \nunreliable. IWYU on the other hand has the compiler tracking where a \nsymbol actually came from, and so if it says that an #include is not \nused, then it's pretty much correct by definition.\n\n\n\n",
"msg_date": "Mon, 12 Feb 2024 17:08:40 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: backend *.c #include cleanup (IWYU)"
},
{
"msg_contents": "On Mon, Feb 12, 2024 at 05:08:40PM +0100, Peter Eisentraut wrote:\n> On 10.02.24 21:13, Nathan Bossart wrote:\n>> I haven't played with it at all, but the topic reminds me of this thread:\n>> \n>> \thttps://postgr.es/m/flat/CALDaNm1B9naPDTm3ox1m_yZvOm3KA5S4kZQSWWAeLHAQ%3D3gV1Q%40mail.gmail.com\n> \n> Approaches like that as well as the in-tree pgrminclude work by \"I removed\n> the #include and it still compiled fine\", which can be unreliable. IWYU on\n> the other hand has the compiler tracking where a symbol actually came from,\n> and so if it says that an #include is not used, then it's pretty much\n> correct by definition.\n\nOkay. FWIW I tend to agree that this is nice cleanup. I'd personally run\nthis before every commit on HEAD if there was an easy way to do so and it\ndidn't cause changes to a bunch of unrelated files, but I understand that\nthe pgindent stuff in the buildfarm isn't super popular. I'd even like to\nhave a tool that automatically adjusted #include ordering to match project\npolicy, assuming one does not already exist.\n\n-- \nNathan Bossart\nAmazon Web Services: https://aws.amazon.com\n\n\n",
"msg_date": "Mon, 12 Feb 2024 10:20:00 -0600",
"msg_from": "Nathan Bossart <nathandbossart@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: backend *.c #include cleanup (IWYU)"
},
{
"msg_contents": "On Sat Feb 10, 2024 at 1:40 AM CST, Peter Eisentraut wrote:\n> I played with include-what-you-use (IWYU), \"a tool for use with clang to \n> analyze #includes in C and C++ source files\".[0] I came across this via \n> clangd (the language server), because clangd (via the editor) kept \n> suggesting a bunch of #includes to remove. And I suppose it was right.\n>\n> So as a test, I ran IWYU over the backend *.c files and removed all the \n> #includes it suggested. (Note that IWYU also suggests to *add* a bunch \n> of #includes, in fact that is its main purpose; I didn't do this here.) \n> In some cases, a more specific #include replaces another less specific \n> one. (To keep the patch from exploding in size, I ignored for now all \n> the suggestions to replace catalog/pg_somecatalog.h with \n> catalog/pg_somecatalog_d.h.) This ended up with the attached patch, \n> which has\n>\n> 432 files changed, 233 insertions(+), 1023 deletions(-)\n>\n> I tested this with various compilation options (assert, WAL_DEBUG, \n> LOCK_DEBUG, different geqo variants, etc.) to make sure a header wasn't \n> just used for some conditional code section. Also, again, this patch \n> touches just *.c files, so nothing declared from header files changes in \n> hidden ways.\n>\n> Also, as a small example, in src/backend/access/transam/rmgr.c you'll \n> see some IWYU pragma annotations to handle a special case there.\n>\n> The purpose of this patch is twofold: One, it's of course a nice \n> cleanup. Two, this is a test how well IWYU might work for us. If we \n> find either by human interpretation that a change doesn't make sense, or \n> something breaks on some platform, then that would be useful feedback \n> (perhaps to addressed by more pragma annotations or more test coverage).\n>\n> (Interestingly, IWYU has been mentioned in src/tools/pginclude/README \n> since 2012. Has anyone else played with it? Was it not mature enough \n> back then?)\n>\n> [0]: https://include-what-you-use.org/\n\nI like this idea. This was something I tried to do but never finished in \nmy last project. I have also been noticing the same issues from clangd. \nHaving more automation around include patterns would be great! I think \nit would be good if there a Meson run_target()/Make .PHONY target that \npeople could use to test too. Then, eventually the cfbot could pick this \nup.\n\n-- \nTristan Partin\nNeon (https://neon.tech)\n\n\n",
"msg_date": "Mon, 12 Feb 2024 11:15:07 -0600",
"msg_from": "\"Tristan Partin\" <tristan@neon.tech>",
"msg_from_op": false,
"msg_subject": "Re: backend *.c #include cleanup (IWYU)"
},
{
"msg_contents": "Hi,\n\nOn 2024-02-10 08:40:43 +0100, Peter Eisentraut wrote:\n> So as a test, I ran IWYU over the backend *.c files and removed all the\n> #includes it suggested. (Note that IWYU also suggests to *add* a bunch of\n> #includes, in fact that is its main purpose; I didn't do this here.) In some\n> cases, a more specific #include replaces another less specific one. (To\n> keep the patch from exploding in size, I ignored for now all the suggestions\n> to replace catalog/pg_somecatalog.h with catalog/pg_somecatalog_d.h.) This\n> ended up with the attached patch, which has\n\nI think this kind of suggested change is why I have been wary of IWYU (and the\nchanges that clangd suggest): By moving indirect includes to .c files you end\nup with implementation details more widely, which can increase the pain of\nrefactoring.\n\nI'd be hesitant to commit to this without a) a policy about adding annotations\nabout when indirect includes shouldn't directly be included b) annotations\nensuring that.\n\n\nWhat were the parameters you used for IWYU? I'm e.g. a bit surprised about the\nchanges to main.c, adding an include for s_lock.h. For one I don't think\ns_lock.h should ever be included directly, but more importantly it seems there\nisn't a reason to include spin.h either, but it's not removed here?\n\nThere are other changes I don't understand. E.g. why is\ncatalog/binary_upgrade.h removed from pg_enum.c? It's actually defining\nbinary_upgrade_next_pg_enum_oid, declared in catalog/binary_upgrade.h?\n\n\nI think some of the changes here could be applied independently of more iwyu\ninfrastructure, e.g. replacing includes of builtins.h with includes of\nfmgrprotos.h. But the larger set of changes seems somewhat hard to judge\nas-is.\n\n\nFWIW, for me the tree with the patch applied doesn't build anymore, presumably\ndue to 8be93177c46.\n../../../../../home/andres/src/postgresql/src/backend/commands/event_trigger.c: In function 'EventTriggerOnLogin':\n../../../../../home/andres/src/postgresql/src/backend/commands/event_trigger.c:955:72: error: 'F_OIDEQ' undeclared (first use in this function)\n 955 | BTEqualStrategyNumber, F_OIDEQ,\n | ^~~~~~~\n../../../../../home/andres/src/postgresql/src/backend/commands/event_trigger.c:955:72: note: each undeclared identifier is reported only once for each function it appears in\n\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Mon, 12 Feb 2024 12:07:06 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: backend *.c #include cleanup (IWYU)"
},
{
"msg_contents": "On 2024-Feb-10, Peter Eisentraut wrote:\n\n> So as a test, I ran IWYU over the backend *.c files and removed all the\n> #includes it suggested. (Note that IWYU also suggests to *add* a bunch of\n> #includes, in fact that is its main purpose; I didn't do this here.) In some\n> cases, a more specific #include replaces another less specific one.\n\nSounds reasonable in principle. I looked at the access/brin changes and\nthey seems OK. Then I noticed the execdebug.h -> executor.h changes and\nwas surprised, until I looked at execdebug.h and though ... maybe we\nshould just get rid of that file altogether.\n\n> Also, as a small example, in src/backend/access/transam/rmgr.c you'll see\n> some IWYU pragma annotations to handle a special case there.\n\nLooks pretty acceptable.\n\n> The purpose of this patch is twofold: One, it's of course a nice cleanup.\n> Two, this is a test how well IWYU might work for us. If we find either by\n> human interpretation that a change doesn't make sense, or something breaks\n> on some platform, then that would be useful feedback (perhaps to addressed\n> by more pragma annotations or more test coverage).\n\nApparently the tool has long standing, so since the results appear to be\ngood, I'm not opposed to adding it to our workflow. Not as much as\npgindent for sure, though.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\"All rings of power are equal,\nBut some rings of power are more equal than others.\"\n (George Orwell's The Lord of the Rings)\n\n\n",
"msg_date": "Mon, 12 Feb 2024 21:11:33 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: backend *.c #include cleanup (IWYU)"
},
{
"msg_contents": "Peter Eisentraut <peter@eisentraut.org> writes:\n> Approaches like that as well as the in-tree pgrminclude work by \"I \n> removed the #include and it still compiled fine\", which can be \n> unreliable. IWYU on the other hand has the compiler tracking where a \n> symbol actually came from, and so if it says that an #include is not \n> used, then it's pretty much correct by definition.\n\nWell, it might be correct by definition for the version of the code\nthat the compiler processed. But it sounds to me like it's just as\nvulnerable as pgrminclude to taking out #includes that are needed\nonly by #ifdef'd code sections that you didn't compile.\n\nOn the whole, our experience with automated #include removal is\npretty awful. I'm not sure I want to go there again.\n\n\t\t\tregards, tom lane\n\n\n",
"msg_date": "Mon, 12 Feb 2024 16:46:55 -0500",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: backend *.c #include cleanup (IWYU)"
},
{
"msg_contents": "Hi,\n\nOn 2024-02-12 16:46:55 -0500, Tom Lane wrote:\n> Peter Eisentraut <peter@eisentraut.org> writes:\n> > Approaches like that as well as the in-tree pgrminclude work by \"I\n> > removed the #include and it still compiled fine\", which can be\n> > unreliable. IWYU on the other hand has the compiler tracking where a\n> > symbol actually came from, and so if it says that an #include is not\n> > used, then it's pretty much correct by definition.\n>\n> Well, it might be correct by definition for the version of the code\n> that the compiler processed. But it sounds to me like it's just as\n> vulnerable as pgrminclude to taking out #includes that are needed\n> only by #ifdef'd code sections that you didn't compile.\n\nI think pgrminclude is far worse than IWYU - it *maximizes* reliance on\nindirect includes, the opposite of what iwyu does. I share concerns about\nremoving includes for platform/config option specific code, but I think that\nit'd not take too many annotations to address that.\n\nI think the proposed patch shows some good changes that are painful to do by\nhand, but easy with iwyu, like replacing builtins.h with fmgrprotos.h,\nreplacing includes of heapam.h/heap.h with table.h etc where appropriate.\n\nWhile I can see applying some targeted changes without more work, I don't\nreally see much point in applying a lot of the other removals without actually\ncommitting to adding the necessary IWYU annotations to our code to make iwyu\nactually usable.\n\nGreetings,\n\nAndres Freund\n\n\n",
"msg_date": "Mon, 12 Feb 2024 14:54:53 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: backend *.c #include cleanup (IWYU)"
},
{
"msg_contents": "On 12.02.24 21:07, Andres Freund wrote:\n> On 2024-02-10 08:40:43 +0100, Peter Eisentraut wrote:\n>> So as a test, I ran IWYU over the backend *.c files and removed all the\n>> #includes it suggested. (Note that IWYU also suggests to *add* a bunch of\n>> #includes, in fact that is its main purpose; I didn't do this here.) In some\n>> cases, a more specific #include replaces another less specific one. (To\n>> keep the patch from exploding in size, I ignored for now all the suggestions\n>> to replace catalog/pg_somecatalog.h with catalog/pg_somecatalog_d.h.) This\n>> ended up with the attached patch, which has\n> \n> I think this kind of suggested change is why I have been wary of IWYU (and the\n> changes that clangd suggest): By moving indirect includes to .c files you end\n> up with implementation details more widely, which can increase the pain of\n> refactoring.\n\nI'm actually not clear on what the policy of catalog/pg_somecatalog.h \nversus catalog/pg_somecatalog_d.h is or should be. There doesn't appear \nto be any consistency, other than that older code obviously is less \nlikely to use the _d.h headers.\n\nIf we have a policy, then adding some annotations might also be a good \nway to describe it.\n\n> What were the parameters you used for IWYU? I'm e.g. a bit surprised about the\n> changes to main.c, adding an include for s_lock.h. For one I don't think\n> s_lock.h should ever be included directly, but more importantly it seems there\n> isn't a reason to include spin.h either, but it's not removed here?\n\nI think the changes in main.c might have been my transcription error. \nThey don't make sense.\n\n> There are other changes I don't understand. E.g. why is\n> catalog/binary_upgrade.h removed from pg_enum.c? It's actually defining\n> binary_upgrade_next_pg_enum_oid, declared in catalog/binary_upgrade.h?\n\nAh, this is a deficiency in IWYU. It keeps headers that provide \nfunction prototypes, but it doesn't keep headers that provide extern \ndeclarations of global variables. I have filed an issue about that, and \nit looks like a fix might already be on the way.[0]\n\n[0]: \nhttps://github.com/include-what-you-use/include-what-you-use/issues/1461\n\nThis issue also led me to discover -Wmissing-variable-declarations, \nabout which I will post separately.\n\nIn the meantime, here is an updated patch with rebase and the above \nissues fixed.",
"msg_date": "Mon, 19 Feb 2024 08:59:53 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: backend *.c #include cleanup (IWYU)"
},
{
"msg_contents": "On 19.02.24 08:59, Peter Eisentraut wrote:\n>> There are other changes I don't understand. E.g. why is\n>> catalog/binary_upgrade.h removed from pg_enum.c? It's actually defining\n>> binary_upgrade_next_pg_enum_oid, declared in catalog/binary_upgrade.h?\n> \n> Ah, this is a deficiency in IWYU. It keeps headers that provide \n> function prototypes, but it doesn't keep headers that provide extern \n> declarations of global variables. I have filed an issue about that, and \n> it looks like a fix might already be on the way.[0]\n> \n> [0]: \n> https://github.com/include-what-you-use/include-what-you-use/issues/1461\n> \n> This issue also led me to discover -Wmissing-variable-declarations, \n> about which I will post separately.\n> \n> In the meantime, here is an updated patch with rebase and the above \n> issues fixed.\n\nHere is another rebase. Also, for extra caution, I undid all the \nremovals of various port(ability) includes, such as \"port/atomics.h\", \njust in case they happen to have some impact in some obscure \nconfiguration (= not covered by Cirrus CI).\n\nI propose to commit this patch now, and then maybe come back with more \nIWYU-related proposals in the future once the above issues are fixed.",
"msg_date": "Mon, 26 Feb 2024 09:30:37 +0100",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": true,
"msg_subject": "Re: backend *.c #include cleanup (IWYU)"
}
] |
[
{
"msg_contents": "Hi all,\n\n \n\nDon't know if I got this to the right group.\n\n \n\nProposal Template For a New Feature\n\nOne-line Summary: Feature request Natively integration support Azure\nMicrosoft Entra ID for authentication from On-premises PostreSQL server.\n\n \n\nBusiness Use-case: Explain the problem that you are trying to solve with the\nproposal.\n\nUsing new Authentciation method (entra ID) vs Ldap method for On-Premises\nPostgreSQL server databases.\n\n \n\nUser impact with the change: \n\nTrying to stream line accounts so we only have one place for Users and\naccounts, for onboarding\n\nand offboarding and our Echo system is starting to move to Azure, but we\nstill have On-premises PostgresSQL servers.\n\n \n\nOur Security groups want us to use new Authentication methods and have\nintegration into MS Entra ID.\n\n \n\nI know that I can from the Azure PostgreSQL log in with Azure Entra ID with\npsql.exe and pgAdmin 4 and have this working for the Azure PostgreSQl\ndatabase.\n\nBut have not found a way to do this with our On-premises PostgreSQL server\ndatabases.\n\nThere may be a method for already doing this but I have not found it, and I\nam very new to PostgreSQL.\n\n \n\nThanks\n\nTrevor.\n\n\nHi all, Don’t know if I got this to the right group. Proposal Template For a New FeatureOne-line Summary: Feature request Natively integration support Azure Microsoft Entra ID for authentication from On-premises PostreSQL server. Business Use-case: Explain the problem that you are trying to solve with the proposal.Using new Authentciation method (entra ID) vs Ldap method for On-Premises PostgreSQL server databases. User impact with the change: Trying to stream line accounts so we only have one place for Users and accounts, for onboardingand offboarding and our Echo system is starting to move to Azure, but we still have On-premises PostgresSQL servers. Our Security groups want us to use new Authentication methods and have integration into MS Entra ID. I know that I can from the Azure PostgreSQL log in with Azure Entra ID with psql.exe and pgAdmin 4 and have this working for the Azure PostgreSQl database.But have not found a way to do this with our On-premises PostgreSQL server databases.There may be a method for already doing this but I have not found it, and I am very new to PostgreSQL. ThanksTrevor.",
"msg_date": "Sat, 10 Feb 2024 10:26:29 -0700",
"msg_from": "<rs.trevk@gmail.com>",
"msg_from_op": true,
"msg_subject": "Feature request support MS Entra ID Authentication from On-premises\n PostreSQL server"
},
{
"msg_contents": "On 2024-02-10 Sa 12:26, rs.trevk@gmail.com wrote:\n>\n> Hi all,\n>\n> Don’t know if I got this to the right group.\n>\n> Proposal Template For a New Feature\n>\n> One-line Summary: Feature request Natively integration support Azure \n> Microsoft Entra ID for authentication from On-premises PostreSQL server.\n>\n> Business Use-case: Explain the problem that you are trying to solve \n> with the proposal.\n>\n> Using new Authentciation method (entra ID) vs Ldap method for \n> On-Premises PostgreSQL server databases.\n>\n> User impact with the change:\n>\n> Trying to stream line accounts so we only have one place for Users and \n> accounts, for onboarding\n>\n> and offboarding and our Echo system is starting to move to Azure, but \n> we still have On-premises PostgresSQL servers.\n>\n> Our Security groups want us to use new Authentication methods and have \n> integration into MS Entra ID.\n>\n> I know that I can from the Azure PostgreSQL log in with Azure Entra ID \n> with psql.exe and pgAdmin 4 and have this working for the Azure \n> PostgreSQl database.\n>\n> But have not found a way to do this with our On-premises PostgreSQL \n> server databases.\n>\n> There may be a method for already doing this but I have not found it, \n> and I am very new to PostgreSQL.\n>\n\nWhat is the difference between this and ActiveDirectory? AD is already \nusable as an authentication mechanism. See for example \n<https://www.crunchydata.com/blog/windows-active-directory-postgresql-gssapi-kerberos-authentication>\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB:https://www.enterprisedb.com\n\n\n\n\n\n\n\n\nOn 2024-02-10 Sa 12:26,\n rs.trevk@gmail.com wrote:\n\n\n\n\n\n\nHi all,\n \nDon’t know if I got this to the right\n group.\n \nProposal Template For a New Feature\nOne-line Summary: Feature request Natively\n integration support Azure Microsoft Entra ID for\n authentication from On-premises PostreSQL server.\n \nBusiness Use-case: Explain the problem that\n you are trying to solve with the proposal.\nUsing new Authentciation method (entra ID)\n vs Ldap method for On-Premises PostgreSQL server databases.\n \nUser impact with the change: \nTrying to stream line accounts so we only\n have one place for Users and accounts, for onboarding\nand offboarding and our Echo system is\n starting to move to Azure, but we still have On-premises\n PostgresSQL servers.\n \nOur Security groups want us to use new\n Authentication methods and have integration into MS Entra ID.\n \nI know that I can from the Azure PostgreSQL\n log in with Azure Entra ID with psql.exe and pgAdmin 4 and\n have this working for the Azure PostgreSQl database.\nBut have not found a way to do this with\n our On-premises PostgreSQL server databases.\nThere may be a method for already doing\n this but I have not found it, and I am very new to PostgreSQL.\n \n\n\n\n\nWhat is the difference between this and ActiveDirectory? AD is\n already usable as an authentication mechanism. See for example\n<https://www.crunchydata.com/blog/windows-active-directory-postgresql-gssapi-kerberos-authentication>\n\n\ncheers\n\n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com",
"msg_date": "Sun, 11 Feb 2024 10:01:51 -0500",
"msg_from": "Andrew Dunstan <andrew@dunslane.net>",
"msg_from_op": false,
"msg_subject": "Re: Feature request support MS Entra ID Authentication from\n On-premises PostreSQL server"
},
{
"msg_contents": "Azure Postgres login authentication :\n\n\n\n \n\nThis is how I do it for the Azure PostgreSQL, I will have to test to see if it will log in the same way, as I need to be able to get the token from Azure and pass that in as the password for the User/group account in the on-prem database.\n\n \n\nThanks the link , \n\nIf anyone else has been able to authenticate on-prem PostgreSQL against Micorosft Entra ID and has the steps to do this that would also be good news.\n\n \n\nFrom: Andrew Dunstan <andrew@dunslane.net> \nSent: Sunday, February 11, 2024 8:02 AM\nTo: rs.trevk@gmail.com; pgsql-hackers@lists.postgresql.org\nSubject: Re: Feature request support MS Entra ID Authentication from On-premises PostreSQL server\n\n \n\n \n\nOn 2024-02-10 Sa 12:26, rs.trevk@gmail.com <mailto:rs.trevk@gmail.com> wrote:\n\nHi all,\n\n \n\nDon’t know if I got this to the right group.\n\n \n\nProposal Template For a New Feature\n\nOne-line Summary: Feature request Natively integration support Azure Microsoft Entra ID for authentication from On-premises PostreSQL server.\n\n \n\nBusiness Use-case: Explain the problem that you are trying to solve with the proposal.\n\nUsing new Authentciation method (entra ID) vs Ldap method for On-Premises PostgreSQL server databases.\n\n \n\nUser impact with the change: \n\nTrying to stream line accounts so we only have one place for Users and accounts, for onboarding\n\nand offboarding and our Echo system is starting to move to Azure, but we still have On-premises PostgresSQL servers.\n\n \n\nOur Security groups want us to use new Authentication methods and have integration into MS Entra ID.\n\n \n\nI know that I can from the Azure PostgreSQL log in with Azure Entra ID with psql.exe and pgAdmin 4 and have this working for the Azure PostgreSQl database.\n\nBut have not found a way to do this with our On-premises PostgreSQL server databases.\n\nThere may be a method for already doing this but I have not found it, and I am very new to PostgreSQL.\n\n \n\n \n\nWhat is the difference between this and ActiveDirectory? AD is already usable as an authentication mechanism. See for example <https://www.crunchydata.com/blog/windows-active-directory-postgresql-gssapi-kerberos-authentication> <https://www.crunchydata.com/blog/windows-active-directory-postgresql-gssapi-kerberos-authentication>\n\n \n\ncheers\n\n \n\nandrew\n\n--\nAndrew Dunstan\nEDB: https://www.enterprisedb.com",
"msg_date": "Sun, 11 Feb 2024 16:12:02 -0700",
"msg_from": "<rs.trevk@gmail.com>",
"msg_from_op": true,
"msg_subject": "RE: Feature request support MS Entra ID Authentication from\n On-premises PostreSQL server"
},
{
"msg_contents": "Hi Andrew, Additionally info:\nThank you very much for your email. Additionally info:\nThis is what I have been able to setup for the Azure Flexserver PostgreSQL:\n[image: image.png]\nAnd this is what I am trying to do:( just drew the bottom to diagrams) So\nthat we have one way to log into for all users and or apps.\n[image: image.png]\nFlexserver PostgreSQL has an MS Extention for PostgreSQL that has\nthe pgaadauth extension which I think takes care of the login info.\n\nOn Sun, Feb 11, 2024 at 4:12 PM <rs.trevk@gmail.com> wrote:\n\n> Azure Postgres login authentication :\n>\n>\n>\n> This is how I do it for the Azure PostgreSQL, I will have to test to see\n> if it will log in the same way, as I need to be able to get the token from\n> Azure and pass that in as the password for the User/group account in the\n> on-prem database.\n>\n>\n>\n> Thanks the link ,\n>\n> If anyone else has been able to authenticate on-prem PostgreSQL against\n> Micorosft Entra ID and has the steps to do this that would also be good\n> news.\n>\n>\n>\n> *From:* Andrew Dunstan <andrew@dunslane.net>\n> *Sent:* Sunday, February 11, 2024 8:02 AM\n> *To:* rs.trevk@gmail.com; pgsql-hackers@lists.postgresql.org\n> *Subject:* Re: Feature request support MS Entra ID Authentication from\n> On-premises PostreSQL server\n>\n>\n>\n>\n>\n> On 2024-02-10 Sa 12:26, rs.trevk@gmail.com wrote:\n>\n> Hi all,\n>\n>\n>\n> Don’t know if I got this to the right group.\n>\n>\n>\n> Proposal Template For a New Feature\n>\n> One-line Summary: Feature request Natively integration support Azure\n> Microsoft Entra ID for authentication from On-premises PostreSQL server.\n>\n>\n>\n> Business Use-case: Explain the problem that you are trying to solve with\n> the proposal.\n>\n> Using new Authentciation method (entra ID) vs Ldap method for On-Premises\n> PostgreSQL server databases.\n>\n>\n>\n> User impact with the change:\n>\n> Trying to stream line accounts so we only have one place for Users and\n> accounts, for onboarding\n>\n> and offboarding and our Echo system is starting to move to Azure, but we\n> still have On-premises PostgresSQL servers.\n>\n>\n>\n> Our Security groups want us to use new Authentication methods and have\n> integration into MS Entra ID.\n>\n>\n>\n> I know that I can from the Azure PostgreSQL log in with Azure Entra ID\n> with psql.exe and pgAdmin 4 and have this working for the Azure PostgreSQl\n> database.\n>\n> But have not found a way to do this with our On-premises PostgreSQL server\n> databases.\n>\n> There may be a method for already doing this but I have not found it, and\n> I am very new to PostgreSQL.\n>\n>\n>\n>\n>\n> What is the difference between this and ActiveDirectory? AD is already\n> usable as an authentication mechanism. See for example\n> <https://www.crunchydata.com/blog/windows-active-directory-postgresql-gssapi-kerberos-authentication>\n> <https://www.crunchydata.com/blog/windows-active-directory-postgresql-gssapi-kerberos-authentication>\n>\n>\n>\n> cheers\n>\n>\n>\n> andrew\n>\n> --\n>\n> Andrew Dunstan\n>\n> EDB: https://www.enterprisedb.com\n>\n>",
"msg_date": "Tue, 13 Feb 2024 10:56:40 -0700",
"msg_from": "Trevor Kohlman <rs.trevk@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Feature request support MS Entra ID Authentication from\n On-premises PostreSQL server"
}
] |
[
{
"msg_contents": "Hi all,\n\nI've attached a patch for the master branch to fix up the custom BIOs used\nby PostgreSQL, in light of the issues with the OpenSSL update recently.\nWhile c82207a548db47623a2bfa2447babdaa630302b9 (switching from BIO_get_data\nto BIO_get_app_data) resolved the immediate conflict, I don't think it\naddressed the root cause, which is that PostgreSQL was mixing up two BIO\nimplementations, each of which expected to be driving the BIO.\n\nIt turns out the parts that came from the OpenSSL socket BIO were a no-op,\nand in fact PostgreSQL is relying on it being a no-op. Instead, it's\ncleaner to just define a custom BIO the normal way, which then leaves the\nmore standard BIO_get_data mechanism usable. This also avoids the risk that\na future OpenSSL will add a now BIO_ctrl to the socket type, with libssl\ncalling into it, and then break some assumptions made by PostgreSQL.\n\nI've attached a patch which does that. The existing SSL tests pass with\nit, tested on Debian stable. (Though it took me a few iterations to figure\nout how to run the SSL tests, so it's possible I've missed something.)\n\nThe patch is not expected to change behavior, so nothing new to document,\nnor any expected performance impact.\n\nDavid",
"msg_date": "Sun, 11 Feb 2024 13:19:00 -0500",
"msg_from": "David Benjamin <davidben@google.com>",
"msg_from_op": true,
"msg_subject": "[PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "> On 11 Feb 2024, at 19:19, David Benjamin <davidben@google.com> wrote:\n> \n> Hi all,\n> \n> I've attached a patch for the master branch to fix up the custom BIOs used by PostgreSQL, in light of the issues with the OpenSSL update recently. While c82207a548db47623a2bfa2447babdaa630302b9 (switching from BIO_get_data to BIO_get_app_data) resolved the immediate conflict, I don't think it addressed the root cause, which is that PostgreSQL was mixing up two BIO implementations, each of which expected to be driving the BIO.\n\nThanks for your patch, I'm still digesting it so will provide more of a review\nlater.\n\n> It turns out the parts that came from the OpenSSL socket BIO were a no-op, and in fact PostgreSQL is relying on it being a no-op. Instead, it's cleaner to just define a custom BIO the normal way, which then leaves the more standard BIO_get_data mechanism usable. This also avoids the risk that a future OpenSSL will add a now BIO_ctrl to the socket type, with libssl calling into it, and then break some assumptions made by PostgreSQL.\n\n+\t\tcase BIO_CTRL_FLUSH:\n+\t\t\t/* libssl expects all BIOs to support BIO_flush. */\n+\t\t\tres = 1;\n+\t\t\tbreak;\n\nWill this always be true? Returning 1 implies that we have flushed all data on\nthe socket, but what if we just before called BIO_set_retry..XX()?\n\n> I've attached a patch which does that. The existing SSL tests pass with it, tested on Debian stable. (Though it took me a few iterations to figure out how to run the SSL tests, so it's possible I've missed something.)\n\nWe've done a fair bit of work on making them easier to run, so I'm curious if\nyou saw any room for improvements there as someone coming to them for the first\ntime?\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Mon, 12 Feb 2024 15:38:39 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "On Mon, Feb 12, 2024 at 9:38 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n\n> > On 11 Feb 2024, at 19:19, David Benjamin <davidben@google.com> wrote:\n> > It turns out the parts that came from the OpenSSL socket BIO were a\n> no-op, and in fact PostgreSQL is relying on it being a no-op. Instead, it's\n> cleaner to just define a custom BIO the normal way, which then leaves the\n> more standard BIO_get_data mechanism usable. This also avoids the risk that\n> a future OpenSSL will add a now BIO_ctrl to the socket type, with libssl\n> calling into it, and then break some assumptions made by PostgreSQL.\n>\n> + case BIO_CTRL_FLUSH:\n> + /* libssl expects all BIOs to support BIO_flush. */\n> + res = 1;\n> + break;\n>\n> Will this always be true? Returning 1 implies that we have flushed all\n> data on\n> the socket, but what if we just before called BIO_set_retry..XX()?\n>\n\nThe real one is also just a no-op. :-)\nhttps://github.com/openssl/openssl/blob/master/crypto/bio/bss_sock.c#L215\n\nThis is used in places like buffer BIO or the FILE* BIO, where BIO_write\nmight accept data, but stage it into a buffer, to be flushed later. libssl\nends up calling BIO_flush at the end of every flight, which in turn means\nthat BIOs used with libssl need to support it, even if to return true\nbecause there's nothing to flush. (Arguably TCP sockets could have used a\nflush concept, to help control Nagle's algorithm, but for better or worse,\nthat's a socket-wide TCP_NODELAY option, rather than an explicit flush\ncall.)\n\nBIO_set_retry.. behaves like POSIX I/O, where a failed EWOULDBLOCK write is\nas if you never wrote to the socket at all and doesn't impact socket state.\nThat is, the data hasn't been accepted yet. It's not expected for BIO_flush\nto care about the rejected write data. (Also I don't believe libssl will\never trigger this case.) It's confusing because unlike an EWOULDBLOCK\nerrno, BIO_set_retry.. *is* itself BIO state, but that's just because the\nBIO calling convention is goofy and didn't just return the error out of the\nreturn value. So OpenSSL just stashes the bit on the BIO itself, for you to\nquery out immediately afterwards.\n\n\n> > I've attached a patch which does that. The existing SSL tests pass with\n> it, tested on Debian stable. (Though it took me a few iterations to figure\n> out how to run the SSL tests, so it's possible I've missed something.)\n>\n> We've done a fair bit of work on making them easier to run, so I'm curious\n> if\n> you saw any room for improvements there as someone coming to them for the\n> first\n> time?\n>\n\n A lot of my time was just trying to figure out how to run the tests in the\nfirst place, so perhaps documentation? But I may just have been looking in\nthe wrong spot and honestly didn't really know what I was doing. I can try\nto summarize what I did (from memory), and perhaps that can point to\npossible improvements?\n\n- I looked in the repository for instructions on running the tests and\ncouldn't find any. At this point, I hadn't found src/test/README.\n- I found\nhttps://wiki.postgresql.org/wiki/Developer_FAQ#How_do_I_test_my_changes.3F,\nlinked from https://www.postgresql.org/developer/\n- I ran the configure build with --enable-cassert, ran make check, tests\npassed.\n- I wrote my patch and then spent a while intentionally adding bugs to see\nif the tests would catch it (I wasn't sure whether there was ssl test\ncoverage), finally concluding that I wasn't running any ssl tests\n- I looked some more and found src/test/ssl/README\n- I reconfigured with --enable-tap-tests and ran make check\nPG_TEST_EXTRA=ssl per those instructions, but the SSL tests still weren't\nrunning\n- I grepped for PG_TEST_EXTRA and found references in the CI config, but\nusing the meson build\n- I installed meson, mimicked a few commands from the CI. That seemed to\nwork.\n- I tried running only the ssl tests, looking up how you specify individual\ntests in meson, to make my compile/test cycles a bit faster, but they\nfailed.\n- I noticed that the first couple \"tests\" were named like setup tasks, and\nguessed that the ssl tests depended on this setup to run. But by then I\njust gave up and waited out the whole test suite per run. :-)\n\nOnce I got it running, it was quite smooth. I just wasn't sure how to do it.\n\nDavid\n\nOn Mon, Feb 12, 2024 at 9:38 AM Daniel Gustafsson <daniel@yesql.se> wrote:> On 11 Feb 2024, at 19:19, David Benjamin <davidben@google.com> wrote:> It turns out the parts that came from the OpenSSL socket BIO were a no-op, and in fact PostgreSQL is relying on it being a no-op. Instead, it's cleaner to just define a custom BIO the normal way, which then leaves the more standard BIO_get_data mechanism usable. This also avoids the risk that a future OpenSSL will add a now BIO_ctrl to the socket type, with libssl calling into it, and then break some assumptions made by PostgreSQL.\n\n+ case BIO_CTRL_FLUSH:\n+ /* libssl expects all BIOs to support BIO_flush. */\n+ res = 1;\n+ break;\n\nWill this always be true? Returning 1 implies that we have flushed all data on\nthe socket, but what if we just before called BIO_set_retry..XX()?The real one is also just a no-op. :-)https://github.com/openssl/openssl/blob/master/crypto/bio/bss_sock.c#L215This is used in places like buffer BIO or the FILE* BIO, where BIO_write might accept data, but stage it into a buffer, to be flushed later. libssl ends up calling BIO_flush at the end of every flight, which in turn means that BIOs used with libssl need to support it, even if to return true because there's nothing to flush. (Arguably TCP sockets could have used a flush concept, to help control Nagle's algorithm, but for better or worse, that's a socket-wide TCP_NODELAY option, rather than an explicit flush call.)BIO_set_retry.. behaves like POSIX I/O, where a failed EWOULDBLOCK write is as if you never wrote to the socket at all and doesn't impact socket state. That is, the data hasn't been accepted yet. It's not expected for BIO_flush to care about the rejected write data. (Also I don't believe libssl will ever trigger this case.) It's confusing because unlike an EWOULDBLOCK errno, BIO_set_retry.. is itself BIO state, but that's just because the BIO calling convention is goofy and didn't just return the error out of the return value. So OpenSSL just stashes the bit on the BIO itself, for you to query out immediately afterwards. \n> I've attached a patch which does that. The existing SSL tests pass with it, tested on Debian stable. (Though it took me a few iterations to figure out how to run the SSL tests, so it's possible I've missed something.)\n\nWe've done a fair bit of work on making them easier to run, so I'm curious if\nyou saw any room for improvements there as someone coming to them for the first\ntime? A lot of my time was just trying to figure out how to run the tests in the first place, so perhaps documentation? But I may just have been looking in the wrong spot and honestly didn't really know what I was doing. I can try to summarize what I did (from memory), and perhaps that can point to possible improvements?- I looked in the repository for instructions on running the tests and couldn't find any. At this point, I hadn't found src/test/README.- I found https://wiki.postgresql.org/wiki/Developer_FAQ#How_do_I_test_my_changes.3F, linked from https://www.postgresql.org/developer/- I ran the configure build with --enable-cassert, ran make check, tests passed.- I wrote my patch and then spent a while intentionally adding bugs to see if the tests would catch it (I wasn't sure whether there was ssl test coverage), finally concluding that I wasn't running any ssl tests- I looked some more and found src/test/ssl/README- I reconfigured with --enable-tap-tests and ran make check PG_TEST_EXTRA=ssl per those instructions, but the SSL tests still weren't running- I grepped for PG_TEST_EXTRA and found references in the CI config, but using the meson build- I installed meson, mimicked a few commands from the CI. That seemed to work.- I tried running only the ssl tests, looking up how you specify individual tests in meson, to make my compile/test cycles a bit faster, but they failed.- I noticed that the first couple \"tests\" were named like setup tasks, and guessed that the ssl tests depended on this setup to run. But by then I just gave up and waited out the whole test suite per run. :-)Once I got it running, it was quite smooth. I just wasn't sure how to do it.David",
"msg_date": "Mon, 12 Feb 2024 11:31:21 -0500",
"msg_from": "David Benjamin <davidben@google.com>",
"msg_from_op": true,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "By the way, I'm unable to add the patch to the next commitfest due to the\ncool off period for new accounts. How long is that period? I don't suppose\nthere's a way to avoid it?\n\nOn Mon, Feb 12, 2024 at 11:31 AM David Benjamin <davidben@google.com> wrote:\n\n> On Mon, Feb 12, 2024 at 9:38 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n>\n>> > On 11 Feb 2024, at 19:19, David Benjamin <davidben@google.com> wrote:\n>> > It turns out the parts that came from the OpenSSL socket BIO were a\n>> no-op, and in fact PostgreSQL is relying on it being a no-op. Instead, it's\n>> cleaner to just define a custom BIO the normal way, which then leaves the\n>> more standard BIO_get_data mechanism usable. This also avoids the risk that\n>> a future OpenSSL will add a now BIO_ctrl to the socket type, with libssl\n>> calling into it, and then break some assumptions made by PostgreSQL.\n>>\n>> + case BIO_CTRL_FLUSH:\n>> + /* libssl expects all BIOs to support BIO_flush.\n>> */\n>> + res = 1;\n>> + break;\n>>\n>> Will this always be true? Returning 1 implies that we have flushed all\n>> data on\n>> the socket, but what if we just before called BIO_set_retry..XX()?\n>>\n>\n> The real one is also just a no-op. :-)\n> https://github.com/openssl/openssl/blob/master/crypto/bio/bss_sock.c#L215\n>\n> This is used in places like buffer BIO or the FILE* BIO, where BIO_write\n> might accept data, but stage it into a buffer, to be flushed later. libssl\n> ends up calling BIO_flush at the end of every flight, which in turn means\n> that BIOs used with libssl need to support it, even if to return true\n> because there's nothing to flush. (Arguably TCP sockets could have used a\n> flush concept, to help control Nagle's algorithm, but for better or worse,\n> that's a socket-wide TCP_NODELAY option, rather than an explicit flush\n> call.)\n>\n> BIO_set_retry.. behaves like POSIX I/O, where a failed EWOULDBLOCK write\n> is as if you never wrote to the socket at all and doesn't impact\n> socket state. That is, the data hasn't been accepted yet. It's not expected\n> for BIO_flush to care about the rejected write data. (Also I don't believe\n> libssl will ever trigger this case.) It's confusing because unlike an\n> EWOULDBLOCK errno, BIO_set_retry.. *is* itself BIO state, but that's just\n> because the BIO calling convention is goofy and didn't just return the\n> error out of the return value. So OpenSSL just stashes the bit on the BIO\n> itself, for you to query out immediately afterwards.\n>\n>\n>> > I've attached a patch which does that. The existing SSL tests pass with\n>> it, tested on Debian stable. (Though it took me a few iterations to figure\n>> out how to run the SSL tests, so it's possible I've missed something.)\n>>\n>> We've done a fair bit of work on making them easier to run, so I'm\n>> curious if\n>> you saw any room for improvements there as someone coming to them for the\n>> first\n>> time?\n>>\n>\n> A lot of my time was just trying to figure out how to run the tests in\n> the first place, so perhaps documentation? But I may just have been looking\n> in the wrong spot and honestly didn't really know what I was doing. I can\n> try to summarize what I did (from memory), and perhaps that can point to\n> possible improvements?\n>\n> - I looked in the repository for instructions on running the tests and\n> couldn't find any. At this point, I hadn't found src/test/README.\n> - I found\n> https://wiki.postgresql.org/wiki/Developer_FAQ#How_do_I_test_my_changes.3F,\n> linked from https://www.postgresql.org/developer/\n> - I ran the configure build with --enable-cassert, ran make check, tests\n> passed.\n> - I wrote my patch and then spent a while intentionally adding bugs to see\n> if the tests would catch it (I wasn't sure whether there was ssl test\n> coverage), finally concluding that I wasn't running any ssl tests\n> - I looked some more and found src/test/ssl/README\n> - I reconfigured with --enable-tap-tests and ran make check\n> PG_TEST_EXTRA=ssl per those instructions, but the SSL tests still weren't\n> running\n> - I grepped for PG_TEST_EXTRA and found references in the CI config, but\n> using the meson build\n> - I installed meson, mimicked a few commands from the CI. That seemed to\n> work.\n> - I tried running only the ssl tests, looking up how you specify\n> individual tests in meson, to make my compile/test cycles a bit faster, but\n> they failed.\n> - I noticed that the first couple \"tests\" were named like setup tasks, and\n> guessed that the ssl tests depended on this setup to run. But by then I\n> just gave up and waited out the whole test suite per run. :-)\n>\n> Once I got it running, it was quite smooth. I just wasn't sure how to do\n> it.\n>\n> David\n>\n\nBy the way, I'm unable to add the patch to the next commitfest due to the cool off period for new accounts. How long is that period? I don't suppose there's a way to avoid it?On Mon, Feb 12, 2024 at 11:31 AM David Benjamin <davidben@google.com> wrote:On Mon, Feb 12, 2024 at 9:38 AM Daniel Gustafsson <daniel@yesql.se> wrote:> On 11 Feb 2024, at 19:19, David Benjamin <davidben@google.com> wrote:> It turns out the parts that came from the OpenSSL socket BIO were a no-op, and in fact PostgreSQL is relying on it being a no-op. Instead, it's cleaner to just define a custom BIO the normal way, which then leaves the more standard BIO_get_data mechanism usable. This also avoids the risk that a future OpenSSL will add a now BIO_ctrl to the socket type, with libssl calling into it, and then break some assumptions made by PostgreSQL.\n\n+ case BIO_CTRL_FLUSH:\n+ /* libssl expects all BIOs to support BIO_flush. */\n+ res = 1;\n+ break;\n\nWill this always be true? Returning 1 implies that we have flushed all data on\nthe socket, but what if we just before called BIO_set_retry..XX()?The real one is also just a no-op. :-)https://github.com/openssl/openssl/blob/master/crypto/bio/bss_sock.c#L215This is used in places like buffer BIO or the FILE* BIO, where BIO_write might accept data, but stage it into a buffer, to be flushed later. libssl ends up calling BIO_flush at the end of every flight, which in turn means that BIOs used with libssl need to support it, even if to return true because there's nothing to flush. (Arguably TCP sockets could have used a flush concept, to help control Nagle's algorithm, but for better or worse, that's a socket-wide TCP_NODELAY option, rather than an explicit flush call.)BIO_set_retry.. behaves like POSIX I/O, where a failed EWOULDBLOCK write is as if you never wrote to the socket at all and doesn't impact socket state. That is, the data hasn't been accepted yet. It's not expected for BIO_flush to care about the rejected write data. (Also I don't believe libssl will ever trigger this case.) It's confusing because unlike an EWOULDBLOCK errno, BIO_set_retry.. is itself BIO state, but that's just because the BIO calling convention is goofy and didn't just return the error out of the return value. So OpenSSL just stashes the bit on the BIO itself, for you to query out immediately afterwards. \n> I've attached a patch which does that. The existing SSL tests pass with it, tested on Debian stable. (Though it took me a few iterations to figure out how to run the SSL tests, so it's possible I've missed something.)\n\nWe've done a fair bit of work on making them easier to run, so I'm curious if\nyou saw any room for improvements there as someone coming to them for the first\ntime? A lot of my time was just trying to figure out how to run the tests in the first place, so perhaps documentation? But I may just have been looking in the wrong spot and honestly didn't really know what I was doing. I can try to summarize what I did (from memory), and perhaps that can point to possible improvements?- I looked in the repository for instructions on running the tests and couldn't find any. At this point, I hadn't found src/test/README.- I found https://wiki.postgresql.org/wiki/Developer_FAQ#How_do_I_test_my_changes.3F, linked from https://www.postgresql.org/developer/- I ran the configure build with --enable-cassert, ran make check, tests passed.- I wrote my patch and then spent a while intentionally adding bugs to see if the tests would catch it (I wasn't sure whether there was ssl test coverage), finally concluding that I wasn't running any ssl tests- I looked some more and found src/test/ssl/README- I reconfigured with --enable-tap-tests and ran make check PG_TEST_EXTRA=ssl per those instructions, but the SSL tests still weren't running- I grepped for PG_TEST_EXTRA and found references in the CI config, but using the meson build- I installed meson, mimicked a few commands from the CI. That seemed to work.- I tried running only the ssl tests, looking up how you specify individual tests in meson, to make my compile/test cycles a bit faster, but they failed.- I noticed that the first couple \"tests\" were named like setup tasks, and guessed that the ssl tests depended on this setup to run. But by then I just gave up and waited out the whole test suite per run. :-)Once I got it running, it was quite smooth. I just wasn't sure how to do it.David",
"msg_date": "Wed, 14 Feb 2024 22:58:17 -0500",
"msg_from": "David Benjamin <davidben@google.com>",
"msg_from_op": true,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "> On 15 Feb 2024, at 04:58, David Benjamin <davidben@google.com> wrote:\n> \n> By the way, I'm unable to add the patch to the next commitfest due to the cool off period for new accounts. How long is that period? I don't suppose there's a way to avoid it?\n\nThere is a way to expedite the cooling-off period (it's a SPAM prevention\nmeasure), but I don't have access to it. In the meantime I've added the patch\nfor you, and once the cooling off is over we can add your name as author.\n\n\thttps://commitfest.postgresql.org/47/4835/\n\nI'm currently reviewing it and will get back to you soon on that.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Thu, 15 Feb 2024 13:58:45 +0100",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "Hi,\n\nOn 2024-02-11 13:19:00 -0500, David Benjamin wrote:\n> I've attached a patch for the master branch to fix up the custom BIOs used\n> by PostgreSQL, in light of the issues with the OpenSSL update recently.\n> While c82207a548db47623a2bfa2447babdaa630302b9 (switching from BIO_get_data\n> to BIO_get_app_data) resolved the immediate conflict, I don't think it\n> addressed the root cause, which is that PostgreSQL was mixing up two BIO\n> implementations, each of which expected to be driving the BIO.\n\nYea, that's certainly not nice - and I think we've been somewhat lucky it\nhasn't caused more issues. There's some nasty possibilities, e.g. sock_ctrl()\npartially enabling ktls without our initialization having called\nktls_enable(). Right now that just means ktls is unusable, but it's not hard\nto imagine accidentally ending up sending unencrypted data.\n\n\n\nI've in the past looked into not using a custom BIO [1], but I have my doubts\nabout that being a good idea. I think medium term we want to be able to do\nnetwork IO asynchronously, which seems quite hard to do when using openssl's\nsocket BIO.\n\n\n\n> Once we've done that, we're free to use BIO_set_data. While BIO_set_app_data\n> works fine, I've reverted back to BIO_set_data because it's more commonly used.\n> app_data depends on OpenSSL's \"ex_data\" mechanism, which is a tad heavier under\n> the hood.\n\nAt first I was a bit wary of that, because it requires us to bring back the\nfallback implementation. But you're right, it's noticeably heavier than\nBIO_get_data(), and we do call BIO_get_app_data() fairly frequently.\n\n\n\n> That leaves ctrl. ctrl is a bunch of operations (it's ioctl). The only\n> operation that matters is BIO_CTRL_FLUSH, which is implemented as a no-op. All\n> other operations are unused. It's once again good that they're unused because\n> otherwise OpenSSL might mess with postgres's socket, break the assumptions\n> around interrupt handling, etc.\n\nHow did you determine that only FLUSH is required? I didn't even really find\ndocumentation about what the intended semantics actually are.\n\nE.g. should we implement BIO_CTRL_EOF? Sure, it wasn't really supported so\nfar, because we never set it, but is that right? What about\nBIO_CTRL_GET_CLOSE/BIO_CTRL_SET_CLOSE?\n\n\nAnother issue is that 0 doesn't actually seem like the universal error return\n- e.g. BIO_C_GET_FD seems to return -1, because 0 is a valid fd.\n\n\nAs of your patch the bio doesn't actually have an FD anymore, should it still\nset BIO_TYPE_DESCRIPTOR?\n\n\n\n> +static long\n> +my_sock_ctrl(BIO *h, int cmd, long num, void *ptr)\n> +{\n> +\tlong\t\tres = 0;\n> +\n> +\tswitch (cmd)\n> +\t{\n> +\t\tcase BIO_CTRL_FLUSH:\n> +\t\t\t/* libssl expects all BIOs to support BIO_flush. */\n> +\t\t\tres = 1;\n> +\t\t\tbreak;\n> +\t}\n> +\n> +\treturn res;\n> +}\n\nI'd move the res = 0 into a default: block. That way the compiler can warn if\nsome case doesn't set it in all branches.\n\n\n> static BIO_METHOD *\n> my_BIO_s_socket(void)\n> {\n\nWonder if we should rename this. It's pretty odd that we still call it's not\nreally related to s_socket anymore, and doesn't even really implement the same\ninterface (e.g. get_fd doesn't work anymore). Similarly, my_SSL_set_fd()\ndoesn't actually call set_fd() anymore, which sure seems odd.\n\n\nGreetings,\n\nAndres Freund\n\n[1] https://www.postgresql.org/message-id/20210715021747.h2hih7mw56ivyntt%40alap3.anarazel.de\n\n\n",
"msg_date": "Thu, 15 Feb 2024 13:17:41 -0800",
"msg_from": "Andres Freund <andres@anarazel.de>",
"msg_from_op": false,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "Thanks for the very thorough comments! I've attached a new version of the\npatch.\n\nOn Thu, Feb 15, 2024 at 4:17 PM Andres Freund <andres@anarazel.de> wrote:\n\n> Hi,\n>\n> On 2024-02-11 13:19:00 -0500, David Benjamin wrote:\n> > I've attached a patch for the master branch to fix up the custom BIOs\n> used\n> > by PostgreSQL, in light of the issues with the OpenSSL update recently.\n> > While c82207a548db47623a2bfa2447babdaa630302b9 (switching from\n> BIO_get_data\n> > to BIO_get_app_data) resolved the immediate conflict, I don't think it\n> > addressed the root cause, which is that PostgreSQL was mixing up two BIO\n> > implementations, each of which expected to be driving the BIO.\n>\n> Yea, that's certainly not nice - and I think we've been somewhat lucky it\n> hasn't caused more issues. There's some nasty possibilities, e.g.\n> sock_ctrl()\n> partially enabling ktls without our initialization having called\n> ktls_enable(). Right now that just means ktls is unusable, but it's not\n> hard\n> to imagine accidentally ending up sending unencrypted data.\n>\n\nYeah. Even if, say, the ktls bits work, given you all care enough about I/O\nto have wanted to wrap the BIO, I assume you'd want to pick up those\nfeatures on your own terms, e.g. by implementing the BIO_CTRLs yourself.\n\n\n> I've in the past looked into not using a custom BIO [1], but I have my\n> doubts\n> about that being a good idea. I think medium term we want to be able to do\n> network IO asynchronously, which seems quite hard to do when using\n> openssl's\n> socket BIO.\n\n\n\n> Once we've done that, we're free to use BIO_set_data. While\n> BIO_set_app_data\n> > works fine, I've reverted back to BIO_set_data because it's more\n> commonly used.\n> > app_data depends on OpenSSL's \"ex_data\" mechanism, which is a tad\n> heavier under\n> > the hood.\n>\n> At first I was a bit wary of that, because it requires us to bring back the\n> fallback implementation. But you're right, it's noticeably heavier than\n> BIO_get_data(), and we do call BIO_get_app_data() fairly frequently.\n>\n\nTBH, I doubt it makes any real difference perf-wise. But I think\nBIO_get_data is a bit more common in this context.\n\n\n> > That leaves ctrl. ctrl is a bunch of operations (it's ioctl). The only\n> > operation that matters is BIO_CTRL_FLUSH, which is implemented as a\n> no-op. All\n> > other operations are unused. It's once again good that they're unused\n> because\n> > otherwise OpenSSL might mess with postgres's socket, break the\n> assumptions\n> > around interrupt handling, etc.\n>\n> How did you determine that only FLUSH is required? I didn't even really\n> find\n> documentation about what the intended semantics actually are.\n>\n\nThe unhelpful answer is that my day job is working on BoringSSL, so I've\nspent a lot of time with this mess. :-) But, yeah, it's not well-documented\nat all. OpenSSL ends up calling BIO_flush at the end of each batch of\nwrites in libssl. TBH, I suspect that was less intentional and more an\nemergent property of them internally layering a buffer BIO at one point in\nthe process, but it's long been part of the (undocumented) API contract.\nConversely, I don't think OpenSSL can possibly make libssl *require* a new\nBIO_CTRL because they'd break every custom BIO anyone has ever used with\nthe library.\n\n\n> E.g. should we implement BIO_CTRL_EOF? Sure, it wasn't really supported so\n> far, because we never set it, but is that right?\n\n\nAh hmm, BIO_CTRL_EOF is... a bit of a mess. OpenSSL kind of messed things\nup. So, up until recently, I would have said that BIO_CTRL_EOF was not part\nof the interface here. OpenSSL 1.0.x did not implement it for sockets, and\nthe BIO_read API *already* had a way to signal EOF: did you return zero or\n-1?\n\nThen OpenSSL 1.1.x introduced size_t-based BIO_read_ex APIs. However, in\nthe process, they *forgot that EOF and error are different things* and made\nit impossible to detect EOFs if you use BIO_read_ex! They never noticed\nthis, because they didn't actually convert their own code to their new API.\nSee this discussion, which alas ended with OpenSSL deciding to ignore the\nproblem and not even document their current interface.\nhttps://github.com/openssl/openssl/issues/8208\n\nThough they never responded, they seem to have tacitly settled using the\nout-of-band BIO_eof function (which is BIO_CTRL_EOF) as the way to signal\nEOF for BIO_read_ex. This is kind of fiddly, but is at least a well-defined\noption. But the problem is no one's BIO_METHODs, including their own, are\nread_ex-based. They all implement the old read callback. But someone might\ncall BIO_read_ex on a read-based BIO_METHOD. IMO, BIO_read_ex should be\nresponsible for translating between the two EOF conventions. For example,\nit could automatically set a flag when the read callback returns 0 and then\nmake BIO_ctrl check the flag and automatically implement BIO_CTRL_EOF for\nBIOs that don't do it themselves. Alas, OpenSSL did not do this and instead\nthey just made their built-in BIOs implement BIO_CTRL_EOF, even though this\nnew expectation is a compatibility break. That leaves BIO_read, the one\neveryone uses, in a pretty ambiguous state that they seem uninterested in\naddressing.\nhttps://github.com/openssl/openssl/pull/10882\nhttps://github.com/openssl/openssl/pull/10907\n\nHonestly, I suspect nothing in postgres actually cares about this, given\nyou all didn't notice things breaking around here in the early days of\n1.1.x. Still, that is a good point. I've updated the patch to implement\nBIO_CTRL_EOF for completeness' sake.\n\n(For BoringSSL, we did not go down this route because, unlike OpenSSL\napparently, we do not think breaking backwards compatibility in the EOF\nconvention is OK. I do want to add the size_t APIs eventually, but I'm\nthinking we'll do the automatic BIO_CTRL_EOF thing described above, to\navoid breaking compatibility with existing BIO_METHODs.)\n\nBeyond BIO_CTRL_EOF, I assume what you're really asking here is \"how do we\nknow OpenSSL won't change the interface again?\". And, honestly, we don't.\nThey promise API and ABI stability, which in theory means they shouldn't.\nBut their track record with custom BIOs is not great. That said, if they do\nbreak it, I think it will unambiguously be an API break on their part and\nhopefully it'll be possible to get them to fix the issue. The EOF issue\nsnuck in because it mostly only impacted people who tried to migrate to\ntheir new APIs. It broke existing APIs too, but the one project that\nnoticed (CPython) misdiagnosed the issue and worked around it.\n(Incorrectly, but no one noticed. See\nhttps://github.com/python/cpython/pull/95495.) So, I raised the issue,\nthey'd long since shipped it and evidently felt no burning need to fix\ntheir regression or unclear APIs. :-(\n\nBut the alternative, picking up the real socket BIO's ctrl function, is\neven more unsound, so I think this is the better place to be.\n\n\n> What about\n> BIO_CTRL_GET_CLOSE/BIO_CTRL_SET_CLOSE?\n>\n\nThe close flag is pretty silly. All BIOs do slightly different things with\nit, which means that libssl cannot possibly call it generically. So if your\nBIO doesn't have any need for it, you don't need to bother. It's usually\nused to indicate whether the BIO owns the underlying fd/socket/BUF_MEM/etc,\n\n\n> Another issue is that 0 doesn't actually seem like the universal error\n> return\n> - e.g. BIO_C_GET_FD seems to return -1, because 0 is a valid fd.\n>\n\nYeah, that is... also a mess. All of OpenSSL's ctrl functions return zero\nfor unrecognized commands. It seems they just don't have a convention for\ndistinguishing unimplemented commands from zero returns. As you note, this\nis a problem for BIO_C_GET_FD. OpenSSL's other non-fd BIOs have the same\nproblem though:\nhttps://github.com/openssl/openssl/blob/master/crypto/bio/bss_file.c#L340\n\nRealistically, type-specific ioctls like that don't matter much because\nyou're really only going to call them if you already know you have an\napplicable BIO. Hopefully, between that, and removing BIO_TYPE_DESCRIPTOR\n(below), it's mostly okay? Also happy to add a `ret = -1` implementation\nof BIO_C_GET_FD if you'd prefer. But, in the general case, I suspect we\njust have to live with the zero thing, and hopefully OpenSSL will stop\nintroducing ctrls where zero is an unsafe return value.\n\nPerhaps BIO_ctrl in OpenSSL should have some logic like...\n```\nif (!(type & BIO_TYPE_DESCRIPTOR) && cmd == BIO_C_GET_FD) {\n return -1;\n}\n```\nAlthough I suspect there are people who implement BIO_C_GET_FD without\nsetting BIO_TYPE_DESCRIPTOR because none of this was ever documented.\n\n\n> As of your patch the bio doesn't actually have an FD anymore, should it\n> still\n> set BIO_TYPE_DESCRIPTOR?\n>\n\nAh good call. Done. I don't think much code really cares, but it does mean\nthat, if you all call SSL_get_fd (why would you?), it won't get confused.\n:-)\n\n> +static long\n> > +my_sock_ctrl(BIO *h, int cmd, long num, void *ptr)\n> > +{\n> > + long res = 0;\n> > +\n> > + switch (cmd)\n> > + {\n> > + case BIO_CTRL_FLUSH:\n> > + /* libssl expects all BIOs to support BIO_flush. */\n> > + res = 1;\n> > + break;\n> > + }\n> > +\n> > + return res;\n> > +}\n>\n> I'd move the res = 0 into a default: block. That way the compiler can warn\n> if\n> some case doesn't set it in all branches.\n>\n\nDone.\n\n\n> > static BIO_METHOD *\n> > my_BIO_s_socket(void)\n> > {\n>\n> Wonder if we should rename this. It's pretty odd that we still call it's\n> not\n> really related to s_socket anymore, and doesn't even really implement the\n> same\n> interface (e.g. get_fd doesn't work anymore). Similarly, my_SSL_set_fd()\n> doesn't actually call set_fd() anymore, which sure seems odd.\n>\n\nDone. I wasn't sure what to name them, or even what the naming convention\nwas, but I opted to name them after the Port and PGconn objects they wrap.\nHappy to switch to another name if you have a better idea though.\n\nDavid",
"msg_date": "Wed, 21 Feb 2024 17:04:08 -0500",
"msg_from": "David Benjamin <davidben@google.com>",
"msg_from_op": true,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "Circling back here, anything else needed from my end on this patch?\n\nOn Wed, Feb 21, 2024, 17:04 David Benjamin <davidben@google.com> wrote:\n\n> Thanks for the very thorough comments! I've attached a new version of the\n> patch.\n>\n> On Thu, Feb 15, 2024 at 4:17 PM Andres Freund <andres@anarazel.de> wrote:\n>\n>> Hi,\n>>\n>> On 2024-02-11 13:19:00 -0500, David Benjamin wrote:\n>> > I've attached a patch for the master branch to fix up the custom BIOs\n>> used\n>> > by PostgreSQL, in light of the issues with the OpenSSL update recently.\n>> > While c82207a548db47623a2bfa2447babdaa630302b9 (switching from\n>> BIO_get_data\n>> > to BIO_get_app_data) resolved the immediate conflict, I don't think it\n>> > addressed the root cause, which is that PostgreSQL was mixing up two BIO\n>> > implementations, each of which expected to be driving the BIO.\n>>\n>> Yea, that's certainly not nice - and I think we've been somewhat lucky it\n>> hasn't caused more issues. There's some nasty possibilities, e.g.\n>> sock_ctrl()\n>> partially enabling ktls without our initialization having called\n>> ktls_enable(). Right now that just means ktls is unusable, but it's not\n>> hard\n>> to imagine accidentally ending up sending unencrypted data.\n>>\n>\n> Yeah. Even if, say, the ktls bits work, given you all care enough about\n> I/O to have wanted to wrap the BIO, I assume you'd want to pick up those\n> features on your own terms, e.g. by implementing the BIO_CTRLs yourself.\n>\n>\n>> I've in the past looked into not using a custom BIO [1], but I have my\n>> doubts\n>> about that being a good idea. I think medium term we want to be able to do\n>> network IO asynchronously, which seems quite hard to do when using\n>> openssl's\n>> socket BIO.\n>\n>\n>\n> > Once we've done that, we're free to use BIO_set_data. While\n>> BIO_set_app_data\n>> > works fine, I've reverted back to BIO_set_data because it's more\n>> commonly used.\n>> > app_data depends on OpenSSL's \"ex_data\" mechanism, which is a tad\n>> heavier under\n>> > the hood.\n>>\n>> At first I was a bit wary of that, because it requires us to bring back\n>> the\n>> fallback implementation. But you're right, it's noticeably heavier than\n>> BIO_get_data(), and we do call BIO_get_app_data() fairly frequently.\n>>\n>\n> TBH, I doubt it makes any real difference perf-wise. But I think\n> BIO_get_data is a bit more common in this context.\n>\n>\n>> > That leaves ctrl. ctrl is a bunch of operations (it's ioctl). The only\n>> > operation that matters is BIO_CTRL_FLUSH, which is implemented as a\n>> no-op. All\n>> > other operations are unused. It's once again good that they're unused\n>> because\n>> > otherwise OpenSSL might mess with postgres's socket, break the\n>> assumptions\n>> > around interrupt handling, etc.\n>>\n>> How did you determine that only FLUSH is required? I didn't even really\n>> find\n>> documentation about what the intended semantics actually are.\n>>\n>\n> The unhelpful answer is that my day job is working on BoringSSL, so I've\n> spent a lot of time with this mess. :-) But, yeah, it's not well-documented\n> at all. OpenSSL ends up calling BIO_flush at the end of each batch of\n> writes in libssl. TBH, I suspect that was less intentional and more an\n> emergent property of them internally layering a buffer BIO at one point in\n> the process, but it's long been part of the (undocumented) API contract.\n> Conversely, I don't think OpenSSL can possibly make libssl *require* a\n> new BIO_CTRL because they'd break every custom BIO anyone has ever used\n> with the library.\n>\n>\n>> E.g. should we implement BIO_CTRL_EOF? Sure, it wasn't really supported so\n>> far, because we never set it, but is that right?\n>\n>\n> Ah hmm, BIO_CTRL_EOF is... a bit of a mess. OpenSSL kind of messed things\n> up. So, up until recently, I would have said that BIO_CTRL_EOF was not part\n> of the interface here. OpenSSL 1.0.x did not implement it for sockets, and\n> the BIO_read API *already* had a way to signal EOF: did you return zero\n> or -1?\n>\n> Then OpenSSL 1.1.x introduced size_t-based BIO_read_ex APIs. However, in\n> the process, they *forgot that EOF and error are different things* and\n> made it impossible to detect EOFs if you use BIO_read_ex! They never\n> noticed this, because they didn't actually convert their own code to their\n> new API. See this discussion, which alas ended with OpenSSL deciding to\n> ignore the problem and not even document their current interface.\n> https://github.com/openssl/openssl/issues/8208\n>\n> Though they never responded, they seem to have tacitly settled using the\n> out-of-band BIO_eof function (which is BIO_CTRL_EOF) as the way to signal\n> EOF for BIO_read_ex. This is kind of fiddly, but is at least a well-defined\n> option. But the problem is no one's BIO_METHODs, including their own, are\n> read_ex-based. They all implement the old read callback. But someone might\n> call BIO_read_ex on a read-based BIO_METHOD. IMO, BIO_read_ex should be\n> responsible for translating between the two EOF conventions. For example,\n> it could automatically set a flag when the read callback returns 0 and then\n> make BIO_ctrl check the flag and automatically implement BIO_CTRL_EOF for\n> BIOs that don't do it themselves. Alas, OpenSSL did not do this and instead\n> they just made their built-in BIOs implement BIO_CTRL_EOF, even though this\n> new expectation is a compatibility break. That leaves BIO_read, the one\n> everyone uses, in a pretty ambiguous state that they seem uninterested in\n> addressing.\n> https://github.com/openssl/openssl/pull/10882\n> https://github.com/openssl/openssl/pull/10907\n>\n> Honestly, I suspect nothing in postgres actually cares about this, given\n> you all didn't notice things breaking around here in the early days of\n> 1.1.x. Still, that is a good point. I've updated the patch to implement\n> BIO_CTRL_EOF for completeness' sake.\n>\n> (For BoringSSL, we did not go down this route because, unlike OpenSSL\n> apparently, we do not think breaking backwards compatibility in the EOF\n> convention is OK. I do want to add the size_t APIs eventually, but I'm\n> thinking we'll do the automatic BIO_CTRL_EOF thing described above, to\n> avoid breaking compatibility with existing BIO_METHODs.)\n>\n> Beyond BIO_CTRL_EOF, I assume what you're really asking here is \"how do we\n> know OpenSSL won't change the interface again?\". And, honestly, we don't.\n> They promise API and ABI stability, which in theory means they shouldn't.\n> But their track record with custom BIOs is not great. That said, if they do\n> break it, I think it will unambiguously be an API break on their part and\n> hopefully it'll be possible to get them to fix the issue. The EOF issue\n> snuck in because it mostly only impacted people who tried to migrate to\n> their new APIs. It broke existing APIs too, but the one project that\n> noticed (CPython) misdiagnosed the issue and worked around it.\n> (Incorrectly, but no one noticed. See\n> https://github.com/python/cpython/pull/95495.) So, I raised the issue,\n> they'd long since shipped it and evidently felt no burning need to fix\n> their regression or unclear APIs. :-(\n>\n> But the alternative, picking up the real socket BIO's ctrl function, is\n> even more unsound, so I think this is the better place to be.\n>\n>\n>> What about\n>> BIO_CTRL_GET_CLOSE/BIO_CTRL_SET_CLOSE?\n>>\n>\n> The close flag is pretty silly. All BIOs do slightly different things with\n> it, which means that libssl cannot possibly call it generically. So if your\n> BIO doesn't have any need for it, you don't need to bother. It's usually\n> used to indicate whether the BIO owns the underlying fd/socket/BUF_MEM/etc,\n>\n>\n>> Another issue is that 0 doesn't actually seem like the universal error\n>> return\n>> - e.g. BIO_C_GET_FD seems to return -1, because 0 is a valid fd.\n>>\n>\n> Yeah, that is... also a mess. All of OpenSSL's ctrl functions return zero\n> for unrecognized commands. It seems they just don't have a convention for\n> distinguishing unimplemented commands from zero returns. As you note, this\n> is a problem for BIO_C_GET_FD. OpenSSL's other non-fd BIOs have the same\n> problem though:\n> https://github.com/openssl/openssl/blob/master/crypto/bio/bss_file.c#L340\n>\n> Realistically, type-specific ioctls like that don't matter much because\n> you're really only going to call them if you already know you have an\n> applicable BIO. Hopefully, between that, and removing BIO_TYPE_DESCRIPTOR\n> (below), it's mostly okay? Also happy to add a `ret = -1` implementation\n> of BIO_C_GET_FD if you'd prefer. But, in the general case, I suspect we\n> just have to live with the zero thing, and hopefully OpenSSL will stop\n> introducing ctrls where zero is an unsafe return value.\n>\n> Perhaps BIO_ctrl in OpenSSL should have some logic like...\n> ```\n> if (!(type & BIO_TYPE_DESCRIPTOR) && cmd == BIO_C_GET_FD) {\n> return -1;\n> }\n> ```\n> Although I suspect there are people who implement BIO_C_GET_FD without\n> setting BIO_TYPE_DESCRIPTOR because none of this was ever documented.\n>\n>\n>> As of your patch the bio doesn't actually have an FD anymore, should it\n>> still\n>> set BIO_TYPE_DESCRIPTOR?\n>>\n>\n> Ah good call. Done. I don't think much code really cares, but it does mean\n> that, if you all call SSL_get_fd (why would you?), it won't get confused.\n> :-)\n>\n> > +static long\n>> > +my_sock_ctrl(BIO *h, int cmd, long num, void *ptr)\n>> > +{\n>> > + long res = 0;\n>> > +\n>> > + switch (cmd)\n>> > + {\n>> > + case BIO_CTRL_FLUSH:\n>> > + /* libssl expects all BIOs to support BIO_flush.\n>> */\n>> > + res = 1;\n>> > + break;\n>> > + }\n>> > +\n>> > + return res;\n>> > +}\n>>\n>> I'd move the res = 0 into a default: block. That way the compiler can\n>> warn if\n>> some case doesn't set it in all branches.\n>>\n>\n> Done.\n>\n>\n>> > static BIO_METHOD *\n>> > my_BIO_s_socket(void)\n>> > {\n>>\n>> Wonder if we should rename this. It's pretty odd that we still call it's\n>> not\n>> really related to s_socket anymore, and doesn't even really implement the\n>> same\n>> interface (e.g. get_fd doesn't work anymore). Similarly, my_SSL_set_fd()\n>> doesn't actually call set_fd() anymore, which sure seems odd.\n>>\n>\n> Done. I wasn't sure what to name them, or even what the naming convention\n> was, but I opted to name them after the Port and PGconn objects they wrap.\n> Happy to switch to another name if you have a better idea though.\n>\n> David\n>\n\nCircling back here, anything else needed from my end on this patch?On Wed, Feb 21, 2024, 17:04 David Benjamin <davidben@google.com> wrote:Thanks for the very thorough comments! I've attached a new version of the patch.On Thu, Feb 15, 2024 at 4:17 PM Andres Freund <andres@anarazel.de> wrote:Hi,\n\nOn 2024-02-11 13:19:00 -0500, David Benjamin wrote:\n> I've attached a patch for the master branch to fix up the custom BIOs used\n> by PostgreSQL, in light of the issues with the OpenSSL update recently.\n> While c82207a548db47623a2bfa2447babdaa630302b9 (switching from BIO_get_data\n> to BIO_get_app_data) resolved the immediate conflict, I don't think it\n> addressed the root cause, which is that PostgreSQL was mixing up two BIO\n> implementations, each of which expected to be driving the BIO.\n\nYea, that's certainly not nice - and I think we've been somewhat lucky it\nhasn't caused more issues. There's some nasty possibilities, e.g. sock_ctrl()\npartially enabling ktls without our initialization having called\nktls_enable(). Right now that just means ktls is unusable, but it's not hard\nto imagine accidentally ending up sending unencrypted data.Yeah. Even if, say, the ktls bits work, given you all care enough about I/O to have wanted to wrap the BIO, I assume you'd want to pick up those features on your own terms, e.g. by implementing the BIO_CTRLs yourself. \nI've in the past looked into not using a custom BIO [1], but I have my doubts\nabout that being a good idea. I think medium term we want to be able to do\nnetwork IO asynchronously, which seems quite hard to do when using openssl's\nsocket BIO. \n> Once we've done that, we're free to use BIO_set_data. While BIO_set_app_data\n> works fine, I've reverted back to BIO_set_data because it's more commonly used.\n> app_data depends on OpenSSL's \"ex_data\" mechanism, which is a tad heavier under\n> the hood.\n\nAt first I was a bit wary of that, because it requires us to bring back the\nfallback implementation. But you're right, it's noticeably heavier than\nBIO_get_data(), and we do call BIO_get_app_data() fairly frequently.TBH, I doubt it makes any real difference perf-wise. But I think BIO_get_data is a bit more common in this context. \n> That leaves ctrl. ctrl is a bunch of operations (it's ioctl). The only\n> operation that matters is BIO_CTRL_FLUSH, which is implemented as a no-op. All\n> other operations are unused. It's once again good that they're unused because\n> otherwise OpenSSL might mess with postgres's socket, break the assumptions\n> around interrupt handling, etc.\n\nHow did you determine that only FLUSH is required? I didn't even really find\ndocumentation about what the intended semantics actually are.The unhelpful answer is that my day job is working on BoringSSL, so I've spent a lot of time with this mess. :-) But, yeah, it's not well-documented at all. OpenSSL ends up calling BIO_flush at the end of each batch of writes in libssl. TBH, I suspect that was less intentional and more an emergent property of them internally layering a buffer BIO at one point in the process, but it's long been part of the (undocumented) API contract. Conversely, I don't think OpenSSL can possibly make libssl require a new BIO_CTRL because they'd break every custom BIO anyone has ever used with the library. \nE.g. should we implement BIO_CTRL_EOF? Sure, it wasn't really supported so\nfar, because we never set it, but is that right?Ah hmm, BIO_CTRL_EOF is... a bit of a mess. OpenSSL kind of messed things up. So, up until recently, I would have said that BIO_CTRL_EOF was not part of the interface here. OpenSSL 1.0.x did not implement it for sockets, and the BIO_read API already had a way to signal EOF: did you return zero or -1?Then OpenSSL 1.1.x introduced size_t-based BIO_read_ex APIs. However, in the process, they forgot that EOF and error are different things and made it impossible to detect EOFs if you use BIO_read_ex! They never noticed this, because they didn't actually convert their own code to their new API. See this discussion, which alas ended with OpenSSL deciding to ignore the problem and not even document their current interface.https://github.com/openssl/openssl/issues/8208Though they never responded, they seem to have tacitly settled using the out-of-band BIO_eof function (which is BIO_CTRL_EOF) as the way to signal EOF for BIO_read_ex. This is kind of fiddly, but is at least a well-defined option. But the problem is no one's BIO_METHODs, including their own, are read_ex-based. They all implement the old read callback. But someone might call BIO_read_ex on a read-based BIO_METHOD. IMO, BIO_read_ex should be responsible for translating between the two EOF conventions. For example, it could automatically set a flag when the read callback returns 0 and then make BIO_ctrl check the flag and automatically implement BIO_CTRL_EOF for BIOs that don't do it themselves. Alas, OpenSSL did not do this and instead they just made their built-in BIOs implement BIO_CTRL_EOF, even though this new expectation is a compatibility break. That leaves BIO_read, the one everyone uses, in a pretty ambiguous state that they seem uninterested in addressing.https://github.com/openssl/openssl/pull/10882https://github.com/openssl/openssl/pull/10907Honestly, I suspect nothing in postgres actually cares about this, given you all didn't notice things breaking around here in the early days of 1.1.x. Still, that is a good point. I've updated the patch to implement BIO_CTRL_EOF for completeness' sake.(For BoringSSL, we did not go down this route because, unlike OpenSSL apparently, we do not think breaking backwards compatibility in the EOF convention is OK. I do want to add the size_t APIs eventually, but I'm thinking we'll do the automatic BIO_CTRL_EOF thing described above, to avoid breaking compatibility with existing BIO_METHODs.)Beyond BIO_CTRL_EOF, I assume what you're really asking here is \"how do we know OpenSSL won't change the interface again?\". And, honestly, we don't. They promise API and ABI stability, which in theory means they shouldn't. But their track record with custom BIOs is not great. That said, if they do break it, I think it will unambiguously be an API break on their part and hopefully it'll be possible to get them to fix the issue. The EOF issue snuck in because it mostly only impacted people who tried to migrate to their new APIs. It broke existing APIs too, but the one project that noticed (CPython) misdiagnosed the issue and worked around it. (Incorrectly, but no one noticed. See https://github.com/python/cpython/pull/95495.) So, I raised the issue, they'd long since shipped it and evidently felt no burning need to fix their regression or unclear APIs. :-(But the alternative, picking up the real socket BIO's ctrl function, is even more unsound, so I think this is the better place to be. What about\nBIO_CTRL_GET_CLOSE/BIO_CTRL_SET_CLOSE?The close flag is pretty silly. All BIOs do slightly different things with it, which means that libssl cannot possibly call it generically. So if your BIO doesn't have any need for it, you don't need to bother. It's usually used to indicate whether the BIO owns the underlying fd/socket/BUF_MEM/etc, \nAnother issue is that 0 doesn't actually seem like the universal error return\n- e.g. BIO_C_GET_FD seems to return -1, because 0 is a valid fd.Yeah, that is... also a mess. All of OpenSSL's ctrl functions return zero for unrecognized commands. It seems they just don't have a convention for distinguishing unimplemented commands from zero returns. As you note, this is a problem for BIO_C_GET_FD. OpenSSL's other non-fd BIOs have the same problem though:https://github.com/openssl/openssl/blob/master/crypto/bio/bss_file.c#L340Realistically, type-specific ioctls like that don't matter much because you're really only going to call them if you already know you have an applicable BIO. Hopefully, between that, and removing BIO_TYPE_DESCRIPTOR (below), it's mostly okay? Also happy to add a `ret = -1` implementation of BIO_C_GET_FD if you'd prefer. But, in the general case, I suspect we just have to live with the zero thing, and hopefully OpenSSL will stop introducing ctrls where zero is an unsafe return value.Perhaps BIO_ctrl in OpenSSL should have some logic like...```if (!(type & BIO_TYPE_DESCRIPTOR) && cmd == BIO_C_GET_FD) { return -1;}```Although I suspect there are people who implement BIO_C_GET_FD without setting BIO_TYPE_DESCRIPTOR because none of this was ever documented. \nAs of your patch the bio doesn't actually have an FD anymore, should it still\nset BIO_TYPE_DESCRIPTOR? Ah good call. Done. I don't think much code really cares, but it does mean that, if you all call SSL_get_fd (why would you?), it won't get confused. :-)\n> +static long\n> +my_sock_ctrl(BIO *h, int cmd, long num, void *ptr)\n> +{\n> + long res = 0;\n> +\n> + switch (cmd)\n> + {\n> + case BIO_CTRL_FLUSH:\n> + /* libssl expects all BIOs to support BIO_flush. */\n> + res = 1;\n> + break;\n> + }\n> +\n> + return res;\n> +}\n\nI'd move the res = 0 into a default: block. That way the compiler can warn if\nsome case doesn't set it in all branches.Done. \n> static BIO_METHOD *\n> my_BIO_s_socket(void)\n> {\n\nWonder if we should rename this. It's pretty odd that we still call it's not\nreally related to s_socket anymore, and doesn't even really implement the same\ninterface (e.g. get_fd doesn't work anymore). Similarly, my_SSL_set_fd()\ndoesn't actually call set_fd() anymore, which sure seems odd.Done. I wasn't sure what to name them, or even what the naming convention was, but I opted to name them after the Port and PGconn objects they wrap. Happy to switch to another name if you have a better idea though.David",
"msg_date": "Fri, 19 Apr 2024 09:13:45 -0400",
"msg_from": "David Benjamin <davidben@google.com>",
"msg_from_op": true,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "> On 19 Apr 2024, at 15:13, David Benjamin <davidben@google.com> wrote:\n> \n> Circling back here, anything else needed from my end on this patch?\n\nPatience mostly, v17 very recently entered feature freeze so a lof of the\ndevelopers are busy finding and fixing bugs to stabilize the release. When the\nwindow for new features opens again I am sure this patch will get reviews (I\nhave it on my personal TODO and hope to get to it).\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Fri, 19 Apr 2024 15:17:10 +0200",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "Daniel Gustafsson <daniel@yesql.se> writes:\n> On 19 Apr 2024, at 15:13, David Benjamin <davidben@google.com> wrote:\n>> Circling back here, anything else needed from my end on this patch?\n\n> Patience mostly, v17 very recently entered feature freeze so a lof of the\n> developers are busy finding and fixing bugs to stabilize the\n> release.\n\nPer the cfbot [1], this patch needs a rebase over the ALPN-related\ncommits. It still isn't likely to get human attention before the\nJuly commitfest, but you can save some time by making sure it's\nin a reviewable state before that.\n\n\t\t\tregards, tom lane\n\n[1] http://commitfest.cputube.org/david-benjamin.html\n\n\n",
"msg_date": "Sun, 19 May 2024 12:21:07 -0400",
"msg_from": "Tom Lane <tgl@sss.pgh.pa.us>",
"msg_from_op": false,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "On Sun, May 19, 2024 at 12:21 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Per the cfbot [1], this patch needs a rebase over the ALPN-related\n> commits. It still isn't likely to get human attention before the\n> July commitfest, but you can save some time by making sure it's\n> in a reviewable state before that.\n>\n\nRebased version attached. (The conflict was pretty trivial. Both patches\nadd a field to some struct.)\n\nDavid",
"msg_date": "Sun, 19 May 2024 14:07:22 -0400",
"msg_from": "David Benjamin <davidben@google.com>",
"msg_from_op": true,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "On 19.05.24 20:07, David Benjamin wrote:\n> On Sun, May 19, 2024 at 12:21 PM Tom Lane <tgl@sss.pgh.pa.us \n> <mailto:tgl@sss.pgh.pa.us>> wrote:\n> \n> Per the cfbot [1], this patch needs a rebase over the ALPN-related\n> commits. It still isn't likely to get human attention before the\n> July commitfest, but you can save some time by making sure it's\n> in a reviewable state before that.\n> \n> \n> Rebased version attached. (The conflict was pretty trivial. Both patches \n> add a field to some struct.)\n\nNote that there is a concurrent plan to drop support for OpenSSL older \nthan 1.1.1 [0], which would obsolete your configure test for \nBIO_get_data. Whoever commits these should be sure to coordinate this.\n\n\n[0]: https://www.postgresql.org/message-id/flat/ZG3JNursG69dz1lr@paquier.xyz\n\n\n\n",
"msg_date": "Sun, 19 May 2024 22:21:37 +0200",
"msg_from": "Peter Eisentraut <peter@eisentraut.org>",
"msg_from_op": false,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "> On 19 May 2024, at 22:21, Peter Eisentraut <peter@eisentraut.org> wrote:\n\n> Whoever commits these should be sure to coordinate this.\n\nThanks for the reminder. I have this patchset, the OCSP stapling patchset and\nthe multiple-cert one on my radar for when I do the 1.1.0 removal work in the\nJuly CF. Will do another scan for SSL related patches in flight at the time.\n\n--\nDaniel Gustafsson\n\n\n\n",
"msg_date": "Sun, 19 May 2024 22:32:45 +0200",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "> On 19 May 2024, at 22:32, Daniel Gustafsson <daniel@yesql.se> wrote:\n> \n>> On 19 May 2024, at 22:21, Peter Eisentraut <peter@eisentraut.org> wrote:\n> \n>> Whoever commits these should be sure to coordinate this.\n> \n> Thanks for the reminder. I have this patchset, the OCSP stapling patchset and\n> the multiple-cert one on my radar for when I do the 1.1.0 removal work in the\n> July CF. Will do another scan for SSL related patches in flight at the time.\n\nAttached is a v4 rebase over the recent OpenSSL 1.0.2 removal which made this\npatch no longer apply. I've just started to dig into it so have no comments on\nit right now, but wanted to get a cleaned up version into the CFBot.\n\n--\nDaniel Gustafsson",
"msg_date": "Tue, 3 Sep 2024 14:18:07 +0200",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "> On 3 Sep 2024, at 14:18, Daniel Gustafsson <daniel@yesql.se> wrote:\n\n> Attached is a v4 rebase over the recent OpenSSL 1.0.2 removal which made this\n> patch no longer apply. I've just started to dig into it so have no comments on\n> it right now, but wanted to get a cleaned up version into the CFBot.\n\nCFBot building green for this, I just have a few small questions/comments:\n\n+\tmy_bio_index |= BIO_TYPE_SOURCE_SINK;\n\nAccording to the OpenSSL docs we should set BIO_TYPE_DESCRIPTOR as well as this\nBIO is socket based, but it's not entirely clear to me why. Is there a\nspecific reason it was removed?\n\n\n+\tbio_method = port_bio_method();\n \tif (bio_method == NULL)\n \t{\n \t\tSSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);\n\nSSL_F_SSL_SET_FD is no longer the correct function context for this error\nreporting. In OpenSSL 3.x it means nothing since SSLerr throws away the\nfunction when calling ERR_raise_data, but we still support 1.1.0+. I think the\ncorrect error would be BIOerr(BIO_F_BIO_METH_NEW..) but I wonder if we should\njust remove it since BIO_meth_new and BIO_new already set errors for us to\nconsume? It doesn't seem to make sense to add more errors on the queue here?\nThe same goes for the frontend part.\n\nThe attached v5 is a fresh rebase with my comments from above as 0002 to\nillustrate.\n\n--\nDaniel Gustafsson",
"msg_date": "Wed, 4 Sep 2024 15:22:12 +0200",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "On Wed, Sep 4, 2024 at 9:22 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n\n> > On 3 Sep 2024, at 14:18, Daniel Gustafsson <daniel@yesql.se> wrote:\n>\n> > Attached is a v4 rebase over the recent OpenSSL 1.0.2 removal which made\n> this\n> > patch no longer apply. I've just started to dig into it so have no\n> comments on\n> > it right now, but wanted to get a cleaned up version into the CFBot.\n>\n> CFBot building green for this, I just have a few small questions/comments:\n>\n> + my_bio_index |= BIO_TYPE_SOURCE_SINK;\n>\n> According to the OpenSSL docs we should set BIO_TYPE_DESCRIPTOR as well as\n> this\n> BIO is socket based, but it's not entirely clear to me why. Is there a\n> specific reason it was removed?\n>\n\nLooking around at what uses it, it seems BIO_TYPE_DESCRIPTOR is how OpenSSL\ndecides whether the BIO is expected to respond to BIO_get_fd\n(BIO_C_GET_FD). Since the custom BIO is not directly backed by an fd and\ndoesn't implement that control, I think we don't want to include that bit.\nhttps://github.com/openssl/openssl/blob/openssl-3.3.2/ssl/ssl_lib.c#L1621-L1643\n\nThe other place I saw that cares about this bit is this debug callback.\nThat one's kinda amusing because it assumes every fd-backed BIO stores its\nfd in bio->num, but bio->num is not even accessible to external BIOs. I\nassume this is an oversight because no one cares about this function.\nPerhaps that should be sampled from BIO_get_fd.\nhttps://github.com/openssl/openssl/blob/openssl-3.3.2/crypto/bio/bio_cb.c#L45-L62\n\nPractically speaking, though, I don't think it makes any difference whether\nBIO_TYPE_DESCRIPTOR or even BIO_TYPE_SOURCE_SINK is set or unset. I\ncouldn't find any code that's sensitive to BIO_TYPE_SOURCE_SINK and\npresumably Postgres is not calling SSL_get_rfd on an SSL object that it\nalready knows is backed by a PGconn. TBH if you just passed 0 in for the\nindex, it would probably work just as well.\n\n\n> + bio_method = port_bio_method();\n> if (bio_method == NULL)\n> {\n> SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);\n>\n> SSL_F_SSL_SET_FD is no longer the correct function context for this error\n> reporting. In OpenSSL 3.x it means nothing since SSLerr throws away the\n> function when calling ERR_raise_data, but we still support 1.1.0+. I\n> think the\n> correct error would be BIOerr(BIO_F_BIO_METH_NEW..) but I wonder if we\n> should\n> just remove it since BIO_meth_new and BIO_new already set errors for us to\n> consume? It doesn't seem to make sense to add more errors on the queue\n> here?\n> The same goes for the frontend part.\n>\n\nAh yeah, +1 to removing them. I've always found external code adding to the\nerror queue to be a little goofy. OpenSSL's error queue is weird enough\nwithout external additions! :-)\n\n\n> The attached v5 is a fresh rebase with my comments from above as 0002 to\n> illustrate.\n>\n\nLGTM\n\nDavid\n\nOn Wed, Sep 4, 2024 at 9:22 AM Daniel Gustafsson <daniel@yesql.se> wrote:> On 3 Sep 2024, at 14:18, Daniel Gustafsson <daniel@yesql.se> wrote:\n\n> Attached is a v4 rebase over the recent OpenSSL 1.0.2 removal which made this\n> patch no longer apply. I've just started to dig into it so have no comments on\n> it right now, but wanted to get a cleaned up version into the CFBot.\n\nCFBot building green for this, I just have a few small questions/comments:\n\n+ my_bio_index |= BIO_TYPE_SOURCE_SINK;\n\nAccording to the OpenSSL docs we should set BIO_TYPE_DESCRIPTOR as well as this\nBIO is socket based, but it's not entirely clear to me why. Is there a\nspecific reason it was removed?Looking around at what uses it, it seems BIO_TYPE_DESCRIPTOR is how OpenSSL decides whether the BIO is expected to respond to BIO_get_fd (BIO_C_GET_FD). Since the custom BIO is not directly backed by an fd and doesn't implement that control, I think we don't want to include that bit.https://github.com/openssl/openssl/blob/openssl-3.3.2/ssl/ssl_lib.c#L1621-L1643The other place I saw that cares about this bit is this debug callback. That one's kinda amusing because it assumes every fd-backed BIO stores its fd in bio->num, but bio->num is not even accessible to external BIOs. I assume this is an oversight because no one cares about this function. Perhaps that should be sampled from BIO_get_fd.https://github.com/openssl/openssl/blob/openssl-3.3.2/crypto/bio/bio_cb.c#L45-L62Practically speaking, though, I don't think it makes any difference whether BIO_TYPE_DESCRIPTOR or even BIO_TYPE_SOURCE_SINK is set or unset. I couldn't find any code that's sensitive to BIO_TYPE_SOURCE_SINK and presumably Postgres is not calling SSL_get_rfd on an SSL object that it already knows is backed by a PGconn. TBH if you just passed 0 in for the index, it would probably work just as well. \n+ bio_method = port_bio_method();\n if (bio_method == NULL)\n {\n SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);\n\nSSL_F_SSL_SET_FD is no longer the correct function context for this error\nreporting. In OpenSSL 3.x it means nothing since SSLerr throws away the\nfunction when calling ERR_raise_data, but we still support 1.1.0+. I think the\ncorrect error would be BIOerr(BIO_F_BIO_METH_NEW..) but I wonder if we should\njust remove it since BIO_meth_new and BIO_new already set errors for us to\nconsume? It doesn't seem to make sense to add more errors on the queue here?\nThe same goes for the frontend part.Ah yeah, +1 to removing them. I've always found external code adding to the error queue to be a little goofy. OpenSSL's error queue is weird enough without external additions! :-) \nThe attached v5 is a fresh rebase with my comments from above as 0002 to\nillustrate.LGTM David",
"msg_date": "Wed, 4 Sep 2024 17:19:18 -0400",
"msg_from": "David Benjamin <davidben@google.com>",
"msg_from_op": true,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
},
{
"msg_contents": "> On 4 Sep 2024, at 23:19, David Benjamin <davidben@google.com> wrote:\n> \n> On Wed, Sep 4, 2024 at 9:22 AM Daniel Gustafsson <daniel@yesql.se <mailto:daniel@yesql.se>> wrote:\n>> > On 3 Sep 2024, at 14:18, Daniel Gustafsson <daniel@yesql.se <mailto:daniel@yesql.se>> wrote:\n>> \n>> > Attached is a v4 rebase over the recent OpenSSL 1.0.2 removal which made this\n>> > patch no longer apply. I've just started to dig into it so have no comments on\n>> > it right now, but wanted to get a cleaned up version into the CFBot.\n>> \n>> CFBot building green for this, I just have a few small questions/comments:\n>> \n>> + my_bio_index |= BIO_TYPE_SOURCE_SINK;\n>> \n>> According to the OpenSSL docs we should set BIO_TYPE_DESCRIPTOR as well as this\n>> BIO is socket based, but it's not entirely clear to me why. Is there a\n>> specific reason it was removed?\n> \n> Looking around at what uses it, it seems BIO_TYPE_DESCRIPTOR is how OpenSSL decides whether the BIO is expected to respond to BIO_get_fd (BIO_C_GET_FD). Since the custom BIO is not directly backed by an fd and doesn't implement that control, I think we don't want to include that bit.\n> https://github.com/openssl/openssl/blob/openssl-3.3.2/ssl/ssl_lib.c#L1621-L1643\n> \n> The other place I saw that cares about this bit is this debug callback. That one's kinda amusing because it assumes every fd-backed BIO stores its fd in bio->num, but bio->num is not even accessible to external BIOs. I assume this is an oversight because no one cares about this function. Perhaps that should be sampled from BIO_get_fd.\n> https://github.com/openssl/openssl/blob/openssl-3.3.2/crypto/bio/bio_cb.c#L45-L62\n> \n> Practically speaking, though, I don't think it makes any difference whether BIO_TYPE_DESCRIPTOR or even BIO_TYPE_SOURCE_SINK is set or unset. I couldn't find any code that's sensitive to BIO_TYPE_SOURCE_SINK and presumably Postgres is not calling SSL_get_rfd on an SSL object that it already knows is backed by a PGconn. TBH if you just passed 0 in for the index, it would probably work just as well.\n\nFollowing the bouncing ball around the code tonight I agree with that. I think\nwe should stick to setting BIO_TYPE_SOURCE_SINK though, if only for passing in\nzero might seem incorrect enough that we get emails about that from future readers.\n\n>> + bio_method = port_bio_method();\n>> if (bio_method == NULL)\n>> {\n>> SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);\n>> \n>> SSL_F_SSL_SET_FD is no longer the correct function context for this error\n>> reporting. In OpenSSL 3.x it means nothing since SSLerr throws away the\n>> function when calling ERR_raise_data, but we still support 1.1.0+. I think the\n>> correct error would be BIOerr(BIO_F_BIO_METH_NEW..) but I wonder if we should\n>> just remove it since BIO_meth_new and BIO_new already set errors for us to\n>> consume? It doesn't seem to make sense to add more errors on the queue here?\n>> The same goes for the frontend part.\n> \n> Ah yeah, +1 to removing them. I've always found external code adding to the error queue to be a little goofy. OpenSSL's error queue is weird enough without external additions! :-)\n\nI wholeheartedly agree. I've previously gone on record saying that every day\nwith the OpenSSL API is an adventure, and the errorhandling code doubly so.\n\n>> The attached v5 is a fresh rebase with my comments from above as 0002 to\n>> illustrate.\n> \n> LGTM \n\nThanks for reviewing, I plan on going ahead with this patch shortly.\n\n--\nDaniel Gustafsson\n\n\nOn 4 Sep 2024, at 23:19, David Benjamin <davidben@google.com> wrote:On Wed, Sep 4, 2024 at 9:22 AM Daniel Gustafsson <daniel@yesql.se> wrote:> On 3 Sep 2024, at 14:18, Daniel Gustafsson <daniel@yesql.se> wrote:\n\n> Attached is a v4 rebase over the recent OpenSSL 1.0.2 removal which made this\n> patch no longer apply. I've just started to dig into it so have no comments on\n> it right now, but wanted to get a cleaned up version into the CFBot.\n\nCFBot building green for this, I just have a few small questions/comments:\n\n+ my_bio_index |= BIO_TYPE_SOURCE_SINK;\n\nAccording to the OpenSSL docs we should set BIO_TYPE_DESCRIPTOR as well as this\nBIO is socket based, but it's not entirely clear to me why. Is there a\nspecific reason it was removed?Looking around at what uses it, it seems BIO_TYPE_DESCRIPTOR is how OpenSSL decides whether the BIO is expected to respond to BIO_get_fd (BIO_C_GET_FD). Since the custom BIO is not directly backed by an fd and doesn't implement that control, I think we don't want to include that bit.https://github.com/openssl/openssl/blob/openssl-3.3.2/ssl/ssl_lib.c#L1621-L1643The other place I saw that cares about this bit is this debug callback. That one's kinda amusing because it assumes every fd-backed BIO stores its fd in bio->num, but bio->num is not even accessible to external BIOs. I assume this is an oversight because no one cares about this function. Perhaps that should be sampled from BIO_get_fd.https://github.com/openssl/openssl/blob/openssl-3.3.2/crypto/bio/bio_cb.c#L45-L62Practically speaking, though, I don't think it makes any difference whether BIO_TYPE_DESCRIPTOR or even BIO_TYPE_SOURCE_SINK is set or unset. I couldn't find any code that's sensitive to BIO_TYPE_SOURCE_SINK and presumably Postgres is not calling SSL_get_rfd on an SSL object that it already knows is backed by a PGconn. TBH if you just passed 0 in for the index, it would probably work just as well.Following the bouncing ball around the code tonight I agree with that. I thinkwe should stick to setting BIO_TYPE_SOURCE_SINK though, if only for passing inzero might seem incorrect enough that we get emails about that from future readers.\n+ bio_method = port_bio_method();\n if (bio_method == NULL)\n {\n SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);\n\nSSL_F_SSL_SET_FD is no longer the correct function context for this error\nreporting. In OpenSSL 3.x it means nothing since SSLerr throws away the\nfunction when calling ERR_raise_data, but we still support 1.1.0+. I think the\ncorrect error would be BIOerr(BIO_F_BIO_METH_NEW..) but I wonder if we should\njust remove it since BIO_meth_new and BIO_new already set errors for us to\nconsume? It doesn't seem to make sense to add more errors on the queue here?\nThe same goes for the frontend part.Ah yeah, +1 to removing them. I've always found external code adding to the error queue to be a little goofy. OpenSSL's error queue is weird enough without external additions! :-)I wholeheartedly agree. I've previously gone on record saying that every daywith the OpenSSL API is an adventure, and the errorhandling code doubly so.\nThe attached v5 is a fresh rebase with my comments from above as 0002 to\nillustrate.LGTM Thanks for reviewing, I plan on going ahead with this patch shortly.\n--Daniel Gustafsson",
"msg_date": "Thu, 5 Sep 2024 00:10:17 +0200",
"msg_from": "Daniel Gustafsson <daniel@yesql.se>",
"msg_from_op": false,
"msg_subject": "Re: [PATCH] Avoid mixing custom and OpenSSL BIO functions"
}
] |
[
{
"msg_contents": "Hi,\n\nThere are several places where publisher and subscriber terms are used\nacross the documentation. But the publisher and subscriber were\nmissing in the documentation. I felt this should be added in the\nglossary.\nI have created a patch for the same.\n\nThanks and Regards\nShlok Kyal",
"msg_date": "Mon, 12 Feb 2024 16:30:35 +0530",
"msg_from": "Shlok Kyal <shlok.kyal.oss@gmail.com>",
"msg_from_op": true,
"msg_subject": "Add publisher and subscriber to glossary documentation."
},
{
"msg_contents": "Hello\n\nOn 2024-Feb-12, Shlok Kyal wrote:\n\n> There are several places where publisher and subscriber terms are used\n> across the documentation. But the publisher and subscriber were\n> missing in the documentation. I felt this should be added in the\n> glossary.\n\nI agree, but let's wordsmith those definitions first.\n\nShould these be \"publisher node\" and \"subscriber node\" instead? Do we\nwant to define the term \"node\"? I think in everyday conversations we\nuse \"node\" quite a lot, so maybe we do need an entry for it. (Maybe\njust <glossssee otherterm=\"instance\"> suffices, plus add under instance\n\"also called a node\".)\n\n+ <glossterm>Publisher</glossterm>\n+ <glossdef>\n+ <para>\n+ A node where publication is defined.\n+ It replicates the publication changes to the subscriber node.\n\nApart from deciding what to do with \"node\", what are \"changes\"? This\ndoesn't seem very specific.\n\n+ <glossterm>Subscriber</glossterm>\n+ <glossdef>\n+ <para>\n+ A node where subscription is defined.\n+ It subscribe to one or more publications on a publisher node and pull the data\n+ from the publications they subscribe to.\n\nSame issues as above, plus there are some grammar issues.\n\n\nI think these definitions should use the term \"logical replication\",\nwhich we don't currently define. We do have \"replication\" where we\nprovide an overview of \"logical replication\". Maybe that's enough, but\nwe should consider whether we want a separate definition of logical\nreplication (I'm leaning towards not having one, but it's worth asking.)\n\n-- \nÁlvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/\n\"But static content is just dynamic content that isn't moving!\"\n http://smylers.hates-software.com/2007/08/15/fe244d0c.html\n\n\n",
"msg_date": "Mon, 12 Feb 2024 12:26:40 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: Add publisher and subscriber to glossary documentation."
},
{
"msg_contents": "Hi,\nI addressed the comments and updated the patch.\n\n> Should these be \"publisher node\" and \"subscriber node\" instead? Do we\n> want to define the term \"node\"? I think in everyday conversations we\n> use \"node\" quite a lot, so maybe we do need an entry for it. (Maybe\n> just <glossssee otherterm=\"instance\"> suffices, plus add under instance\n> \"also called a node\".)\n\nModified\n\n> + <glossterm>Publisher</glossterm>\n> + <glossdef>\n> + <para>\n> + A node where publication is defined.\n> + It replicates the publication changes to the subscriber node.\n>\n> Apart from deciding what to do with \"node\", what are \"changes\"? This\n> doesn't seem very specific.\n\nModified\n\n> + <glossterm>Subscriber</glossterm>\n> + <glossdef>\n> + <para>\n> + A node where subscription is defined.\n> + It subscribe to one or more publications on a publisher node and pull the data\n> + from the publications they subscribe to.\n>\n> Same issues as above, plus there are some grammar issues.\n\nModified\n\n> I think these definitions should use the term \"logical replication\",\n> which we don't currently define. We do have \"replication\" where we\n> provide an overview of \"logical replication\". Maybe that's enough, but\n> we should consider whether we want a separate definition of logical\n> replication (I'm leaning towards not having one, but it's worth asking.)\n\nModified. Added the term \"logical replication\" in the definitions.\nUsed reference to \"replication\".\n\nThanks and Regards,\nShlok Kyal",
"msg_date": "Tue, 13 Feb 2024 16:18:33 +0530",
"msg_from": "Shlok Kyal <shlok.kyal.oss@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Add publisher and subscriber to glossary documentation."
},
{
"msg_contents": "Here are some comments for patch v2.\n\n======\n\n1. There are whitespace problems\n\n[postgres@CentOS7-x64 oss_postgres_misc]$ git apply\n../patches_misc/v2-0001-Add-publisher-and-subscriber-to-glossary-document.patch\n../patches_misc/v2-0001-Add-publisher-and-subscriber-to-glossary-document.patch:43:\ntrailing whitespace.\n A node where publication is defined for\n../patches_misc/v2-0001-Add-publisher-and-subscriber-to-glossary-document.patch:45:\ntrailing whitespace.\n It replicates a set of changes from a table or a group of tables in\n../patches_misc/v2-0001-Add-publisher-and-subscriber-to-glossary-document.patch:66:\ntrailing whitespace.\n A node where subscription is defined for\n../patches_misc/v2-0001-Add-publisher-and-subscriber-to-glossary-document.patch:67:\ntrailing whitespace.\n <glossterm linkend=\"glossary-replication\">logical replication</glossterm>.\n../patches_misc/v2-0001-Add-publisher-and-subscriber-to-glossary-document.patch:68:\ntrailing whitespace.\n It subscribes to one or more publications on a publisher node and pulls\nwarning: squelched 2 whitespace errors\nwarning: 7 lines add whitespace errors.\n\n~~~\n\n2. Publisher node\n\n+ <glossentry id=\"glossary-publisher\">\n+ <glossterm>Publisher node</glossterm>\n+ <glossdef>\n+ <para>\n+ A node where publication is defined for\n+ <glossterm linkend=\"glossary-replication\">logical\nreplication</glossterm>.\n+ It replicates a set of changes from a table or a group of tables in\n+ publication to the subscriber node.\n+ </para>\n+ <para>\n+ For more information, see\n+ <xref linkend=\"logical-replication-publication\"/>.\n+ </para>\n+ </glossdef>\n+ </glossentry>\n+\n\n\n2a.\nI felt the term here should be \"Publication node\".\n\nIndeed, there should also be additional glossary terms like\n\"Publisher\" (i.e. it is the same as \"Publication node\") and\n\"Subscriber\" (i.e. it is the same as \"Subscription node\"). These\ndefinitions will then be consistent with node descriptions already in\nsections 30.1 and 30.2\n\n\n~\n\n2b.\n\"node\" should include a link to the glossary term. Same for any other\nterms mentioned\n\n~\n\n2c.\n/A node where publication is defined for/A node where a publication is\ndefined for/\n\n~\n\n2d.\n\"It replicates\" is misleading because it is the PUBLICATION doing the\nreplicating, not the node.\n\nIMO it will be better to include 2 more glossary terms \"Publication\"\nand \"Subscription\" where you can say this kind of information. Then\nthe link \"logical-replication-publication\" also belongs under the\n\"Publication\" term.\n\n\n~~~\n\n3.\n+ <glossentry id=\"glossary-subscriber\">\n+ <glossterm>Subscriber node</glossterm>\n+ <glossdef>\n+ <para>\n+ A node where subscription is defined for\n+ <glossterm linkend=\"glossary-replication\">logical replication</glossterm>.\n+ It subscribes to one or more publications on a publisher node and pulls\n+ a set of changes from a table or a group of tables in publications it\n+ subscribes to.\n+ </para>\n+ <para>\n+ For more information, see\n+ <xref linkend=\"logical-replication-subscription\"/>.\n+ </para>\n+ </glossdef>\n+ </glossentry>\n\nAll comments are similar to those above.\n\n======\n\nIn summary, IMO it should be a bit more like below:\n\nSUGGESTION (include all the necessary links etc)\n\nPublisher\nSee \"Publication node\"\n\nPublication\nA publication replicates the changes of one or more tables to a\nsubscription. For more information, see Section 30.1\n\nPublication node\nA node where a publication is defined for logical replication.\n\nSubscriber\nSee \"Subscription node\"\n\nSubscription\nA subscription receives the changes of one or more tables from the\npublications it subscribes to. For more information, see Section 30.2\n\nSubscription node\nA node where a subscription is defined for logical replication.\n\n======\nKind Regards,\nPeter Smith.\nFujitsu Australia\n\n\n",
"msg_date": "Fri, 23 Feb 2024 13:27:51 +1100",
"msg_from": "Peter Smith <smithpb2250@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add publisher and subscriber to glossary documentation."
},
{
"msg_contents": "> Here are some comments for patch v2.\n>\n> ======\n>\n> 1. There are whitespace problems\n>\n> [postgres@CentOS7-x64 oss_postgres_misc]$ git apply\n> ../patches_misc/v2-0001-Add-publisher-and-subscriber-to-glossary-document.patch\n> ../patches_misc/v2-0001-Add-publisher-and-subscriber-to-glossary-document.patch:43:\n> trailing whitespace.\n> A node where publication is defined for\n> ../patches_misc/v2-0001-Add-publisher-and-subscriber-to-glossary-document.patch:45:\n> trailing whitespace.\n> It replicates a set of changes from a table or a group of tables in\n> ../patches_misc/v2-0001-Add-publisher-and-subscriber-to-glossary-document.patch:66:\n> trailing whitespace.\n> A node where subscription is defined for\n> ../patches_misc/v2-0001-Add-publisher-and-subscriber-to-glossary-document.patch:67:\n> trailing whitespace.\n> <glossterm linkend=\"glossary-replication\">logical replication</glossterm>.\n> ../patches_misc/v2-0001-Add-publisher-and-subscriber-to-glossary-document.patch:68:\n> trailing whitespace.\n> It subscribes to one or more publications on a publisher node and pulls\n> warning: squelched 2 whitespace errors\n> warning: 7 lines add whitespace errors.\n>\n> ~~~\n> 2. Publisher node\n>\n> + <glossentry id=\"glossary-publisher\">\n> + <glossterm>Publisher node</glossterm>\n> + <glossdef>\n> + <para>\n> + A node where publication is defined for\n> + <glossterm linkend=\"glossary-replication\">logical\n> replication</glossterm>.\n> + It replicates a set of changes from a table or a group of tables in\n> + publication to the subscriber node.\n> + </para>\n> + <para>\n> + For more information, see\n> + <xref linkend=\"logical-replication-publication\"/>.\n> + </para>\n> + </glossdef>\n> + </glossentry>\n> +\n>\n>\n> 2a.\n> I felt the term here should be \"Publication node\".\n>\n> Indeed, there should also be additional glossary terms like\n> \"Publisher\" (i.e. it is the same as \"Publication node\") and\n> \"Subscriber\" (i.e. it is the same as \"Subscription node\"). These\n> definitions will then be consistent with node descriptions already in\n> sections 30.1 and 30.2\n>\n>\n> ~\n>\n> 2b.\n> \"node\" should include a link to the glossary term. Same for any other\n> terms mentioned\n>\n> ~\n>\n> 2c.\n> /A node where publication is defined for/A node where a publication is\n> defined for/\n>\n> ~\n>\n> 2d.\n> \"It replicates\" is misleading because it is the PUBLICATION doing the\n> replicating, not the node.\n>\n> IMO it will be better to include 2 more glossary terms \"Publication\"\n> and \"Subscription\" where you can say this kind of information. Then\n> the link \"logical-replication-publication\" also belongs under the\n> \"Publication\" term.\n>\n>\n> ~~~\n>\n> 3.\n> + <glossentry id=\"glossary-subscriber\">\n> + <glossterm>Subscriber node</glossterm>\n> + <glossdef>\n> + <para>\n> + A node where subscription is defined for\n> + <glossterm linkend=\"glossary-replication\">logical replication</glossterm>.\n> + It subscribes to one or more publications on a publisher node and pulls\n> + a set of changes from a table or a group of tables in publications it\n> + subscribes to.\n> + </para>\n> + <para>\n> + For more information, see\n> + <xref linkend=\"logical-replication-subscription\"/>.\n> + </para>\n> + </glossdef>\n> + </glossentry>\n>\n> All comments are similar to those above.\n>\n> ======\n>\n> In summary, IMO it should be a bit more like below:\n>\n> SUGGESTION (include all the necessary links etc)\n>\n> Publisher\n> See \"Publication node\"\n>\n> Publication\n> A publication replicates the changes of one or more tables to a\n> subscription. For more information, see Section 30.1\n>\n> Publication node\n> A node where a publication is defined for logical replication.\n>\n> Subscriber\n> See \"Subscription node\"\n>\n> Subscription\n> A subscription receives the changes of one or more tables from the\n> publications it subscribes to. For more information, see Section 30.2\n>\n> Subscription node\n> A node where a subscription is defined for logical replication.\n\nI have addressed the comments and added an updated patch.\n\nThanks and Regards,\nShlok Kyal",
"msg_date": "Fri, 23 Feb 2024 14:15:23 +0530",
"msg_from": "Shlok Kyal <shlok.kyal.oss@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Add publisher and subscriber to glossary documentation."
},
{
"msg_contents": "Here are some comments for patch v3:\n\n1.\n+ <glossentry id=\"glossary-publication-node\">\n+ <glossterm>Publication node</glossterm>\n+ <glossdef>\n+ <para>\n+ A <glossterm linkend=\"glossary-instance\">node</glossterm> where a\n+ <glossterm\nlinkend=\"glossary-publication\">publication</glossterm> is defined\n+ for <glossterm linkend=\"glossary-replication\">logical\nreplication</glossterm>.\n+ </para>\n+ </glossdef>\n+ </glossentry>\n+\n\nI felt the word \"node\" here should link to the glossary term \"Node\",\ninstead of directly to the term \"Instance\".\n\n~~\n\n2.\n+ <glossentry id=\"glossary-subscription-node\">\n+ <glossterm>Subscription node</glossterm>\n+ <glossdef>\n+ <para>\n+ A <glossterm linkend=\"glossary-instance\">node</glossterm> where a\n+ <glossterm\nlinkend=\"glossary-subscription\">subscription</glossterm> is defined\n+ for <glossterm linkend=\"glossary-replication\">logical\nreplication</glossterm>.\n+ </para>\n+ </glossdef>\n+ </glossentry>\n+\n\n(same comment as above)\n\nI felt the word \"node\" here should link to the glossary term \"Node\",\ninstead of directly to the term \"Instance\".\n\n~~\n\nApart from those links, it looks good to me. Let's see what others think.\n\n======\nKind Regards,\nPeter Smith.\nFujitsu Australia\n\n\n",
"msg_date": "Mon, 26 Feb 2024 11:11:02 +1100",
"msg_from": "Peter Smith <smithpb2250@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add publisher and subscriber to glossary documentation."
},
{
"msg_contents": "> 1.\n> + <glossentry id=\"glossary-publication-node\">\n> + <glossterm>Publication node</glossterm>\n> + <glossdef>\n> + <para>\n> + A <glossterm linkend=\"glossary-instance\">node</glossterm> where a\n> + <glossterm\n> linkend=\"glossary-publication\">publication</glossterm> is defined\n> + for <glossterm linkend=\"glossary-replication\">logical\n> replication</glossterm>.\n> + </para>\n> + </glossdef>\n> + </glossentry>\n> +\n>\n> I felt the word \"node\" here should link to the glossary term \"Node\",\n> instead of directly to the term \"Instance\".\n>\n> ~~\n>\n> 2.\n> + <glossentry id=\"glossary-subscription-node\">\n> + <glossterm>Subscription node</glossterm>\n> + <glossdef>\n> + <para>\n> + A <glossterm linkend=\"glossary-instance\">node</glossterm> where a\n> + <glossterm\n> linkend=\"glossary-subscription\">subscription</glossterm> is defined\n> + for <glossterm linkend=\"glossary-replication\">logical\n> replication</glossterm>.\n> + </para>\n> + </glossdef>\n> + </glossentry>\n> +\n>\n> (same comment as above)\n>\n> I felt the word \"node\" here should link to the glossary term \"Node\",\n> instead of directly to the term \"Instance\".\n\nI have addressed the comments and have attached the updated version.\n\nThanks and Regards,\nShlok Kyal",
"msg_date": "Mon, 26 Feb 2024 12:25:42 +0530",
"msg_from": "Shlok Kyal <shlok.kyal.oss@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Add publisher and subscriber to glossary documentation."
},
{
"msg_contents": "Hi, the patch v4 LGTM.\n\n======\nKind Regards,\nPeter Smith.\nFujitsu Australia\n\n\n",
"msg_date": "Mon, 26 Feb 2024 18:07:32 +1100",
"msg_from": "Peter Smith <smithpb2250@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add publisher and subscriber to glossary documentation."
},
{
"msg_contents": "If there's a movement towards \"node\" to refer to the database which has the\nSubscription object, then perhaps the documentation for\n\n31.2. Subscription, Chapter 31. Logical Replication\n<https://www.postgresql.org/docs/current/logical-replication-subscription.html>\nshould be updated as well, since it uses both the \"database\" and \"node\"\nterms on the same page, and to me referring to the same thing (I could be\nmissing a subtlety).\n\nSee:\n\n\"The subscriber database...\"\n\n\"A subscriber node may...\"\n\nAlso, the word \"database\" in this sentence: \"A subscription defines the\nconnection to another database\" to me works, but I think using \"node\" there\ncould be more consistent if it’s referring to the server instance running\nthe database that holds the PUBLICATION. The connection string information\nexample later on the page shows \"host\" and \"dbname\" configured in the\nCONNECTION value for the SUBSCRIPTION. This sentence seems like the use of\n\"database\" in casual style to mean the \"server instance\" (or \"node\").\n\nAlso, the \"The node where a subscription is defined\". That one actually\nfeels to me like \"The database where a subscription is defined\", but then\nthat contradicts what I just said, and \"node\" is fine here but I think\n\"node\" should be on the preceding sentence too.\n\nAnyway, hopefully these examples show “node” and “database” are mixed and\nperhaps others agree using one consistently might help the goals of the\ndocs.\n\n\nThanks!\n\n\n\nOn Mon, Feb 26, 2024 at 1:08 AM Peter Smith <smithpb2250@gmail.com> wrote:\n\n> Hi, the patch v4 LGTM.\n>\n> ======\n> Kind Regards,\n> Peter Smith.\n> Fujitsu Australia\n>\n>\n>\n\nIf there's a movement towards \"node\" to refer to the database which has the Subscription object, then perhaps the documentation for31.2. Subscription, Chapter 31. Logical Replication should be updated as well, since it uses both the \"database\" and \"node\" terms on the same page, and to me referring to the same thing (I could be missing a subtlety).See:\"The subscriber database...\"\"A subscriber node may...\"Also, the word \"database\" in this sentence: \"A subscription defines the connection to another database\" to me works, but I think using \"node\" there could be more consistent if it’s referring to the server instance running the database that holds the PUBLICATION. The connection string information example later on the page shows \"host\" and \"dbname\" configured in the CONNECTION value for the SUBSCRIPTION. This sentence seems like the use of \"database\" in casual style to mean the \"server instance\" (or \"node\").Also, the \"The node where a subscription is defined\". That one actually feels to me like \"The database where a subscription is defined\", but then that contradicts what I just said, and \"node\" is fine here but I think \"node\" should be on the preceding sentence too.Anyway, hopefully these examples show “node” and “database” are mixed and perhaps others agree using one consistently might help the goals of the docs.Thanks!On Mon, Feb 26, 2024 at 1:08 AM Peter Smith <smithpb2250@gmail.com> wrote:Hi, the patch v4 LGTM.\n\n======\nKind Regards,\nPeter Smith.\nFujitsu Australia",
"msg_date": "Mon, 26 Feb 2024 15:13:34 -0600",
"msg_from": "Andrew Atkinson <andyatkinson@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add publisher and subscriber to glossary documentation."
},
{
"msg_contents": "Hi Andrew,\n\n> If there's a movement towards \"node\" to refer to the database which has the Subscription object, then perhaps the documentation for\n>\n> 31.2. Subscription, Chapter 31. Logical Replication should be updated as well, since it uses both the \"database\" and \"node\" terms on the same page, and to me referring to the same thing (I could be missing a subtlety).\n>\n>\n> See:\n>\n>\n> \"The subscriber database...\"\n>\n>\n> \"A subscriber node may...\"\n>\n>\n> Also, the word \"database\" in this sentence: \"A subscription defines the connection to another database\" to me works, but I think using \"node\" there could be more consistent if it’s referring to the server instance running the database that holds the PUBLICATION. The connection string information example later on the page shows \"host\" and \"dbname\" configured in the CONNECTION value for the SUBSCRIPTION. This sentence seems like the use of \"database\" in casual style to mean the \"server instance\" (or \"node\").\n>\n>\n> Also, the \"The node where a subscription is defined\". That one actually feels to me like \"The database where a subscription is defined\", but then that contradicts what I just said, and \"node\" is fine here but I think \"node\" should be on the preceding sentence too.\n>\n>\n> Anyway, hopefully these examples show “node” and “database” are mixed and perhaps others agree using one consistently might help the goals of the docs.\n\nFor me the existing content looks good, I felt let's keep it as it is\nunless others feel differently.\n\nThanks and regards,\nShlok Kyal\n\n\n",
"msg_date": "Thu, 14 Mar 2024 16:20:55 +0530",
"msg_from": "Shlok Kyal <shlok.kyal.oss@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: Add publisher and subscriber to glossary documentation."
},
{
"msg_contents": "On 2024-Mar-14, Shlok Kyal wrote:\n\n> Andrew Atkinson wrote:\n>\n> > Anyway, hopefully these examples show “node” and “database” are\n> > mixed and perhaps others agree using one consistently might help the\n> > goals of the docs.\n> \n> For me the existing content looks good, I felt let's keep it as it is\n> unless others feel differently.\n\nActually it's these small terminology glitches that give me pause. If\nwe're going to have terms that are interchangeable (in this case \"node\"\nand \"database\"), then they should be always interchangeable, not just in\nsome unspecified cases. Maybe the idea of using \"node\" (which sounds\nlike something that's instance-wide) is wrong for logical replication,\nwhich is necessarily something that happens database-locally.\n\nThen again, maybe defining \"node\" as something that exists at a\ndatabase-local level when used in the context of logical replication is\nsufficient. In that case, it would be better to avoid defining it as a\nsynonym of \"instance\". Then the terms are not always interchangeable,\nbut it's clear when they are and when they aren't.\n\n\"Node: in <glossterm>replication</>, each of the endpoints to which or\nfrom which data is replicated. In the context of physical replication,\neach node is an instance. In the context of logical replication, each\nnode is a database\".\n\nDoes that make sense?\n\nI'd also look at altering \"Primary\" and \"Standby\" so that it's clearer\nthat they're about physical replication, and don't mention \"database\"\nanymore, since that's the wrong level. Maybe turn them into \"Primary\n(node)\" and \"Standby (node)\" instead.\n\n-- \nÁlvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/\n\n\n",
"msg_date": "Thu, 14 Mar 2024 15:21:46 +0100",
"msg_from": "Alvaro Herrera <alvherre@alvh.no-ip.org>",
"msg_from_op": false,
"msg_subject": "Re: Add publisher and subscriber to glossary documentation."
},
{
"msg_contents": "On Thu, Mar 14, 2024 at 7:51 PM Alvaro Herrera <alvherre@alvh.no-ip.org> wrote:\n>\n> On 2024-Mar-14, Shlok Kyal wrote:\n>\n> > Andrew Atkinson wrote:\n> >\n> > > Anyway, hopefully these examples show “node” and “database” are\n> > > mixed and perhaps others agree using one consistently might help the\n> > > goals of the docs.\n> >\n> > For me the existing content looks good, I felt let's keep it as it is\n> > unless others feel differently.\n>\n> Actually it's these small terminology glitches that give me pause. If\n> we're going to have terms that are interchangeable (in this case \"node\"\n> and \"database\"), then they should be always interchangeable, not just in\n> some unspecified cases. Maybe the idea of using \"node\" (which sounds\n> like something that's instance-wide) is wrong for logical replication,\n> which is necessarily something that happens database-locally.\n>\n> Then again, maybe defining \"node\" as something that exists at a\n> database-local level when used in the context of logical replication is\n> sufficient. In that case, it would be better to avoid defining it as a\n> synonym of \"instance\". Then the terms are not always interchangeable,\n> but it's clear when they are and when they aren't.\n>\n> \"Node: in <glossterm>replication</>, each of the endpoints to which or\n> from which data is replicated. In the context of physical replication,\n> each node is an instance. In the context of logical replication, each\n> node is a database\".\n>\n\nI think node should mean instance for both physical and logical\nreplication, otherwise, it would be confusing. We need both the usages\nas a particular publication/subscription is defined at the database\nlevel but the server on which we define those is referred to as a\nnode/instance.\n\nOne of the usages pointed out by Andrew: \"The subscriber database...\"\n[1] is unclear but I feel we can use node there as well instead of\ndatabase.\n\n[1] - https://www.postgresql.org/docs/current/logical-replication-subscription.html\n\n-- \nWith Regards,\nAmit Kapila.\n\n\n",
"msg_date": "Fri, 15 Mar 2024 09:44:44 +0530",
"msg_from": "Amit Kapila <amit.kapila16@gmail.com>",
"msg_from_op": false,
"msg_subject": "Re: Add publisher and subscriber to glossary documentation."
},
{
"msg_contents": "On Fri, Mar 15, 2024, at 1:14 AM, Amit Kapila wrote:\n> I think node should mean instance for both physical and logical\n> replication, otherwise, it would be confusing. We need both the usages\n> as a particular publication/subscription is defined at the database\n> level but the server on which we define those is referred to as a\n> node/instance.\n\nIf you are creating a subscription that connects to the same instance\n(replication between 2 databases in the same cluster), your definition is not\ncorrect and Alvaro's definition is accurate. The node definition is closely\nlinked to the connection string. While the physical replication does not\nspecify a database (meaning \"any database\" referring to an instance), the\nlogical replication requires a database.\n\n\n--\nEuler Taveira\nEDB https://www.enterprisedb.com/\n\nOn Fri, Mar 15, 2024, at 1:14 AM, Amit Kapila wrote:I think node should mean instance for both physical and logicalreplication, otherwise, it would be confusing. We need both the usagesas a particular publication/subscription is defined at the databaselevel but the server on which we define those is referred to as anode/instance.If you are creating a subscription that connects to the same instance(replication between 2 databases in the same cluster), your definition is notcorrect and Alvaro's definition is accurate. The node definition is closelylinked to the connection string. While the physical replication does notspecify a database (meaning \"any database\" referring to an instance), thelogical replication requires a database.--Euler TaveiraEDB https://www.enterprisedb.com/",
"msg_date": "Fri, 15 Mar 2024 01:37:31 -0300",
"msg_from": "\"Euler Taveira\" <euler@eulerto.com>",
"msg_from_op": false,
"msg_subject": "Re: Add publisher and subscriber to glossary documentation."
}
] |
[
{
"msg_contents": "Hi All,\nalter table t1 add column c serial;\nALTER TABLE\n\nthis works, but not\n#alter table t1 add column c int;\nALTER TABLE\n#alter table t1 alter column c type serial;\nERROR: type \"serial\" does not exist\n\nLooking at the documentation [1], the grammar for both mentions data_type\n\nADD [ COLUMN ] [ IF NOT EXISTS ] column_name data_type and\n\nALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type\n\ndata_type is described on that page as \"Data type of the new column,\nor new data type for an existing column.\" but CREATE TABLE\ndocumentation [2] redirects data_type to [3], which mentions serial.\nThe impression created by the documentation is the second statement\nabove is a valid statement as should not throw an error; instead\nchange the data type of the column (and create required sequence).\n\nIn code ATPrepAlterColumnType() calls typenameTypeIdAndMod(), whereas\ntransformColumnDefinition() (called for ALTER TABLE ... ADD COLUMN and\nCREATE TABLE) handles \"serial\" data type separately. Looks like we are\nmissing a call to transformColumnDefinition() in\ntransformAlterTableStmt() under case AT_AlterColumnType.\n\n[1] https://www.postgresql.org/docs/current/sql-altertable.html\n[2] https://www.postgresql.org/docs/16/sql-createtable.html\n[3] https://www.postgresql.org/docs/16/datatype.html\n\n-- \nBest Wishes,\nAshutosh Bapat\n\n\n",
"msg_date": "Mon, 12 Feb 2024 19:20:28 +0530",
"msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>",
"msg_from_op": true,
"msg_subject": "serial not accepted as datatype in ALTER TABLE ... ALTER COLUMN"
},
{
"msg_contents": "Hi Ashutosh, \n\n> data_type is described on that page as \"Data type of the new column,\n> or new data type for an existing column.\" but CREATE TABLE\n> documentation [2] redirects data_type to [3], which mentions serial.\n> The impression created by the documentation is the second statement\n> above is a valid statement as should not throw an error; instead\n> change the data type of the column (and create required sequence).\n\nI didn't find out a reason to not support it, if have any reason, I\nthink it is better have some explaination in the document.\n\n> In code ATPrepAlterColumnType() calls typenameTypeIdAndMod(), whereas\n> transformColumnDefinition() (called for ALTER TABLE ... ADD COLUMN and\n> CREATE TABLE) handles \"serial\" data type separately. Looks like we are\n> missing a call to transformColumnDefinition() in\n> transformAlterTableStmt() under case AT_AlterColumnType.\n\nI tried your idea with the attatchment, it is still in a drafted state\nbut it can be used as a prove-of-concept and for better following\ncommunicating. Just one point needs to metion is serial implies\n\"default value\" + \"not null\" constaint. So when we modify a column into\nserial, we need to modify the 'NULL value' and only to the default value\nat the RewriteTable stage.\n\n-- \nBest Regards\nAndy Fan",
"msg_date": "Sun, 18 Feb 2024 16:19:04 +0800",
"msg_from": "Andy Fan <zhihuifan1213@163.com>",
"msg_from_op": false,
"msg_subject": "Re: serial not accepted as datatype in ALTER TABLE ... ALTER COLUMN"
},
{
"msg_contents": "On Sun, Feb 18, 2024 at 1:59 PM Andy Fan <zhihuifan1213@163.com> wrote:\n>\n>\n> Hi Ashutosh,\n>\n> > data_type is described on that page as \"Data type of the new column,\n> > or new data type for an existing column.\" but CREATE TABLE\n> > documentation [2] redirects data_type to [3], which mentions serial.\n> > The impression created by the documentation is the second statement\n> > above is a valid statement as should not throw an error; instead\n> > change the data type of the column (and create required sequence).\n>\n> I didn't find out a reason to not support it, if have any reason, I\n> think it is better have some explaination in the document.\n>\n> > In code ATPrepAlterColumnType() calls typenameTypeIdAndMod(), whereas\n> > transformColumnDefinition() (called for ALTER TABLE ... ADD COLUMN and\n> > CREATE TABLE) handles \"serial\" data type separately. Looks like we are\n> > missing a call to transformColumnDefinition() in\n> > transformAlterTableStmt() under case AT_AlterColumnType.\n>\n> I tried your idea with the attatchment, it is still in a drafted state\n> but it can be used as a prove-of-concept and for better following\n> communicating. Just one point needs to metion is serial implies\n> \"default value\" + \"not null\" constaint. So when we modify a column into\n> serial, we need to modify the 'NULL value' and only to the default value\n> at the RewriteTable stage.\n>\n\nI am surprised that this requires changes in ReWrite. I thought adding\nNOT NULL constraint and default value commands would be done by\ntransformColumnDefinition(). But I haven't looked at the patch close\nenough.\n\n-- \nBest Wishes,\nAshutosh Bapat\n\n\n",
"msg_date": "Mon, 19 Feb 2024 18:40:32 +0530",
"msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>",
"msg_from_op": true,
"msg_subject": "Re: serial not accepted as datatype in ALTER TABLE ... ALTER COLUMN"
},
{
"msg_contents": "\nAshutosh Bapat <ashutosh.bapat.oss@gmail.com> writes:\n\n> On Sun, Feb 18, 2024 at 1:59 PM Andy Fan <zhihuifan1213@163.com> wrote:\n>>\n>>\n>> I tried your idea with the attatchment, it is still in a drafted state\n>> but it can be used as a prove-of-concept and for better following\n>> communicating. Just one point needs to metion is serial implies\n>> \"default value\" + \"not null\" constaint. So when we modify a column into\n>> serial, we need to modify the 'NULL value' and only to the default value\n>> at the RewriteTable stage.\n>>\n>\n> I am surprised that this requires changes in ReWrite. I thought adding\n> NOT NULL constraint and default value commands would be done by\n> transformColumnDefinition(). But I haven't looked at the patch close\n> enough.\n\nHmm, I think this depends on how to handle the NULL values before the\nRewriteTable. \n\nConsider the example like this:\n\n\\pset null (null)\ncreate table t(a int);\ninsert into t select 1;\ninsert into t select;\n\npostgres=# select * from t;\n a \n--------\n 1\n (null)\n(2 rows)\n\nsince serial type implies \"not null\" + \"default value\", shall we raise error\nor fill the value with the \"default\" value? The patch choose the later\nway which needs changes in RewirteTable stage, but now I think the raise\nerror directly is an option as well. \n\n-- \nBest Regards\nAndy Fan\n\n\n\n",
"msg_date": "Tue, 20 Feb 2024 09:17:37 +0800",
"msg_from": "Andy Fan <zhihuifan1213@163.com>",
"msg_from_op": false,
"msg_subject": "Re: serial not accepted as datatype in ALTER TABLE ... ALTER COLUMN"
}
] |
[
{
"msg_contents": "Hi,\n\nI noticed that in the following code in BitmapPrefetch(), we use the\ncurrent block's TBMIterateResult->recheck when deciding whether or not\nto prefetch the block returned by tbm_iterate() (which is very likely\na different block). Why not use TBMIterateResult->recheck for the\nblock we are considering prefetching?\n\nI see a note that the skip fetch logic here depends on the assumption\nthat the index AM will report the same recheck flag for this future\nheap page as it did for the current heap page. But why would we depend\non that assumption instead of just using the TBMIterateResult just\npopulated by tbm_iterate() for the block we are about to prefetch?\nThat is the block we pass to PrefetchBuffer() afterward.\n\n /*\n * If we expect not to have to actually read this heap page,\n * skip this prefetch call, but continue to run the prefetch\n * logic normally. (Would it be better not to increment\n * prefetch_pages?)\n *\n * This depends on the assumption that the index AM will\n * report the same recheck flag for this future heap page as\n * it did for the current heap page; which is not a certainty\n * but is true in many cases.\n */\n skip_fetch = (node->can_skip_fetch &&\n (node->tbmres ? !node->tbmres->recheck : false) &&\n VM_ALL_VISIBLE(node->ss.ss_currentRelation,\n tbmpre->blockno,\n &node->pvmbuffer));\n\n if (!skip_fetch)\n PrefetchBuffer(scan->rs_rd, MAIN_FORKNUM, tbmpre->blockno);\n\n\n- Melanie\n\n\n",
"msg_date": "Mon, 12 Feb 2024 15:17:32 -0500",
"msg_from": "Melanie Plageman <melanieplageman@gmail.com>",
"msg_from_op": true,
"msg_subject": "Why does BitmapPrefetch() skip fetch based on current block recheck\n flag"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.