Therefore, I propose the attached patch, which simply sees to it that we discard any partial query result at the start of error message collection not the end. This makes the behavior very much better, at least on Linux.
I have tested the build of Postgres with attached patch and confirm that I don't see this problematic behavior anymore even with default allocator. Thank you!
I think this is a back-patchable bug fix; certainly so at least back to 9.6 where \errverbose was added. Versions before that do not show the persistent memory bloat the OP is complaining of, so that what we have here is arguably a performance regression. Comments?
This should not bring regression, since the memory is freed anyway, but is valuable as puts less pressure on client memory requirements for manual data inspection workflows.