Subject: GRAPH_TABLE: lateral reference with label disjunction fails with "plan should not reference subplan's variable"

From: Ewan Young <[email-masked]>
Date: Thu, 4 Jun 2026 16:28:13 +0800

Hi hackers,

While testing with master I ran into an internal error in the
SQL/PGQ code (commit 2f094e7ac69).  A lateral reference into a
GRAPH_TABLE clause whose graph pattern contains a label disjunction
resolving to more than one element table fails at plan time:

    CREATE TABLE v1 (id int);
    CREATE TABLE v2 (id int);
    CREATE TABLE x (a int);
    CREATE PROPERTY GRAPH g
      VERTEX TABLES (v1 KEY (id) LABEL l1, v2 KEY (id) LABEL l2);

    SELECT 1 FROM x,
      GRAPH_TABLE (g MATCH (s IS l1|l2 WHERE s.id = x.a) COLUMNS (s.id));
    ERROR:  plan should not reference subplan's variable

The same pattern with a single label works fine, as does a label
disjunction without the lateral reference.  Reproduces on any build of
master and 19beta1; the equivalent hand-written query (LATERAL over a
UNION ALL) plans fine.

The cause is in rewriteGraphTable.c.  replace_property_refs_mutator()
increments varlevelsup of lateral references by one, assuming the path
query will directly become the GRAPH_TABLE's subquery.  That holds for
a single path query, but when the disjunction produces several path
queries, generate_union_from_pathqueries() wraps them in subquery RTEs
of a new UNION query, one level deeper, and nothing compensates for
that.  The planner then attributes the parameters to the wrong query
level, which finalize_plan() detects.

The attached patch increments the level of outer references in each
path query once more at the point where they are wrapped in the UNION
query, using IncrementVarSublevelsUp().  With the fix, the query above
returns the same results as the hand-written UNION ALL equivalent.

make check passes with the patch applied.

Regards,
Ewan Young

---

From: Ashutosh Bapat <[email-masked]>
Date: Thu, 4 Jun 2026 15:25:05 +0530

Hi Ewan,
Thanks for trying out SQL/PGQ and the report.

> make check passes with the patch applied.

This bug is the same as the one being discussed in [1]. Let's continue
the discussion there.

[1] http://postgr.es/m/[email-masked]

-- 
Best Wishes,
Ashutosh Bapat