Repository: edgedb/edgedb

Issue:
Access Policy Internal Server Error
<!-- Please search existing issues to avoid creating duplicates. -->
- EdgeDB Version: 2.1
- OS Version: Windows 10

Steps to Reproduce:

1. Create schema like the one below
2. Create a migration and migrate the database
3. Try to `select Organization` 
4. See error same as below

<!-- If the issue is about a query error, please also provide your schema -->
Schema: 
```
  type User {
    multi link organizations := .<users[is Organization];

    multi link roles -> Role {
      on target delete allow;
      property itemId -> uuid;
    }
  }
  type Role {
    required property description -> str;

    multi link permissions -> Permission;
  }

  type Permission {
    required property slug -> str;

    required property allow -> bool {
      default := true;
    };

    index on (.slug);
    index on ((.slug, .allow));

    constraint exclusive on ((.slug, .allow))
  }

  type Organization {
    multi link users -> User {
      on target delete allow;
    };

    access policy read_allow_org
      allow select 
      using 
      (
        exists
        (
          select .users
          { 
            roles:
            { 
              permissions filter .slug = 'READ_ORG' and .allow = true
            }
          } filter
              .id ?= global currentUserId
              and .roles@itemId = Organization.id
        )
      )
  }
```

Error: Can provide more of the stack trace if needed 
```
edgedb error: InternalServerError: None
  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 "/home/edgedb/.local/share/edgedb/portable/2.1/lib/python3.10/site-packages/edb/pgsql/compiler/__init__.py", line 120, in compile_ir_to_sql_tree
          qtree = dispatch.compile(ir_expr, ctx=ctx)
        File "/home/edgedb/.local/share/edgedb/portable/2.1/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
```


Discussion:
Interesting. The shape in this query seems superfluous, and if you change the access policy to
```
access policy read_allow_org
  allow select
  using
  (
	exists
	(
	  select .users
	  filter
		  .id ?= global currentUserId
		  and .roles@itemId = Organization.id
	)
  )
```
it works.

I suspect the issue is related to using shapes in access policies.

Resolving patch:
diff --git a/edb/edgeql/compiler/stmtctx.py b/edb/edgeql/compiler/stmtctx.py
--- a/edb/edgeql/compiler/stmtctx.py
+++ b/edb/edgeql/compiler/stmtctx.py
@@ -326,6 +326,9 @@ def _fixup_materialized_sets(
     for nobe in ctx.env.source_map.values():
         if nobe.irexpr:
             children += ast_visitor.find_children(nobe.irexpr, irast.Stmt)
+    for node in ctx.env.type_rewrites.values():
+        if isinstance(node, irast.Set):
+            children += ast_visitor.find_children(node, irast.Stmt)
 
     to_clear = []
     for stmt in ordered.OrderedSet(children):


Test patch:
diff --git a/tests/test_edgeql_policies.py b/tests/test_edgeql_policies.py
--- a/tests/test_edgeql_policies.py
+++ b/tests/test_edgeql_policies.py
@@ -845,3 +845,22 @@ async def test_edgeql_policies_multi_object_01(self):
             ''',
             [{'username': 'admin'}]
         )
+
+    async def test_edgeql_policies_internal_shape_01(self):
+        await self.con.execute('''
+            alter type Issue {
+                create access policy foo_1 deny select using (
+                    not exists (select .watchers { foo := .todo }
+                                filter .foo.name = "x"));
+                create access policy foo_2 deny select using (
+                    not exists (select .watchers { todo }
+                                filter .todo.name = "x"));
+             };
+        ''')
+
+        await self.assert_query_result(
+            r'''
+                select Issue
+            ''',
+            [],
+        )