Assert failure in find_var_for_subquery_tle

Started by Richard Guoabout 2 months ago3 messageshackers
Jump to latest
#1Richard Guo
guofenglinux@gmail.com

The following query, run in the regression database, trips an Assert:

select ss.v from int8_tbl x,
lateral (select x.q1 from (select distinct q2 from int8_tbl) s
union all
select q2 from int8_tbl) ss(v);

TRAP: failed Assert("var->varno == rel->relid"), File: "pathkeys.c"

In set_append_rel_size(), we have this comment:

* NB: the resulting childrel->reltarget->exprs may contain arbitrary
* expressions, which otherwise would not occur in a rel's targetlist.
* Code that might be looking at an appendrel child must cope with
* such. (Normally, a rel's targetlist would only include Vars and
* PlaceHolderVars.)

Apparently find_var_for_subquery_tle() did not get this memo, and
assumes that every Var in a subquery rel's targetlist belongs to that
rel.

To fix, I think we can just ignore Vars that do not belong to the
subquery rel. Such a Var cannot be a reference to the subquery's
output, so it should never be treated as a match.

Any thoughts?

- Richard

Attachments:

t254104_1
v1-0001-Fix-bogus-Assert-in-find_var_for_subquery_tle.patchapplication/octet-stream; name=v1-0001-Fix-bogus-Assert-in-find_var_for_subquery_tle.patchDownload+35-3
#2shihao zhong
zhong950419@gmail.com
In reply to: Richard Guo (#1)
Re: Assert failure in find_var_for_subquery_tle

Hi Richard,

The fix looks right to me. The new test trips the Assert without the
pathkeys.c change.

A CTE scan as the member hits the same Assert, example:

set_cte_pathlist().
explain (costs off)
with c as materialized (select q2 from int8_tbl order by q2)
select ss.v from int8_tbl x,
lateral (select x.q1 from c union all
select q2 from int8_tbl) ss(v);

The patch fixes this one too. Maybe the commit message could mention
it as well.

Thanks,
Shihao

#3Richard Guo
guofenglinux@gmail.com
In reply to: Richard Guo (#1)
Re: Assert failure in find_var_for_subquery_tle

On Thu, Oct 8, 2026 at 4:42 PM Richard Guo <guofenglinux@gmail.com> wrote:

To fix, I think we can just ignore Vars that do not belong to the
subquery rel. Such a Var cannot be a reference to the subquery's
output, so it should never be treated as a match.

Pushed and back-patched to all supported branches.

- Richard