The difference between plans in (2) and (3) is interesting, because it seems the CTE got inlined, so why was the refcount not decremented?
The query is not actually referencing the cte. So the cte range table entry would not appear anywhere in the query tree. That's why refcount is not decremented after inline cte walker.
If we explicitly reference the cte in the query, say in the targetlist, it would then work.
# explain (costs off) SELECT * FROM results_agg ORDER BY 1; QUERY PLAN --------------------------------------- Sort Sort Key: r.run -> HashAggregate Group Key: r.run -> Seq Scan on results r SubPlan 1 -> Seq Scan on results Filter: (run = r.run) (8 rows)
IMO the culprit is that we incorrectly set cterefcount to one while actually the cte is not referenced at all.