Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mtXhu-0004s7-Ks for pgsql-general@arkaria.postgresql.org; Sat, 04 Dec 2021 16:16:14 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1mtXhs-0005Hl-Ph for pgsql-general@arkaria.postgresql.org; Sat, 04 Dec 2021 16:16:12 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mtXhs-0005Hb-EF for pgsql-general@lists.postgresql.org; Sat, 04 Dec 2021 16:16:12 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mtXhn-0003O5-AX for pgsql-general@lists.postgresql.org; Sat, 04 Dec 2021 16:16:11 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 1B4GG5G72643579; Sat, 4 Dec 2021 11:16:05 -0500 From: Tom Lane To: Matt Magoffin cc: pgsql-general@lists.postgresql.org Subject: Re: Handling memory contexts in aggregate function invoking other built-in aggregate functions In-reply-to: References: Comments: In-reply-to Matt Magoffin message dated "Sat, 04 Dec 2021 18:14:46 +1300" MIME-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-ID: <2643577.1638634565.1@sss.pgh.pa.us> Content-Transfer-Encoding: quoted-printable Date: Sat, 04 Dec 2021 11:16:05 -0500 Message-ID: <2643578.1638634565@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Matt Magoffin writes: > So far, I have been working on average support via the vec_to_mean() agg= regate, and my aggregate's [2] transition function sets up a FunctionCallI= nfo for the numeric_avg_accum() [3] function and then loops over the input= array elements, calling numeric_avg_accum() and saving its result state o= bject in my aggregate=E2=80=99s state. Before looping, I switch the memory= context to the aggregate=E2=80=99s context, i.e. there is stuff like > MemoryContext aggContext; > AggCheckCallContext(fcinfo, &aggContext); > old =3D MemoryContextSwitchTo(aggContext); > for (i =3D 0; i < arrayLength; i++) { > // invoke numeric_avg_accum() for each array element, store result in = my state > } > MemoryContextSwitchTo(old); Calling numeric_avg_accum in the agg_context is unnecessary, and possibly counterproductive (it might leak memory in that context, since like all other aggregates it assumes it's called in a short-lived context). That doesn't seem to explain your crash though. Are you testing in an --enable-cassert build? If not, do that; it might make the cause of the crashes more apparent, thanks to CLOBBER_FREED_MEMORY and other debug support. regards, tom lane