Repository: edgedb/edgedb

Issue:
ISE on introspection query
<!-- Please search existing issues to avoid creating duplicates. -->
- EdgeDB Version: beta-1
- OS Version: macOS Big Sur

Steps to Reproduce:

```
with module schema 
 select Type { 
   id, 
   name, 
   from_casts := .<from_type[IS Cast] { allow_implicit } 
 };
```
 
Result: 

```
ERROR: InternalServerError: cannot find 'a8aaa4d4-ce3b-11eb-b9f7-85bc9f63d0a6' in <pg.RangeSubselect alias=q~6 at 0x7ff0e011b130> output
  Hint: This is most likely a bug in EdgeDB. Please consider opening an issue ticket at https://github.com/edgedb/edgedb/issues/new?template=bug_report.md
  Server traceback:
      Traceback (most recent call last):
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/__init__.py", line 94, in compile_ir_to_sql_tree
          qtree = dispatch.compile(ir_expr, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/functools.py", line 877, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/expr.py", line 60, in compile_Set
          _compile_set_impl(ir_set, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/expr.py", line 114, in _compile_set_impl
          _compile_set(ir_set, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/expr.py", line 589, in _compile_set
          relgen.get_set_rvar(ir_set, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relgen.py", line 136, in get_set_rvar
          return _process_toplevel_query(ir_set, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relgen.py", line 243, in _process_toplevel_query
          rvars = _get_set_rvar(ir_set, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relgen.py", line 277, in _get_set_rvar
          rvars = process_set_as_subquery(ir_set, stmt, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relgen.py", line 1218, in process_set_as_subquery
          dispatch.visit(ir_set.expr, ctx=newctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/functools.py", line 877, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/dispatch.py", line 44, in visit
          compile(ir, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/functools.py", line 877, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/stmt.py", line 95, in compile_SelectStmt
          outvar = clauses.compile_output(stmt.result, ctx=ictx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/clauses.py", line 174, in compile_output
          dispatch.visit(ir_set, ctx=newctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/functools.py", line 877, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/expr.py", line 85, in visit_Set
          _compile_set_impl(ir_set, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/expr.py", line 114, in _compile_set_impl
          _compile_set(ir_set, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/expr.py", line 593, in _compile_set
          _compile_shape(ir_set, ir_set.shape, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/expr.py", line 612, in _compile_shape
          result = shapecomp.compile_shape(ir_set, shape, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/shapecomp.py", line 79, in compile_shape
          wrapper = relgen.set_as_subquery(
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relgen.py", line 422, in set_as_subquery
          dispatch.visit(ir_set, ctx=subctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/functools.py", line 877, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/expr.py", line 85, in visit_Set
          _compile_set_impl(ir_set, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/expr.py", line 110, in _compile_set_impl
          _compile_set(ir_set, ctx=scopectx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/expr.py", line 589, in _compile_set
          relgen.get_set_rvar(ir_set, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relgen.py", line 189, in get_set_rvar
          rvars = _get_set_rvar(ir_set, ctx=subctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relgen.py", line 277, in _get_set_rvar
          rvars = process_set_as_subquery(ir_set, stmt, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relgen.py", line 1218, in process_set_as_subquery
          dispatch.visit(ir_set.expr, ctx=newctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/functools.py", line 877, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/dispatch.py", line 44, in visit
          compile(ir, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/functools.py", line 877, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/stmt.py", line 95, in compile_SelectStmt
          outvar = clauses.compile_output(stmt.result, ctx=ictx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/clauses.py", line 174, in compile_output
          dispatch.visit(ir_set, ctx=newctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/functools.py", line 877, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/expr.py", line 85, in visit_Set
          _compile_set_impl(ir_set, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/expr.py", line 114, in _compile_set_impl
          _compile_set(ir_set, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/expr.py", line 589, in _compile_set
          relgen.get_set_rvar(ir_set, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relgen.py", line 189, in get_set_rvar
          rvars = _get_set_rvar(ir_set, ctx=subctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relgen.py", line 371, in _get_set_rvar
          rvars = process_set_as_path(ir_set, stmt, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relgen.py", line 945, in process_set_as_path
          return process_set_as_path_type_intersection(
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relgen.py", line 854, in process_set_as_path_type_intersection
          source_rvar = get_set_rvar(ir_source, ctx=subctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relgen.py", line 198, in get_set_rvar
          result_rvar = _include_rvars(rvars, scope_stmt=scope_stmt, ctx=subctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relgen.py", line 224, in _include_rvars
          relctx.include_specific_rvar(
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relctx.py", line 219, in include_specific_rvar
          rel_join(stmt, rvar, ctx=ctx)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/relctx.py", line 763, in rel_join
          rref = pathctx.get_rvar_path_identity_var(
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/pathctx.py", line 561, in get_rvar_path_identity_var
          return get_rvar_path_var(rvar, path_id, aspect='identity', env=env)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/pathctx.py", line 549, in get_rvar_path_var
          return astutils.get_rvar_var(rvar, outvar)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/astutils.py", line 333, in get_rvar_var
          fieldref = get_column(rvar, var)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/astutils.py", line 279, in get_column
          col_idx = find_column_in_subselect_rvar(rvar, colname)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/astutils.py", line 255, in find_column_in_subselect_rvar
          raise RuntimeError(f'cannot find {name!r} in {rvar} output')
      RuntimeError: cannot find 'a8aaa4d4-ce3b-11eb-b9f7-85bc9f63d0a6' in <pg.RangeSubselect alias=q~6 at 0x7ff0e011b130> output
      
      The above exception was the direct cause of the following exception:
      
      Traceback (most recent call last):
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/server/compiler_pool/worker.py", line 311, in worker
          res = meth(*args)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/server/compiler_pool/worker.py", line 180, in compile
          units, cstate = COMPILER.compile(
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/server/compiler/compiler.py", line 2005, in compile
          units = self._compile(ctx=ctx, source=source)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/server/compiler/compiler.py", line 1584, in _compile
          return self._try_compile(ctx=ctx, source=source)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/server/compiler/compiler.py", line 1637, in _try_compile
          comp, capabilities = self._compile_dispatch_ql(ctx, stmt)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/server/compiler/compiler.py", line 1558, in _compile_dispatch_ql
          query = self._compile_ql_query(ctx, ql)
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/server/compiler/compiler.py", line 597, in _compile_ql_query
          sql_text, argmap = pg_compiler.compile_ir_to_sql(
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/__init__.py", line 116, in compile_ir_to_sql
          qtree = compile_ir_to_sql_tree(
        File "/Library/Frameworks/EdgeDB.framework/Versions/1-beta3-dev202105190000/lib/edgedb-server-1-beta3-dev202105190000/lib/python3.9/site-packages/edb/pgsql/compiler/__init__.py", line 101, in compile_ir_to_sql_tree
          raise errors.InternalServerError(*args) from e
      edb.errors.InternalServerError: cannot find 'a8aaa4d4-ce3b-11eb-b9f7-85bc9f63d0a6' in <pg.RangeSubselect alias=q~6 at 0x7ff0e011b130> output
```




Discussion:

Resolving patch:
diff --git a/edb/ir/ast.py b/edb/ir/ast.py
--- a/edb/ir/ast.py
+++ b/edb/ir/ast.py
@@ -179,7 +179,7 @@ class BasePointerRef(ImmutableBase):
     __abstract_node__ = True
 
     # Hide children to reduce noise
-    __ast_hidden__ = {'children'}
+    __ast_hidden__ = {'children', 'outbound_ptr'}
 
     # cardinality fields need to be mutable for lazy cardinality inference.
     # and children because we update pointers with newly derived children
@@ -212,6 +212,11 @@ class BasePointerRef(ImmutableBase):
     # Outbound cardinality of the pointer.
     out_cardinality: qltypes.Cardinality
 
+    # For inbound pointers, a pointer to the corresponding outbound pointer.
+    # I think it might be better to drop direction from PointerRef and track it
+    # externally?
+    outbound_ptr: typing.Optional[BasePointerRef] = None
+
     @property
     def dir_target(self) -> TypeRef:
         if self.direction is s_pointers.PointerDirection.Outbound:
diff --git a/edb/ir/typeutils.py b/edb/ir/typeutils.py
--- a/edb/ir/typeutils.py
+++ b/edb/ir/typeutils.py
@@ -636,6 +636,13 @@ def ptrref_from_ptrcls(  # NoQA: F811
     else:
         children = frozenset()
 
+    if direction == s_pointers.PointerDirection.Outbound:
+        outbound_ptr = None
+    else:
+        outbound_ptr = ptrref_from_ptrcls(
+            schema=schema, ptrcls=ptrcls, cache=cache,
+            typeref_cache=typeref_cache)
+
     kwargs.update(dict(
         out_source=out_source,
         out_target=out_target,
@@ -656,6 +663,7 @@ def ptrref_from_ptrcls(  # NoQA: F811
         has_properties=ptrcls.has_user_defined_properties(schema),
         dir_cardinality=dir_cardinality,
         out_cardinality=out_cardinality,
+        outbound_ptr=outbound_ptr,
     ))
 
     ptrref = ircls(**kwargs)
diff --git a/edb/pgsql/compiler/relctx.py b/edb/pgsql/compiler/relctx.py
--- a/edb/pgsql/compiler/relctx.py
+++ b/edb/pgsql/compiler/relctx.py
@@ -427,6 +427,8 @@ def new_primitive_rvar(
         ptr_ref_map: Dict[uuid.UUID, irast.BasePointerRef] = {}
         p: irast.BasePointerRef
 
+        # TODO: It should I think be possible to replace all of this
+        # ptr_ref_map logic with a generalized find_actual_ptrref.
         rptrref = ir_set.rptr.ptrref
         if isinstance(rptrref, irast.TypeIntersectionPointerRef):
             if rptrref.rptr_specialization:
@@ -458,73 +460,29 @@ def new_primitive_rvar(
             rptrref = narrow_rptrref
 
         ptr_info = pg_types.get_ptrref_storage_info(
-            rptrref, resolve_type=False, link_bias=False)
+            rptrref, resolve_type=False, link_bias=False, allow_missing=True)
 
-        if ptr_info.table_type == 'ObjectType' and rptrref.is_inbound:
+        # If the set comes from an backlink, and the link is stored inline,
+        # we want to output the source path.
+        if (
+            ptr_info
+            and ptr_info.table_type == 'ObjectType'
+            and rptrref.is_inbound
+        ):
             # Inline link
             prefix_path_id = path_id.src_path()
             assert prefix_path_id is not None, 'expected a path'
-            rref = pgast.ColumnRef(
-                name=[ptr_info.column_name],
-                nullable=not rptrref.required)
+
+            assert rptrref.outbound_ptr
+            flipped_id = path_id.extend(ptrref=rptrref.outbound_ptr)
+            rref = pathctx.get_path_output(
+                set_rvar.query, flipped_id, aspect='identity', env=ctx.env)
+
             pathctx.put_rvar_path_bond(set_rvar, prefix_path_id)
             pathctx.put_rvar_path_output(
                 set_rvar, prefix_path_id,
                 aspect='identity', var=rref, env=ctx.env)
 
-            if astutils.is_set_op_query(set_rvar.query):
-                assert isinstance(set_rvar.query, pgast.SelectStmt)
-
-                def _pull_col(comp_qry: pgast.Query) -> None:
-                    rvar = pathctx.get_path_rvar(
-                        comp_qry, path_id, aspect='source', env=ctx.env)
-                    typeref = rvar.typeref
-                    assert typeref is not None
-                    comp_ptrref = ptr_ref_map[typeref.id]
-                    comp_pi = pg_types.get_ptrref_storage_info(
-                        comp_ptrref, resolve_type=False, link_bias=False)
-
-                    comp_qry.target_list.append(
-                        pgast.ResTarget(
-                            val=pgast.ColumnRef(name=[comp_pi.column_name]),
-                            name=ptr_info.column_name,
-                        )
-                    )
-
-                astutils.for_each_query_in_set(
-                    set_rvar.query,
-                    _pull_col,
-                )
-            elif isinstance(set_rvar, pgast.RangeSubselect):
-                rvar_path_var = pathctx.maybe_get_path_rvar(
-                    set_rvar.query,
-                    path_id=path_id,
-                    aspect='identity',
-                    env=ctx.env,
-                )
-
-                if isinstance(rvar_path_var, pgast.IntersectionRangeVar):
-                    for comp_rvar in rvar_path_var.component_rvars:
-                        if comp_rvar.typeref is None:
-                            continue
-                        comp_ptrref = ptr_ref_map.get(comp_rvar.typeref.id)
-                        if comp_ptrref is None:
-                            continue
-                        comp_pi = pg_types.get_ptrref_storage_info(
-                            comp_ptrref, resolve_type=False)
-
-                        set_rvar.query.target_list.append(
-                            pgast.ResTarget(
-                                val=pgast.ColumnRef(
-                                    name=[
-                                        comp_rvar.alias.aliasname,
-                                        comp_pi.column_name,
-                                    ]
-                                ),
-                                name=ptr_info.column_name,
-                            )
-                        )
-
     return set_rvar
 
 
@@ -1394,7 +1352,8 @@ def range_for_typeref(
 
             set_ops.append(('union', qry))
 
-        rvar = range_from_queryset(set_ops, typeref.name_hint, ctx=ctx)
+        rvar = range_from_queryset(
+            set_ops, typeref.name_hint, typeref=typeref, ctx=ctx)
 
     elif typeref.intersection:
         wrapper = pgast.SelectStmt()
@@ -1489,6 +1448,7 @@ def range_from_queryset(
     prep_filter: Callable[
         [pgast.SelectStmt, pgast.SelectStmt], None]=lambda a, b: None,
     path_id: Optional[irast.PathId]=None,
+    typeref: Optional[irast.TypeRef]=None,
     ctx: context.CompilerContextLevel,
 ) -> pgast.PathRangeVar:
 
@@ -1515,7 +1475,8 @@ def range_from_queryset(
             subquery=qry,
             alias=pgast.Alias(
                 aliasname=ctx.env.aliases.get(objname.name),
-            )
+            ),
+            typeref=typeref,
         )
 
     else:


Test patch:
diff --git a/tests/test_edgeql_introspection.py b/tests/test_edgeql_introspection.py
--- a/tests/test_edgeql_introspection.py
+++ b/tests/test_edgeql_introspection.py
@@ -20,6 +20,7 @@
 import os.path
 
 from edb.testbase import server as tb
+from edb.tools import test
 
 
 class TestIntrospection(tb.QueryTestCase):
@@ -1357,6 +1358,24 @@ async def test_edgeql_introspection_database_01(self):
 
         self.assertGreater(res, 0)
 
+    @test.xfail("""
+       We don't always properly filter things when
+       intersections/unions/backlinks are involved.
+    """)
+    async def test_edgeql_introspection_reverse_leaks_01(self):
+        res1 = await self.con.query(r"""
+            WITH MODULE schema
+            SELECT ScalarType { z := count(.<target) }
+            FILTER .name = 'std::str';
+        """)
+
+        res2 = await self.con.query_single(r"""
+            WITH MODULE schema
+            SELECT count((SELECT Property FILTER .target.name = 'std::str'));
+        """)
+
+        self.assertEqual(res1[0].z, res2)
+
     async def test_edgeql_default_injection_collision_01(self):
         await self.assert_query_result(
             r"""
@@ -1404,3 +1423,54 @@ async def test_edgeql_default_injection_collision_02(self):
                 }
             ]
         )
+
+    async def test_edgeql_introspection_reverse_01(self):
+        await self.assert_query_result(
+            r"""
+            WITH MODULE schema
+            SELECT Type {
+                name,
+                from_casts := .<from_type[IS Cast] { allow_implicit }
+            }
+            FILTER .name = 'std::BaseObject';
+            """,
+            [
+                {
+                    "from_casts": [{"allow_implicit": False}],
+                    "name": "std::BaseObject",
+                },
+            ]
+        )
+
+    async def test_edgeql_introspection_reverse_02(self):
+        await self.assert_query_result(
+            r"""
+            WITH MODULE schema
+            SELECT EXISTS Cast.from_type.<from_type[IS Cast];
+            """,
+            [True],
+        )
+
+    async def test_edgeql_introspection_reverse_03(self):
+        # just some ones that crashed; can clean up later
+        await self.con.query(r'''
+            with module schema
+            SELECT Type.<type[IS std::Object][IS schema::TupleElement];
+        ''')
+
+        await self.con.query(r'''
+            with module schema
+            SELECT Type.<type[IS std::Object]
+        ''')
+
+        await self.con.query(r'''
+            with module schema
+            SELECT Type.<type[IS schema::Object]
+        ''')
+
+        res = await self.con.query(r'''
+            with module schema
+            SELECT Type { name, z := count(.<type[IS Object]) };
+        ''')
+        count1 = res[0].z
+        self.assertFalse(all(row.z == count1 for row in res))
diff --git a/tests/test_edgeql_select.py b/tests/test_edgeql_select.py
--- a/tests/test_edgeql_select.py
+++ b/tests/test_edgeql_select.py
@@ -6112,3 +6112,40 @@ async def test_edgeql_select_result_alias_binding_02(self):
             await self.con.query(r'''
                 SELECT _ := (User { tag := _.name });
             ''')
+
+    async def test_edgeql_select_reverse_overload_01(self):
+        await self.con.execute('''
+            CREATE TYPE Dummy {
+                CREATE LINK owner -> User;
+            }
+        ''')
+
+        await self.assert_query_result(
+            r'''
+                SELECT User {
+                    z := (SELECT .<owner[IS Named] { name }
+                          ORDER BY .name)
+                } FILTER .name = 'Elvis';
+            ''',
+            [{"z": [{"name": "Regression."}, {"name": "Release EdgeDB"}]}],
+        )
+
+    async def test_edgeql_select_reverse_overload_02(self):
+        await self.con.execute('''
+            CREATE TYPE Dummy1 {
+                CREATE MULTI LINK owner -> User;
+            };
+            CREATE TYPE Dummy2 {
+                CREATE SINGLE LINK owner -> User;
+            };
+        ''')
+
+        await self.assert_query_result(
+            r'''
+                SELECT User {
+                    z := (SELECT .<owner[IS Named] { name }
+                          ORDER BY .name)
+                } FILTER .name = 'Elvis';
+            ''',
+            [{"z": [{"name": "Regression."}, {"name": "Release EdgeDB"}]}],
+        )