Repository: edgedb/edgedb

Issue:
ISE with `select` + `group` on backlink
Running this query:

```
select (group Level.leaderboard_entries by .level) {
  a := .key.level,
}
```

produces this error:

```
InternalServerError: Calling new() on a context other than the current one
```

Schema:

```
module default {
  type Level {
    required level_id: str {
      constraint exclusive;
      constraint min_len_value(1);
    }
    required name: str {
      constraint min_len_value(1);
    }
    multi leaderboard_entries: LeaderboardEntry {
      constraint exclusive;
    };
  }

  type LeaderboardEntry {
    required player: str {
      constraint min_len_value(1);
    }
    required finish_time_ms: int32 {
      constraint min_value(0);
    }
    single link level := .<leaderboard_entries[is Level];
  }
}
```

**edit:**

I got a different error with this slightly different query:

```
with
  b := (select (group Level.leaderboard_entries by .level) {
    a := .key.level,
  })
group b by .a;
```

Output:

```
InternalServerError: Can't find materialized set (__derived__::b@w~1)
```

- EdgeDB Version: `3.3+7771468`
- EdgeDB CLI Version: `3.5.0+907ff37`
- OS: Arch on WSL2 on Windows 10


Discussion:

Resolving patch:
diff --git a/edb/pgsql/compiler/relgen.py b/edb/pgsql/compiler/relgen.py
--- a/edb/pgsql/compiler/relgen.py
+++ b/edb/pgsql/compiler/relgen.py
@@ -1403,7 +1403,7 @@ def process_set_as_subquery(
                     ensure_source_rvar(ir_source, subctx.rel, ctx=subctx)
 
                 relctx.include_rvar(
-                    stmt, subrvar, ir_source.path_id, ctx=ctx)
+                    stmt, subrvar, ir_source.path_id, ctx=newctx)
 
         # If we are looking at a materialized computable, running
         # get_set_rvar on the source above may have made it show
@@ -1411,8 +1411,8 @@ def process_set_as_subquery(
         # in the source_rvar itself, and if we find it, skip compiling
         # the computable.
         if ir_source and (new_rvar := (
-            _lookup_set_rvar(ir_set, ctx=ctx)
-            or _lookup_set_rvar_in_source(ir_set, source_set_rvar, ctx=ctx)
+            _lookup_set_rvar(ir_set, ctx=newctx)
+            or _lookup_set_rvar_in_source(ir_set, source_set_rvar, ctx=newctx)
         )):
             if semi_join:
                 # We need to use DISTINCT, instead of doing an actual
@@ -1424,7 +1424,7 @@ def process_set_as_subquery(
                     pathctx.get_rvar_output_var_as_col_list(
                         subrvar, value_var, aspect='value', env=ctx.env))
 
-            return _new_subquery_stmt_set_rvar(ir_set, stmt, ctx=ctx)
+            return _new_subquery_stmt_set_rvar(ir_set, stmt, ctx=newctx)
 
         # materialized refs should always get picked up by now
         assert not ir_set.is_materialized_ref, (
@@ -1461,7 +1461,7 @@ def process_set_as_subquery(
             # Make a new stmt, join in the new root, and semi join on
             # the original statement.
             stmt = pgast.SelectStmt()
-            relctx.include_rvar(stmt, set_rvar, ir_set.path_id, ctx=ctx)
+            relctx.include_rvar(stmt, set_rvar, ir_set.path_id, ctx=newctx)
             stmt.where_clause = astutils.extend_binop(
                 stmt.where_clause, cond_expr)
 


Test patch:
diff --git a/tests/schemas/cards.esdl b/tests/schemas/cards.esdl
--- a/tests/schemas/cards.esdl
+++ b/tests/schemas/cards.esdl
@@ -64,7 +64,9 @@ type Card extending Named {
 
 type SpecialCard extending Card;
 
-type Award extending Named;
+type Award extending Named {
+    link winner := .<awards[is User];
+};
 
 alias AirCard := (
     SELECT Card
diff --git a/tests/test_edgeql_group.py b/tests/test_edgeql_group.py
--- a/tests/test_edgeql_group.py
+++ b/tests/test_edgeql_group.py
@@ -1371,3 +1371,13 @@ async def test_edgeql_group_uses_name_01(self):
             };
             ''',
         )
+
+    async def test_edgeql_group_backlink(self):
+        await self.assert_query_result(
+            r'''
+            select (group cards::Award by .winner) {
+              a := .key.winner,
+            };
+            ''',
+            [{"a": {}}, {"a": {}}],
+        )