Repository: edgedb/edgedb

Issue:
`Can't compile ref to visible binding` for nested FOR
<!-- Please search existing issues to avoid creating duplicates. -->
- EdgeDB Version: `2.0-dev.6463+c6f9815` (nightly)
- OS Version: macOS 12.0.1

Steps to reproduce:

Schema:

```
abstract type Person {
  required property name -> str {
    constraint exclusive;
  };
}

type Villain extending Person {
  link nemesis -> Hero;
}

type Hero extending Person {
  property secret_identity -> str;
  property number_of_movies -> int64;
  multi link villains := .<nemesis[IS Villain];
}
```

This query: 

```
WITH
  v := DETACHED default::Villain
SELECT v {
  id,
  name,
  nemesis := (
    WITH
      nemesis := v.nemesis,
      nemesis_mod := (FOR nem IN {nemesis} UNION (
        WITH
          name_len := std::len(nem.name)
        SELECT nem {
          name_len := name_len
        }
      ))
    SELECT nemesis_mod {
      name,
      single nameLen := nemesis_mod.name_len,
      single nameLen2 := nemesis_mod.name_len
    }
  )
}
```

Causes ISE:

```
edgedb error: InternalServerError: Can't compile ref to visible binding ns~5@@(__derived__::nem@w~4)
  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 "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/__init__.py", line 114, in compile_ir_to_sql_tree
          qtree = dispatch.compile(ir_expr, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 60, in compile_Set
          _compile_set_impl(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 114, in _compile_set_impl
          _compile_set(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 643, in _compile_set
          relgen.get_set_rvar(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 160, in get_set_rvar
          return _process_toplevel_query(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 263, in _process_toplevel_query
          rvars = _get_set_rvar(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 302, in _get_set_rvar
          rvars = process_set_as_subquery(ir_set, stmt, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 1301, in process_set_as_subquery
          dispatch.visit(expr, ctx=newctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/dispatch.py", line 44, in visit
          compile(ir, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/stmt.py", line 96, in compile_SelectStmt
          outvar = clauses.compile_output(stmt.result, ctx=ictx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/clauses.py", line 203, in compile_output
          dispatch.visit(ir_set, ctx=newctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 85, in visit_Set
          _compile_set_impl(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 110, in _compile_set_impl
          _compile_set(ir_set, ctx=scopectx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 647, in _compile_set
          _compile_shape(ir_set, ir_set.shape, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 666, in _compile_shape
          result = shapecomp.compile_shape(ir_set, shape, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/shapecomp.py", line 100, in compile_shape
          wrapper = relgen.set_as_subquery(
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 481, in set_as_subquery
          dispatch.visit(ir_set, ctx=subctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 85, in visit_Set
          _compile_set_impl(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 110, in _compile_set_impl
          _compile_set(ir_set, ctx=scopectx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 643, in _compile_set
          relgen.get_set_rvar(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 207, in get_set_rvar
          rvars = _get_set_rvar(ir_set, ctx=subctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 302, in _get_set_rvar
          rvars = process_set_as_subquery(ir_set, stmt, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 1301, in process_set_as_subquery
          dispatch.visit(expr, ctx=newctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/dispatch.py", line 44, in visit
          compile(ir, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/stmt.py", line 96, in compile_SelectStmt
          outvar = clauses.compile_output(stmt.result, ctx=ictx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/clauses.py", line 203, in compile_output
          dispatch.visit(ir_set, ctx=newctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 85, in visit_Set
          _compile_set_impl(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 110, in _compile_set_impl
          _compile_set(ir_set, ctx=scopectx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 643, in _compile_set
          relgen.get_set_rvar(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 207, in get_set_rvar
          rvars = _get_set_rvar(ir_set, ctx=subctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 302, in _get_set_rvar
          rvars = process_set_as_subquery(ir_set, stmt, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 1301, in process_set_as_subquery
          dispatch.visit(expr, ctx=newctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/dispatch.py", line 44, in visit
          compile(ir, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/stmt.py", line 96, in compile_SelectStmt
          outvar = clauses.compile_output(stmt.result, ctx=ictx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/clauses.py", line 203, in compile_output
          dispatch.visit(ir_set, ctx=newctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 85, in visit_Set
          _compile_set_impl(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 110, in _compile_set_impl
          _compile_set(ir_set, ctx=scopectx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 647, in _compile_set
          _compile_shape(ir_set, ir_set.shape, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 666, in _compile_shape
          result = shapecomp.compile_shape(ir_set, shape, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/shapecomp.py", line 100, in compile_shape
          wrapper = relgen.set_as_subquery(
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 481, in set_as_subquery
          dispatch.visit(ir_set, ctx=subctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 85, in visit_Set
          _compile_set_impl(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 110, in _compile_set_impl
          _compile_set(ir_set, ctx=scopectx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 643, in _compile_set
          relgen.get_set_rvar(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 207, in get_set_rvar
          rvars = _get_set_rvar(ir_set, ctx=subctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 302, in _get_set_rvar
          rvars = process_set_as_subquery(ir_set, stmt, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 1301, in process_set_as_subquery
          dispatch.visit(expr, ctx=newctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/dispatch.py", line 44, in visit
          compile(ir, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/stmt.py", line 96, in compile_SelectStmt
          outvar = clauses.compile_output(stmt.result, ctx=ictx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/clauses.py", line 203, in compile_output
          dispatch.visit(ir_set, ctx=newctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 85, in visit_Set
          _compile_set_impl(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 110, in _compile_set_impl
          _compile_set(ir_set, ctx=scopectx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 643, in _compile_set
          relgen.get_set_rvar(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 207, in get_set_rvar
          rvars = _get_set_rvar(ir_set, ctx=subctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 302, in _get_set_rvar
          rvars = process_set_as_subquery(ir_set, stmt, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 1301, in process_set_as_subquery
          dispatch.visit(expr, ctx=newctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/dispatch.py", line 44, in visit
          compile(ir, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/stmt.py", line 96, in compile_SelectStmt
          outvar = clauses.compile_output(stmt.result, ctx=ictx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/clauses.py", line 203, in compile_output
          dispatch.visit(ir_set, ctx=newctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 85, in visit_Set
          _compile_set_impl(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 110, in _compile_set_impl
          _compile_set(ir_set, ctx=scopectx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 643, in _compile_set
          relgen.get_set_rvar(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 207, in get_set_rvar
          rvars = _get_set_rvar(ir_set, ctx=subctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 302, in _get_set_rvar
          rvars = process_set_as_subquery(ir_set, stmt, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 1301, in process_set_as_subquery
          dispatch.visit(expr, ctx=newctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/dispatch.py", line 44, in visit
          compile(ir, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/stmt.py", line 96, in compile_SelectStmt
          outvar = clauses.compile_output(stmt.result, ctx=ictx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/clauses.py", line 203, in compile_output
          dispatch.visit(ir_set, ctx=newctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 85, in visit_Set
          _compile_set_impl(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 110, in _compile_set_impl
          _compile_set(ir_set, ctx=scopectx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 643, in _compile_set
          relgen.get_set_rvar(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 207, in get_set_rvar
          rvars = _get_set_rvar(ir_set, ctx=subctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 302, in _get_set_rvar
          rvars = process_set_as_subquery(ir_set, stmt, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 1301, in process_set_as_subquery
          dispatch.visit(expr, ctx=newctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/dispatch.py", line 44, in visit
          compile(ir, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/stmt.py", line 96, in compile_SelectStmt
          outvar = clauses.compile_output(stmt.result, ctx=ictx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/clauses.py", line 203, in compile_output
          dispatch.visit(ir_set, ctx=newctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 85, in visit_Set
          _compile_set_impl(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 114, in _compile_set_impl
          _compile_set(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 643, in _compile_set
          relgen.get_set_rvar(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 207, in get_set_rvar
          rvars = _get_set_rvar(ir_set, ctx=subctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 383, in _get_set_rvar
          rvars = process_set_as_func_expr(ir_set, stmt, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 2889, in process_set_as_func_expr
          args = _compile_call_args(ir_set, ctx=newctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 2800, in _compile_call_args
          arg_ref = dispatch.compile(ir_arg.expr, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 60, in compile_Set
          _compile_set_impl(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 114, in _compile_set_impl
          _compile_set(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/expr.py", line 643, in _compile_set
          relgen.get_set_rvar(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 207, in get_set_rvar
          rvars = _get_set_rvar(ir_set, ctx=subctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 418, in _get_set_rvar
          rvars = process_set_as_path(ir_set, stmt, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 1073, in process_set_as_path
          ensure_source_rvar(ir_source, stmt, ctx=ctx),
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 441, in ensure_source_rvar
          get_set_rvar(ir_set, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 207, in get_set_rvar
          rvars = _get_set_rvar(ir_set, ctx=subctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 426, in _get_set_rvar
          rvars = process_set_as_root(ir_set, stmt, ctx=ctx)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/relgen.py", line 710, in process_set_as_root
          assert not ir_set.is_visible_binding_ref, (
      AssertionError: Can't compile ref to visible binding ns~5@@(__derived__::nem@w~4)
      
      The above exception was the direct cause of the following exception:
      
      Traceback (most recent call last):
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/server/compiler_pool/worker.py", line 309, in worker
          res = meth(*args)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/server/compiler_pool/worker.py", line 177, in compile
          units, cstate = COMPILER.compile(
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/server/compiler/compiler.py", line 2109, in compile
          units = self._compile(ctx=ctx, source=source)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/server/compiler/compiler.py", line 1671, in _compile
          return self._try_compile(ctx=ctx, source=source)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/server/compiler/compiler.py", line 1724, in _try_compile
          comp, capabilities = self._compile_dispatch_ql(
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/server/compiler/compiler.py", line 1645, in _compile_dispatch_ql
          query = self._compile_ql_query(ctx, ql)
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/server/compiler/compiler.py", line 605, in _compile_ql_query
          sql_text, argmap = pg_compiler.compile_ir_to_sql(
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/__init__.py", line 146, in compile_ir_to_sql
          qtree = compile_ir_to_sql_tree(
        File "/Users/colinmcd94/Library/Application Support/edgedb/portable/2.0-dev.6463/lib/python3.10/site-packages/edb/pgsql/compiler/__init__.py", line 129, in compile_ir_to_sql_tree
          raise errors.InternalServerError(*args) from e
      edb.errors.InternalServerError: Can't compile ref to visible binding ns~5@@(__derived__::nem@w~4)

```



Discussion:
```
SELECT User {
  name,
  avatar := (
    WITH
      nemesis := User.avatar,
      nemesis_mod := (FOR nem IN {nemesis} UNION (
        WITH
          name_len := std::len(nem.name)
        SELECT nem {
          name_len := name_len
        }
      ))
    SELECT nemesis_mod {
      name,
      single nameLen := nemesis_mod.name_len,
      single nameLen2 := nemesis_mod.name_len
    }
  )
};
```
is a version that fails on the `scope` database

Resolving patch:
diff --git a/edb/edgeql/compiler/inference/cardinality.py b/edb/edgeql/compiler/inference/cardinality.py
--- a/edb/edgeql/compiler/inference/cardinality.py
+++ b/edb/edgeql/compiler/inference/cardinality.py
@@ -512,6 +512,10 @@ def _infer_set_inner(
     if rptr is not None:
         rptrref = rptr.ptrref
 
+        source_card = infer_cardinality(
+            rptr.source, scope_tree=scope_tree, ctx=ctx,
+        )
+
         ctx.env.schema, ptrcls = typeutils.ptrcls_from_ptrref(
             rptrref, schema=ctx.env.schema)
         if ir.expr:
@@ -525,10 +529,6 @@ def _infer_set_inner(
                 ctx=ctx,
             )
 
-        source_card = infer_cardinality(
-            rptr.source, scope_tree=scope_tree, ctx=ctx,
-        )
-
     # We have now inferred all of the subtrees we need to, so it is
     # safe to return.
 
diff --git a/edb/edgeql/compiler/setgen.py b/edb/edgeql/compiler/setgen.py
--- a/edb/edgeql/compiler/setgen.py
+++ b/edb/edgeql/compiler/setgen.py
@@ -486,17 +486,18 @@ def compile_path(expr: qlast.Path, *, ctx: context.ContextLevel) -> irast.Set:
                 scope_set = scoped_set(scope_set, ctx=subctx)
 
         # We compile computables under namespaces, but we need to have
-        # the source of the computable *not* under that namespace (and
-        # potentially with the source's expr/rptr/etc?), so we need to
-        # do some remapping.
+        # the source of the computable *not* under that namespace,
+        # so we need to do some remapping.
         if mapped := get_view_map_remapping(path_tip.path_id, ctx):
             path_tip = new_set_from_set(
                 path_tip,
                 path_id=mapped.path_id,
                 preserve_scope_ns=True,
-                expr=mapped.expr,
-                rptr=mapped.rptr,
                 ctx=ctx)
+            # If we are remapping a source path, then we know that
+            # the path is visible, so we shouldn't recompile it
+            # if it is a computable path.
+            is_computable = False
 
         if is_computable:
             computables.append(path_tip)
@@ -1561,7 +1562,9 @@ def should_materialize(
     if (
         materialize_visible
         and (vis := irutils.find_potentially_visible(
-            ir, ctx.path_scope, ctx.env.scope_tree_nodes, skipped_bindings))
+            ir,
+            ctx.env.scope_tree_nodes[not_none(ir.path_scope_id)],
+            ctx.env.scope_tree_nodes, skipped_bindings))
     ):
         reasons.append(irast.MaterializeVisible(sets=vis))
 
diff --git a/edb/ir/utils.py b/edb/ir/utils.py
--- a/edb/ir/utils.py
+++ b/edb/ir/utils.py
@@ -341,9 +341,10 @@ class FindPathScopes(ast.NodeVisitor):
     This is set up so that another visitor could inherit from it,
     override process_set, and also collect the scope tree info.
     """
-    def __init__(self) -> None:
+    def __init__(self, init_scope: Optional[int]=None) -> None:
         super().__init__()
-        self.path_scope_ids: List[Optional[int]] = [None]
+        self.path_scope_ids: List[Optional[int]] = [init_scope]
+        self.use_scopes: Dict[irast.Set, Optional[int]] = {}
         self.scopes: Dict[irast.Set, Optional[int]] = {}
 
     def visit_Stmt(self, stmt: irast.Stmt) -> Any:
@@ -365,6 +366,7 @@ def visit_Stmt(self, stmt: irast.Stmt) -> Any:
 
     def visit_Set(self, node: irast.Set) -> Any:
         val = self.path_scope_ids[-1]
+        self.use_scopes[node] = val
         if node.path_scope_id:
             self.path_scope_ids.append(node.path_scope_id)
         if not node.is_binding:
@@ -394,9 +396,16 @@ class FindPotentiallyVisibleVisitor(FindPathScopes):
     skip_hidden = True
     extra_skips = frozenset(['materialized_sets'])
 
-    def __init__(self, to_skip: AbstractSet[irast.PathId]) -> None:
-        super().__init__()
+    def __init__(
+        self,
+        to_skip: AbstractSet[irast.PathId],
+        scope: irast.ScopeTreeNode,
+        scope_tree_nodes: Mapping[int, irast.ScopeTreeNode],
+    ) -> None:
+        super().__init__(init_scope=scope.unique_id)
         self.to_skip = to_skip
+        self.orig_scope = scope
+        self.scope_tree_nodes = scope_tree_nodes
 
     def combine_field_results(self, xs: Any) -> Set[irast.Set]:
         out = set()
@@ -410,7 +419,18 @@ def combine_field_results(self, xs: Any) -> Set[irast.Set]:
 
     def process_set(self, node: irast.Set) -> Set[irast.Set]:
         if node.path_id in self.to_skip:
-            return set()
+            # We only skip nodes in to_skip if their use site is
+            # underneath our original binding site. This prevents us
+            # from skipping references to them embedded in outside
+            # WITH bindings.
+            if (
+                (psid := self.use_scopes[node]) is not None
+                and (
+                    self.orig_scope in
+                    self.scope_tree_nodes[psid].ancestors
+                )
+            ):
+                return set()
 
         results = [{node}]
         results.append(self.visit(node.rptr))
@@ -438,7 +458,8 @@ def find_potentially_visible(
 ) -> Set[Tuple[irast.PathId, irast.Set]]:
     """Find all "potentially visible" sets referenced."""
     # TODO: Make this caching.
-    visitor = FindPotentiallyVisibleVisitor(to_skip=to_skip)
+    visitor = FindPotentiallyVisibleVisitor(
+        to_skip=to_skip, scope=scope, scope_tree_nodes=scope_tree_nodes)
     visible_sets = cast(Set[irast.Set], visitor.visit(stmt))
 
     visible_paths = set()


Test patch:
diff --git a/tests/test_edgeql_scope.py b/tests/test_edgeql_scope.py
--- a/tests/test_edgeql_scope.py
+++ b/tests/test_edgeql_scope.py
@@ -3546,11 +3546,11 @@ async def test_edgeql_select_outer_rebind_01(self):
             ]
         )
 
-    @test.xfail("still breaks with a computed link")
-    async def test_edgeql_select_outer_rebind_02(self):
+    async def test_edgeql_select_outer_rebind_02a(self):
         await self.assert_query_result(
             r'''
             select Card {
+              name,
               owners := (
                 with
                   U := (
@@ -3567,6 +3567,27 @@ async def test_edgeql_select_outer_rebind_02(self):
             [{"name": "Djinn", "owners": [{"n": "Carol"}, {"n": "Dave"}]}]
         )
 
+    async def test_edgeql_select_outer_rebind_02b(self):
+        await self.assert_query_result(
+            r'''
+            select Card {
+              name,
+              foo := (
+                with
+                  U := (
+                    select Card.<deck[IS User] {
+                      n := Card.<deck[IS User].name
+                    }
+                  )
+                select U {
+                  n
+                } order by .name
+              )
+            } FILTER .name = 'Djinn';
+            ''',
+            [{"name": "Djinn", "foo": [{"n": "Carol"}, {"n": "Dave"}]}]
+        )
+
     async def test_edgeql_select_outer_rebind_03(self):
         await self.assert_query_result(
             r'''
@@ -3627,6 +3648,64 @@ async def test_edgeql_select_outer_rebind_04(self):
             ]
         )
 
+    async def test_edgeql_select_outer_rebind_05(self):
+        await self.assert_query_result(
+            r'''
+            SELECT User {
+              name,
+              avatar := (
+                WITH
+                  nemesis := User.avatar,
+                  nemesis_mod := (FOR nem IN {nemesis} UNION (
+                    WITH
+                      name_len := std::len(nem.name)
+                    SELECT nem {
+                      name_len := name_len
+                    }
+                  ))
+                SELECT nemesis_mod {
+                  name,
+                  single nameLen := nemesis_mod.name_len,
+                  single nameLen2 := nemesis_mod.name_len
+                }
+              )
+            }
+            FILTER .name = 'Alice';
+            ''',
+            [
+                {
+                    "avatar": {"name": "Dragon", "nameLen": 6, "nameLen2": 6},
+                    "name": "Alice"
+                }
+            ]
+        )
+
+    async def test_edgeql_select_outer_rebind_06(self):
+        # hm, not really an outer rebind anymore!
+        await self.assert_query_result(
+            r'''
+            for User in (select User filter .name = 'Alice') union (
+              (
+                WITH
+                  nemesis := User.avatar,
+                  nemesis_mod := (FOR nem IN {nemesis} UNION (
+                    WITH
+                      name_len := std::len(nem.name)
+                    SELECT nem {
+                      name_len := name_len
+                    }
+                  ))
+                SELECT nemesis_mod {
+                  name,
+                  single nameLen := nemesis_mod.name_len,
+                  single nameLen2 := nemesis_mod.name_len
+                }
+              )
+            );
+            ''',
+            [{"name": "Dragon", "nameLen": 6, "nameLen2": 6}]
+        )
+
     async def test_edgeql_scope_for_with_computable_01(self):
         await self.assert_query_result(
             r'''