From 9fc7160fa0bf299e5a5d4c255d39c98344ab81d4 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Tue, 10 Nov 2026 12:04:36 -0500
Subject: [PATCH v1 09/10] ECCHAIN: Free outerkeys and merge_pathkeys in
 sort_inner_and_outer

sort_inner_and_outer() freed the outer sort keys only when the list was
not also used as the join's output pathkeys, and it never freed the
output pathkeys.  But create_mergejoin_path() copies all the lists it is
given, so neither list is referenced by the new path.  build_join_pathkeys()
returns the outer sort keys unchanged when all of them are useful for the
join rel, which is the case whenever the merge key is shared with
relations outside the join, e.g. when many tables are joined on the same
column.  So the list was leaked for most join pairs of such queries.

Free the output pathkeys when they are a separate list, and always free
the outer sort keys.

When joining 10 tables on the same column, planning memory goes from
8558 kB to 4621 kB (-46%).

Reproducer: reproducers/27-free-sort-inner-outer-keys.sql
---
 reproducers/27-free-sort-inner-outer-keys.sql | 81 +++++++++++++++++++
 src/backend/optimizer/path/joinpath.c         |  6 +-
 2 files changed, 85 insertions(+), 2 deletions(-)
 create mode 100644 reproducers/27-free-sort-inner-outer-keys.sql

diff --git a/reproducers/27-free-sort-inner-outer-keys.sql b/reproducers/27-free-sort-inner-outer-keys.sql
new file mode 100644
index 00000000000..387839a00c8
--- /dev/null
+++ b/reproducers/27-free-sort-inner-outer-keys.sql
@@ -0,0 +1,81 @@
+-- Reproducer for commit "Free outerkeys and merge_pathkeys in sort_inner_and_outer"
+--
+-- sort_inner_and_outer() freed the outer sort keys only when the list was
+-- not also used as the join's output pathkeys, and never freed the output
+-- pathkeys.  But create_mergejoin_path() copies all the lists it gets, so
+-- neither list is referenced by the path.  build_join_pathkeys() returns
+-- the outer sort keys unchanged when they are all useful for the join rel,
+-- which is the case whenever the merge key is shared with relations
+-- outside the join, e.g. when many tables are joined on the same column.
+--
+-- Query: 10 tables joined on the same column, so all the join clauses
+-- belong to a single equivalence class.
+--
+-- Run it on a build of the parent commit and of this commit, and compare
+-- the reported planning memory:
+--
+--   psql -X -f reproducers/27-free-sort-inner-outer-keys.sql
+--
+-- The tables are created in schema repro_27, 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    8558      16448
+--   this commit      4621       8256   (-46.0% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_27 CASCADE;
+CREATE SCHEMA repro_27;
+SET search_path = repro_27;
+
+-- Ten tables t1 .. t10 (1000 rows each), with an index on column a.
+DO $$
+BEGIN
+    FOR i IN 1..10 LOOP
+        EXECUTE format('CREATE TABLE t%s (a int, b int)', i);
+        EXECUTE format('INSERT INTO t%s SELECT g, g FROM generate_series(1, 1000) g', i);
+        EXECUTE format('CREATE INDEX ON t%s (a)', i);
+    END LOOP;
+END
+$$;
+ANALYZE t1, t2, t3, t4, t5, t6, t7, t8, t9, t10;
+
+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 t1
+  JOIN t2 ON t1.a = t2.a
+  JOIN t3 ON t2.a = t3.a
+  JOIN t4 ON t3.a = t4.a
+  JOIN t5 ON t4.a = t5.a
+  JOIN t6 ON t5.a = t6.a
+  JOIN t7 ON t6.a = t7.a
+  JOIN t8 ON t7.a = t8.a
+  JOIN t9 ON t8.a = t9.a
+  JOIN t10 ON t9.a = t10.a
+$q$);
diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c
index 5a4c7587eb1..0b610beb475 100644
--- a/src/backend/optimizer/path/joinpath.c
+++ b/src/backend/optimizer/path/joinpath.c
@@ -1737,8 +1737,10 @@ sort_inner_and_outer(PlannerInfo *root,
 		list_free(cur_mergeclauses);
 		list_free(innerkeys);
 
-		if ((outerkeys != merge_pathkeys) && (innerkeys != merge_pathkeys))
-			list_free(outerkeys);
+		/* build_join_pathkeys() may have returned outerkeys itself */
+		if (merge_pathkeys != outerkeys)
+			list_free(merge_pathkeys);
+		list_free(outerkeys);
 	}
 
 	list_free(all_pathkeys);
-- 
2.56.1

