Hi,
Here's the second chunk of patches reducing memory used by the planner.
The first part [1] was pretty straightforward, mostly releasing working
copies of lists in a bunch of functions. This patch is a bit more
invasive - the goal is to release memory used by Material/Memoize paths
that end up not being used.
match_unsorted_outer() creates a Memoize and Material paths for each
combination of outer/inner paths it considers, but most of the paths get
rejected in add_path(). But match_unsorted_outer() does not know that,
and it keeps the Memoize/Material paths allocated - those paths may also
contain long lists etc. Which also uses a lot of memory.
Each patch has a reproducer (but it's the same query, really), with an
EXISTS query. The query is a bit strange as it has a join in the EXISTS
clause. Again, it's intentionally extreme in order to demonstrate the
benefits, and because it partially aims to improve "worst case" queries
with increased join_collapse_limit (is sets it to 16).
The commit messages also include some basic numbers, illustrating the
impact of each patch - how much memory is saved, etc.
1) v1-0001-EXISTS-Free-unused-Material-and-Memoize-paths-in-.patch
----------
The goal is to free Material/Memoize paths in match_unsorted_outer, that
end up being unused used. To do this, we need to know whether
try_nestloop_path succeeded, and in turn whether add_path succeeded. So
the patch adjusts those functions, to provide that as return value.
2) v1-0002-EXISTS-Free-cache-key-lists-of-rejected-Memoize-p.patch
----------
This is a small improvement on top of (1), freeing not just the mpath,
but also the lists built for the mpath.
Evaluation
----------
Here's a brief evaluation, showing the impact of the two patches. The
numbers are memory usage in kB, per EXPLAIN (MEMORY), for the reproducer
(same for both patches):
master 0001 0002
-----------------------------------------
repro 264979 196008 159503
That's ~40% reduction, which is not bad for two small patches. It still
uses a lot of memory, of course, but the savings combine with the other
patches shared earlier, to save ~80% of memory. I have a couple more
experimental patches, but the benefits are diminishing and it may not be
worth it.
regards
[1]
https://www.postgresql.org/message-id/f3e94bfa-340c-4b51-9c63-1a5cb57aa27b%40vondra.me
--
Tomas Vondra
From b0060ac79e457f077940316c22ec2a1744ceae87 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Thu, 18 Jun 2026 18:12:16 +0200
Subject: [PATCH v1 1/2] EXISTS: Free unused Material and Memoize paths in
match_unsorted_outer
match_unsorted_outer() builds a MemoizePath for each combination of
outer path and parameterized inner path, and a MaterialPath for the
cheapest inner path, but most of the resulting nestloop paths are
rejected. Make add_path() and try_nestloop_path() return whether the
new path was accepted, and free the Memoize and Material paths not used
by any accepted path.
On a correlated semijoin against a 13-way join, planning memory goes
from 154309 kB to 87547 kB (-43%).
Reproducer: reproducers/08-nestloop-material-memoize-paths.sql
---
.../08-nestloop-material-memoize-paths.sql | 106 ++++++++++++++++++
src/backend/optimizer/path/joinpath.c | 54 +++++----
src/backend/optimizer/util/pathnode.c | 4 +-
src/include/optimizer/pathnode.h | 2 +-
4 files changed, 143 insertions(+), 23 deletions(-)
create mode 100644 reproducers/08-nestloop-material-memoize-paths.sql
diff --git a/reproducers/08-nestloop-material-memoize-paths.sql b/reproducers/08-nestloop-material-memoize-paths.sql
new file mode 100644
index 00000000000..0c46ae94139
--- /dev/null
+++ b/reproducers/08-nestloop-material-memoize-paths.sql
@@ -0,0 +1,106 @@
+-- Reproducer for commit "Free unused Material and Memoize paths in match_unsorted_outer"
+--
+-- match_unsorted_outer() creates a MemoizePath for each combination of outer
+-- path and parameterized inner path, and a MaterialPath for the cheapest
+-- inner path, but most of the nestloop paths using them are rejected by
+-- add_path(). The commit makes add_path() and try_nestloop_path() report
+-- whether the path was accepted, and frees the Memoize/Material paths that
+-- did not end up in any accepted path. The correlated semijoin produces
+-- many parameterized paths, and thus many Memoize paths.
+--
+-- Query: semijoin of a table against a 13-way join (14 relations),
+-- correlated with the outer query.
+--
+-- Run it on a build of the parent commit and of this commit, and compare
+-- the reported planning memory:
+--
+-- psql -X -f reproducers/08-nestloop-material-memoize-paths.sql
+--
+-- The tables are created in schema repro_08, which is dropped and
+-- recreated on each run. plan_md5 is a hash of the plan, to show the
+-- plan is the same on both builds.
+--
+-- Planning memory in kB, measured on builds without assertions
+-- (meson buildtype=debugoptimized):
+--
+-- used allocated
+-- parent commit 154309 155937
+-- this commit 87547 90401 (-43.3% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_08 CASCADE;
+CREATE SCHEMA repro_08;
+SET search_path = repro_08;
+
+-- Outer table a, and a semijoin against b joined to 12 dimension tables,
+-- correlated with the outer query on b.x = a.x. All tables have 1000 rows
+-- and an index on every column, so the semijoin's inner side gets
+-- parameterized join paths (parameterized by a) for every subset of
+-- relations containing b.
+CREATE TABLE a (x int, y int);
+INSERT INTO a SELECT g, g FROM generate_series(1, 1000) g;
+CREATE INDEX ON a (x);
+CREATE INDEX ON a (y);
+
+DO $$
+BEGIN
+ EXECUTE 'CREATE TABLE b (x int, ' ||
+ (SELECT string_agg(format('c%s int', i), ', ')
+ FROM generate_series(1, 12) i) || ')';
+ EXECUTE 'INSERT INTO b SELECT g, ' ||
+ (SELECT string_agg('g', ', ') FROM generate_series(1, 12) i) ||
+ ' FROM generate_series(1, 1000) g';
+ EXECUTE 'CREATE INDEX ON b (x)';
+
+ FOR i IN 1..12 LOOP
+ EXECUTE format('CREATE INDEX ON b (c%s)', i);
+ EXECUTE format('CREATE TABLE d%s (k int, v int)', i);
+ EXECUTE format('INSERT INTO d%s SELECT g, g FROM generate_series(1, 1000) g', i);
+ EXECUTE format('CREATE INDEX ON d%s (k)', i);
+ EXECUTE format('CREATE INDEX ON d%s (v)', i);
+ END LOOP;
+END
+$$;
+ANALYZE a, b, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12;
+
+SET join_collapse_limit = 16;
+SET from_collapse_limit = 16;
+SET geqo = off;
+
+-- Plan the query and return the planning memory reported by EXPLAIN (MEMORY),
+-- along with a hash of the plan (to check the plan did not change).
+CREATE FUNCTION pg_temp.planning_memory(query text,
+ OUT memory_used_kb bigint,
+ OUT memory_allocated_kb bigint,
+ OUT plan_md5 text)
+LANGUAGE plpgsql AS $fn$
+DECLARE
+ plan json;
+BEGIN
+ EXECUTE 'EXPLAIN (MEMORY, COSTS OFF, FORMAT JSON) ' || query INTO plan;
+ memory_used_kb := (plan->0->'Planning'->>'Memory Used')::bigint;
+ memory_allocated_kb := (plan->0->'Planning'->>'Memory Allocated')::bigint;
+ plan_md5 := md5((plan->0->'Plan')::text);
+END
+$fn$;
+
+SELECT * FROM pg_temp.planning_memory($q$
+SELECT *
+ FROM a
+ WHERE EXISTS (SELECT 1
+ FROM b
+ JOIN d1 ON b.c1 = d1.k
+ JOIN d2 ON b.c2 = d2.k
+ JOIN d3 ON b.c3 = d3.k
+ JOIN d4 ON b.c4 = d4.k
+ JOIN d5 ON b.c5 = d5.k
+ JOIN d6 ON b.c6 = d6.k
+ JOIN d7 ON b.c7 = d7.k
+ JOIN d8 ON b.c8 = d8.k
+ JOIN d9 ON b.c9 = d9.k
+ JOIN d10 ON b.c10 = d10.k
+ JOIN d11 ON b.c11 = d11.k
+ JOIN d12 ON b.c12 = d12.k
+ WHERE b.x = a.x)
+$q$);
diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c
index beb2856dd21..3ae80ced59e 100644
--- a/src/backend/optimizer/path/joinpath.c
+++ b/src/backend/optimizer/path/joinpath.c
@@ -1026,7 +1026,7 @@ get_memoize_path(PlannerInfo *root, RelOptInfo *innerrel,
* Consider a nestloop join path; if it appears useful, push it into
* the joinrel's pathlist via add_path().
*/
-static void
+static bool
try_nestloop_path(PlannerInfo *root,
RelOptInfo *joinrel,
Path *outer_path,
@@ -1056,7 +1056,7 @@ try_nestloop_path(PlannerInfo *root,
*/
if (bms_overlap(extra->ojrelids, inner_paramrels) ||
bms_overlap(extra->ojrelids, outer_paramrels))
- return;
+ return false;
/*
* Any parameterization of the input paths refers to topmost parents of
@@ -1088,7 +1088,7 @@ try_nestloop_path(PlannerInfo *root,
{
/* Waste no memory when we reject a path here */
bms_free(required_outer);
- return;
+ return false;
}
/* If we got past that, we shouldn't have any unsafe outer-join refs */
@@ -1105,7 +1105,7 @@ try_nestloop_path(PlannerInfo *root,
!path_is_reparameterizable_by_child(inner_path, outer_path->parent))
{
bms_free(required_outer);
- return;
+ return false;
}
/*
@@ -1125,8 +1125,8 @@ try_nestloop_path(PlannerInfo *root,
workspace.startup_cost, workspace.total_cost,
pathkeys, required_outer))
{
- add_path(joinrel, (Path *)
- create_nestloop_path(root,
+ return add_path(joinrel, (Path *)
+ create_nestloop_path(root,
joinrel,
jointype,
&workspace,
@@ -1142,6 +1142,8 @@ try_nestloop_path(PlannerInfo *root,
/* Waste no memory when we reject a path here */
bms_free(required_outer);
}
+
+ return false;
}
/*
@@ -2000,6 +2002,7 @@ match_unsorted_outer(PlannerInfo *root,
bool useallclauses;
Path *inner_cheapest_total = innerrel->cheapest_total_path;
Path *matpath = NULL;
+ bool matused = false;
ListCell *lc1;
/*
@@ -2129,26 +2132,32 @@ match_unsorted_outer(PlannerInfo *root,
innerpath, outerpath, jointype,
extra);
if (mpath != NULL)
- try_nestloop_path(root,
+ {
+ if (!try_nestloop_path(root,
+ joinrel,
+ outerpath,
+ mpath,
+ merge_pathkeys,
+ jointype,
+ PGS_NESTLOOP_MEMOIZE,
+ extra))
+ pfree(mpath);
+ }
+ }
+
+ /* Also consider materialized form of the cheapest inner path */
+ if (matpath != NULL)
+ {
+ if (try_nestloop_path(root,
joinrel,
outerpath,
- mpath,
+ matpath,
merge_pathkeys,
jointype,
- PGS_NESTLOOP_MEMOIZE,
- extra);
+ PGS_NESTLOOP_MATERIALIZE,
+ extra))
+ matused = true;
}
-
- /* Also consider materialized form of the cheapest inner path */
- if (matpath != NULL)
- try_nestloop_path(root,
- joinrel,
- outerpath,
- matpath,
- merge_pathkeys,
- jointype,
- PGS_NESTLOOP_MATERIALIZE,
- extra);
}
/* Can't do anything else if inner rel is parameterized by outer */
@@ -2162,6 +2171,9 @@ match_unsorted_outer(PlannerInfo *root,
false);
}
+ if ((matpath != NULL) && !matused)
+ pfree(matpath);
+
/*
* Consider partial nestloop and mergejoin plan if outerrel has any
* partial path and the joinrel is parallel-safe. However, we can't
diff --git a/src/backend/optimizer/util/pathnode.c b/src/backend/optimizer/util/pathnode.c
index 5f28174a5fa..a4c7a116971 100644
--- a/src/backend/optimizer/util/pathnode.c
+++ b/src/backend/optimizer/util/pathnode.c
@@ -465,7 +465,7 @@ set_cheapest(RelOptInfo *parent_rel)
*
* Returns nothing, but modifies parent_rel->pathlist.
*/
-void
+bool
add_path(RelOptInfo *parent_rel, Path *new_path)
{
bool accept_new = true; /* unless we find a superior old path */
@@ -672,6 +672,8 @@ add_path(RelOptInfo *parent_rel, Path *new_path)
new_path->parent == parent_rel)
pfree(new_path);
}
+
+ return accept_new;
}
/*
diff --git a/src/include/optimizer/pathnode.h b/src/include/optimizer/pathnode.h
index e74a95d0d22..398b10c8d64 100644
--- a/src/include/optimizer/pathnode.h
+++ b/src/include/optimizer/pathnode.h
@@ -55,7 +55,7 @@ extern int compare_path_costs(Path *path1, Path *path2,
extern int compare_fractional_path_costs(Path *path1, Path *path2,
double fraction);
extern void set_cheapest(RelOptInfo *parent_rel);
-extern void add_path(RelOptInfo *parent_rel, Path *new_path);
+extern bool add_path(RelOptInfo *parent_rel, Path *new_path);
extern bool add_path_precheck(RelOptInfo *parent_rel, int disabled_nodes,
Cost startup_cost, Cost total_cost,
List *pathkeys, Relids required_outer);
--
2.56.1
From 50f4155eff0215cf177da7db2eaec4dfe26bc464 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Tue, 10 Nov 2026 11:31:36 -0500
Subject: [PATCH v1 2/2] EXISTS: Free cache key lists of rejected Memoize paths
match_unsorted_outer() frees a MemoizePath when the nestloop path using
it is rejected, but not the param_exprs and hash_operators lists that
paraminfo_get_equal_hashops() built for it. Free those too.
On a correlated semijoin against a 13-way join, planning memory goes
from 84572 kB to 51717 kB (-38.8%).
Reproducer: reproducers/14-memoize-cache-key-lists.sql
---
reproducers/14-memoize-cache-key-lists.sql | 104 +++++++++++++++++++++
src/backend/optimizer/path/joinpath.c | 5 +
2 files changed, 109 insertions(+)
create mode 100644 reproducers/14-memoize-cache-key-lists.sql
diff --git a/reproducers/14-memoize-cache-key-lists.sql b/reproducers/14-memoize-cache-key-lists.sql
new file mode 100644
index 00000000000..1407e1baec0
--- /dev/null
+++ b/reproducers/14-memoize-cache-key-lists.sql
@@ -0,0 +1,104 @@
+-- Reproducer for commit "Free cache key lists of rejected Memoize paths"
+--
+-- match_unsorted_outer() builds a MemoizePath for each combination of outer
+-- path and parameterized inner path, and frees it when the nestloop path
+-- using it is rejected. But the cache key lists (param_exprs and
+-- hash_operators), built by paraminfo_get_equal_hashops() for that path
+-- alone, were not freed. The commit frees them along with the path.
+--
+-- Query: semijoin of a table against a 13-way join (14 relations),
+-- correlated with the outer query.
+--
+-- Run it on a build of the parent commit and of this commit, and compare
+-- the reported planning memory:
+--
+-- psql -X -f reproducers/14-memoize-cache-key-lists.sql
+--
+-- The tables are created in schema repro_14, which is dropped and
+-- recreated on each run. plan_md5 is a hash of the plan, to show the
+-- plan is the same on both builds.
+--
+-- Planning memory in kB, measured on builds without assertions
+-- (meson buildtype=debugoptimized):
+--
+-- used allocated
+-- parent commit 84572 90401
+-- this commit 51717 57633 (-38.8% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_14 CASCADE;
+CREATE SCHEMA repro_14;
+SET search_path = repro_14;
+
+-- Outer table a, and a semijoin against b joined to 12 dimension tables,
+-- correlated with the outer query on b.x = a.x. All tables have 1000 rows
+-- and an index on every column, so the semijoin's inner side gets
+-- parameterized join paths (parameterized by a) for every subset of
+-- relations containing b.
+CREATE TABLE a (x int, y int);
+INSERT INTO a SELECT g, g FROM generate_series(1, 1000) g;
+CREATE INDEX ON a (x);
+CREATE INDEX ON a (y);
+
+DO $$
+BEGIN
+ EXECUTE 'CREATE TABLE b (x int, ' ||
+ (SELECT string_agg(format('c%s int', i), ', ')
+ FROM generate_series(1, 12) i) || ')';
+ EXECUTE 'INSERT INTO b SELECT g, ' ||
+ (SELECT string_agg('g', ', ') FROM generate_series(1, 12) i) ||
+ ' FROM generate_series(1, 1000) g';
+ EXECUTE 'CREATE INDEX ON b (x)';
+
+ FOR i IN 1..12 LOOP
+ EXECUTE format('CREATE INDEX ON b (c%s)', i);
+ EXECUTE format('CREATE TABLE d%s (k int, v int)', i);
+ EXECUTE format('INSERT INTO d%s SELECT g, g FROM generate_series(1, 1000) g', i);
+ EXECUTE format('CREATE INDEX ON d%s (k)', i);
+ EXECUTE format('CREATE INDEX ON d%s (v)', i);
+ END LOOP;
+END
+$$;
+ANALYZE a, b, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12;
+
+SET join_collapse_limit = 16;
+SET from_collapse_limit = 16;
+SET geqo = off;
+
+-- Plan the query and return the planning memory reported by EXPLAIN (MEMORY),
+-- along with a hash of the plan (to check the plan did not change).
+CREATE FUNCTION pg_temp.planning_memory(query text,
+ OUT memory_used_kb bigint,
+ OUT memory_allocated_kb bigint,
+ OUT plan_md5 text)
+LANGUAGE plpgsql AS $fn$
+DECLARE
+ plan json;
+BEGIN
+ EXECUTE 'EXPLAIN (MEMORY, COSTS OFF, FORMAT JSON) ' || query INTO plan;
+ memory_used_kb := (plan->0->'Planning'->>'Memory Used')::bigint;
+ memory_allocated_kb := (plan->0->'Planning'->>'Memory Allocated')::bigint;
+ plan_md5 := md5((plan->0->'Plan')::text);
+END
+$fn$;
+
+SELECT * FROM pg_temp.planning_memory($q$
+SELECT *
+ FROM a
+ WHERE EXISTS (SELECT 1
+ FROM b
+ JOIN d1 ON b.c1 = d1.k
+ JOIN d2 ON b.c2 = d2.k
+ JOIN d3 ON b.c3 = d3.k
+ JOIN d4 ON b.c4 = d4.k
+ JOIN d5 ON b.c5 = d5.k
+ JOIN d6 ON b.c6 = d6.k
+ JOIN d7 ON b.c7 = d7.k
+ JOIN d8 ON b.c8 = d8.k
+ JOIN d9 ON b.c9 = d9.k
+ JOIN d10 ON b.c10 = d10.k
+ JOIN d11 ON b.c11 = d11.k
+ JOIN d12 ON b.c12 = d12.k
+ WHERE b.x = a.x)
+$q$);
diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c
index 3ae80ced59e..41423b71745 100644
--- a/src/backend/optimizer/path/joinpath.c
+++ b/src/backend/optimizer/path/joinpath.c
@@ -2141,7 +2141,12 @@ match_unsorted_outer(PlannerInfo *root,
jointype,
PGS_NESTLOOP_MEMOIZE,
extra))
+ {
+ /* The cache key lists were built just for this path */
+ list_free(((MemoizePath *) mpath)->param_exprs);
+ list_free(((MemoizePath *) mpath)->hash_operators);
pfree(mpath);
+ }
}
}
--
2.56.1