Repository: edgedb/edgedb

Issue:
InternalServerError: Calling new() on a context other than the current one / AssertionError
<!-- Please search existing issues to avoid creating duplicates. -->

<!--
For the EdgeDB Version: run `edgedb query 'select sys::get_version_as_str()'` from your project directory (or run `select sys::get_version_as_str();` in the EdgeDB interactive shell).
For the EdgeDB CLI Version: Run `edgedb --version` from anywhere
-->

- EdgeDB Version: 3.0-dev.7411+306d957
- EdgeDB CLI Version: 3.0.0-dev.947+3c26302
- OS Version: endeavouros linux-lts

Steps to Reproduce:

1. Apply migration
2. Run this query: `update Avatar set {deleted_at:=datetime_of_statement()};`

<!-- If the issue is about a query error, please also provide your schema -->

[Schema + migration](https://gist.github.com/lu-zen/315117d2c54ab5f50b1c0a23da95e789)

Error:
```
edgedb error: InternalServerError: Calling new() on a context other than the current one
  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/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/server/compiler_pool/worker_proc.py", line 55, in worker
          res = meth(*args)
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/server/compiler_pool/worker.py", line 161, in compile
          units, cstate = COMPILER.compile(
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/server/compiler/compiler.py", line 742, in compile
          unit_group = compile(ctx=ctx, source=source)
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/server/compiler/compiler.py", line 1923, in compile
          return _try_compile(ctx=ctx, source=source)
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/server/compiler/compiler.py", line 1991, in _try_compile
          comp, capabilities = _compile_dispatch_ql(
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/server/compiler/compiler.py", line 1897, in _compile_dispatch_ql
          query = _compile_ql_query(ctx, ql, script_info=script_info)
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/server/compiler/compiler.py", line 1461, in _compile_ql_query
          ir = qlcompiler.compile_ast_to_ir(
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/edgeql/compiler/__init__.py", line 179, in wrapper
          return func(*args, **kwargs)
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/edgeql/compiler/__init__.py", line 237, in compile_ast_to_ir
          ir_set = dispatch_mod.compile(tree, ctx=ctx)
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/functools.py", line 889, in wrapper
          return dispatch(args[0].__class__)(*args, **kw)
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/edgeql/compiler/stmt.py", line 616, in compile_UpdateQuery
          stmt.subject = compile_query_subject(
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/edgeql/compiler/stmt.py", line 1469, in compile_query_subject
          view_scls, expr = viewgen.process_view(
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/edgeql/compiler/viewgen.py", line 151, in process_view
          view_scls, ir = _process_view(
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/edgeql/compiler/viewgen.py", line 432, in _process_view
          rewrites = _compile_rewrites(
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/edgeql/compiler/viewgen.py", line 853, in _compile_rewrites
          rewrites = _compile_rewrites_for_stype(
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/edgeql/compiler/viewgen.py", line 1086, in _compile_rewrites_for_stype
          pointer, ptr_set = _normalize_view_ptr_expr(
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/edgeql/compiler/viewgen.py", line 1498, in _normalize_view_ptr_expr
          irexpr, sub_view_rptr = _compile_qlexpr(
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/edgeql/compiler/viewgen.py", line 1254, in _compile_qlexpr
          source_set = setgen.fixup_computable_source_set(ir_source, ctx=ctx)
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/edgeql/compiler/setgen.py", line 1341, in fixup_computable_source_set
          source_set = new_set_from_set(
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/edgeql/compiler/setgen.py", line 187, in new_set_from_set
          return new_set(
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/edgeql/compiler/setgen.py", line 103, in new_set
          policies.try_type_rewrite(stype, skip_subtypes=skip_subtypes, ctx=ctx)
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/edgeql/compiler/policies.py", line 310, in try_type_rewrite
          with ctx.detached() as subctx:
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/common/compiler.py", line 67, in __enter__
          return self.context.push(self.mode, self.prevlevel)
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/common/compiler.py", line 103, in push
          return self._push(mode, prevlevel)
        File "/home/user/.local/share/edgedb/portable/3.0-dev.7411/lib/python3.10/site-packages/edb/common/compiler.py", line 125, in _push
          raise AssertionError(
      AssertionError: Calling new() on a context other than the current one
```



Discussion:

Resolving patch:
diff --git a/edb/edgeql/compiler/viewgen.py b/edb/edgeql/compiler/viewgen.py
--- a/edb/edgeql/compiler/viewgen.py
+++ b/edb/edgeql/compiler/viewgen.py
@@ -1251,7 +1251,9 @@ def _compile_qlexpr(
 
         shape_expr_ctx.defining_view = view_scls
         shape_expr_ctx.path_scope.unnest_fence = True
-        source_set = setgen.fixup_computable_source_set(ir_source, ctx=ctx)
+        source_set = setgen.fixup_computable_source_set(
+            ir_source, ctx=shape_expr_ctx
+        )
         shape_expr_ctx.partial_path_prefix = source_set
 
         if s_ctx.exprtype.is_mutation() and ptrcls is not None:


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
@@ -1125,3 +1125,54 @@ async def test_edgeql_policies_function_01(self):
             r'''select (count(Issue), count_Issue())''',
             [(4, 4)],
         )
+
+    async def test_edgeql_policies_complex_01(self):
+        await self.migrate(
+            """
+            abstract type Auditable {
+                access policy auditable_default
+                    allow all ;
+                access policy auditable_prohibit_hard_deletes
+                    deny delete  {
+                        errmessage := 'hard deletes are disallowed';
+                    };
+                delegated constraint std::expression on
+                    ((.updated_at >= .created_at))
+                    except (NOT (EXISTS (.updated_at)));
+                delegated constraint std::expression on
+                    ((.deleted_at > .created_at))
+                    except (NOT (EXISTS (.deleted_at)));
+                required property created_at: std::datetime {
+                    default := (std::datetime_of_statement());
+                    readonly := true;
+                };
+                property deleted_at: std::datetime;
+                required property uid: std::str {
+                    default := <str>random();
+                    readonly := true;
+                    constraint std::exclusive;
+                };
+                property updated_at: std::datetime {
+                    rewrite
+                        update
+                        using (std::datetime_of_statement());
+                };
+            };
+            type Avatar extending default::Auditable {
+                link owner := (.<avatar[is default::Member]);
+                required property url: std::str;
+            };
+            type Member extending default::Auditable {
+                link avatar: default::Avatar {
+                    on source delete delete target if orphan;
+                    on target delete allow;
+                    constraint std::exclusive;
+                };
+            };
+            """
+        )
+        await self.con.execute(
+            '''
+            update Avatar set {deleted_at:=datetime_of_statement()};
+            '''
+        )