internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: edgedb/edgedb

Issue:
Confusing `__slots__` behavior of `struct.ProtoField` subtypes
After fixing https://github.com/edgedb/edgedb/pull/2722 I realiazed that probably current `edb/schema/objects.Field` behavior is not what users / developers might expect.

Since it has `__slots__` defined without explicit `__dict__`, it is expected to fail on unknown attribute assign.
But, this does not happen right now, because `struct.ProtoField` does not have `__slots__`, but has `__dict__`.

Short repro:

```python
class A:
   ...

class B(A):
    __slots__ = ('b',)
    def __init__(self) -> None:
        self.a = 1  # works, but is missing from slots
        self.b = 2  # ok
```

So, there are two ways of "fixing" this:
1. Add empty `__slots__` to `struct.ProtoField` (I will go this way for now, feel free to correct me)
2. Add explicit `__dict__` to `__slots__` of `edb/schema/objects.Field` and friends


Discussion:

Resolving patch:
diff --git a/edb/common/struct.py b/edb/common/struct.py
--- a/edb/common/struct.py
+++ b/edb/common/struct.py
@@ -27,7 +27,7 @@
 
 
 class ProtoField:
-    pass
+    __slots__ = ()
 
 
 class NoDefaultT(enum.Enum):
diff --git a/edb/schema/objects.py b/edb/schema/objects.py
--- a/edb/schema/objects.py
+++ b/edb/schema/objects.py
@@ -461,7 +461,7 @@ def __repr__(self) -> str:
 
 class SchemaField(Field[Type_T]):
 
-    __slots__ = ('default', 'hashable')
+    __slots__ = ('default', 'hashable', 'allow_ddl_set', 'index')
 
     #: The default value to use for the field.
     default: Any


Test patch:
Repository: edgedb/edgedb

Issue:
Update notebook protocol to return protocol version
Protocol version 0.11 introduces changes in the type descriptor structure, so the protocol version is now required to decode the codecs, which the notebook protocol currently doesn't return.


Discussion:

Resolving patch:
diff --git a/edb/server/compiler/compiler.py b/edb/server/compiler/compiler.py
--- a/edb/server/compiler/compiler.py
+++ b/edb/server/compiler/compiler.py
@@ -1884,6 +1884,7 @@ def compile_notebook(
         database_config: Mapping[str, config.SettingValue],
         system_config: Mapping[str, config.SettingValue],
         queries: List[str],
+        protocol_version: tuple,
         implicit_limit: int = 0,
     ) -> List[dbstate.QueryUnit]:
 
@@ -1905,6 +1906,7 @@ def compile_notebook(
             inline_typenames=True,
             stmt_mode=enums.CompileStatementMode.SINGLE,
             json_parameters=False,
+            protocol_version=protocol_version
         )
 
         ctx.state.start_tx()
@@ -1929,7 +1931,8 @@ def compile_notebook(
                     inline_typenames=True,
                     stmt_mode=enums.CompileStatementMode.SINGLE,
                     json_parameters=False,
-                    source=source
+                    source=source,
+                    protocol_version=protocol_version
                 )
 
                 result.append(


Test patch:
diff --git a/tests/test_http_notebook.py b/tests/test_http_notebook.py
--- a/tests/test_http_notebook.py
+++ b/tests/test_http_notebook.py
@@ -45,6 +45,9 @@ def run_queries(self, queries: List[str]):
         response = urllib.request.urlopen(
             req, json.dumps(req_data).encode(), context=self.tls_context
         )
+
+        self.assertIsNotNone(response.headers['EdgeDB-Protocol-Version'])
+
         resp_data = json.loads(response.read())
         return resp_data
 
@@ -192,3 +195,11 @@ def test_http_notebook_05(self):
                 ]
             }
         )
+
+    def test_http_notebook_06(self):
+        results = self.run_queries([
+            'SELECT {protocol := "notebook"}'
+        ])
+
+        self.assertEqual(results['kind'], 'results')
+        self.assertEqual(results['results'][0]['kind'], 'data')
Repository: edgedb/edgedb

Issue:
Using [IS Type] in a shape on a computable link fails.
<!-- Please search existing issues to avoid creating duplicates. -->
- EdgeDB Version: 1.0.0-beta.1
- OS Version: Linux

Steps to Reproduce:

Schema:
```
module default {
    abstract type Exercise {
        property description -> str;
        property num -> int64;
        link sheet -> MathSheet;
    }

    type MathEx extending Exercise {
        property answer -> int64;
    }

    type MathSheet {
        required property serial -> int64;
        link exercises := .<sheet[IS Exercise];
    }
};
```

This query causes an error:
```
edgedb> SELECT MathSheet{exercises[IS MathEx]: {num, answer}};
ERROR: InternalServerError: column Exercise~1.477e284c-7deb-11eb-a3cc-0b4fca5304c1 does not exist
  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:
      edb.errors.InternalServerError: column Exercise~1.477e284c-7deb-11eb-a3cc-0b4fca5304c1 does not exist
```


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
@@ -781,6 +781,7 @@ def process_set_as_path_type_intersection(
     if (not source_is_visible
             and ir_source.rptr is not None
             and not ir_source.path_id.is_type_intersection_path()
+            and not ir_source.rptr.ptrref.is_computable
             and (
                 ptrref.is_subtype
                 or pg_types.get_ptrref_storage_info(


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
@@ -2847,6 +2847,18 @@ async def test_edgeql_scope_link_narrow_card_01(self):
             ],
         )
 
+    async def test_edgeql_scope_link_narrow_computable_01(self):
+        await self.assert_query_result(
+            """
+                SELECT Card {
+                    owners[IS Bot]: {name}
+                } FILTER .name = 'Sprite'
+            """,
+            [
+                {"owners": [{"name": "Dave"}]},
+            ],
+        )
+
     async def test_edgeql_scope_branch_01(self):
         await self.assert_query_result(
             """
Repository: edgedb/edgedb

Issue:
Migration creation fails despite no questions asked
In a project with lots of migrations, I'm no longer able to create new migrations. The `edgedb migration create` command fails without asking any questions.

```
$ edgedb migration create
edgedb error: EdgeDB could not resolve migration with the provided answers. Please retry with different answers.
```

This is a path-dependent problem - when I deleted the existing migrations and “squashed” them into a single new migration this went away. 

Repro

```
git clone git@github.com:colinhacks/lotsa-migrations.git
cd lotsa-migrations
edgedb project init
edgedb migration create
```


[lotsa-migrations.zip](https://github.com/edgedb/edgedb/files/7584266/lotsa-migrations.zip)



Discussion:
Fortunately, the lots of migrations part of this was a red herring. Migrating from
```
module default {
  type Bag {
    property switching_tuple -> tuple<name: str, age: int64>;
  };
}
```
to
```
module default {
  type Bag {
    property switching_tuple -> tuple<name: str, weight: int64>;
  };
}
```
is the issue.

Hopefully shouldn't be tough.

Resolving patch:
diff --git a/edb/schema/objects.py b/edb/schema/objects.py
--- a/edb/schema/objects.py
+++ b/edb/schema/objects.py
@@ -2682,6 +2682,26 @@ def create(  # type: ignore
             super().create(schema, data.values(), _keys=tuple(data.keys())),
         )
 
+    @classmethod
+    def compare_values(
+        cls,
+        ours: ObjectCollection[Object_T],
+        theirs: ObjectCollection[Object_T],
+        *,
+        our_schema: s_schema.Schema,
+        their_schema: s_schema.Schema,
+        context: ComparisonContext,
+        compcoef: float,
+    ) -> float:
+        assert isinstance(ours, ObjectDict)
+        assert isinstance(theirs, ObjectDict)
+        if ours.keys(our_schema) != theirs.keys(their_schema):
+            return compcoef
+        return super().compare_values(
+            ours, theirs,
+            our_schema=our_schema, their_schema=their_schema,
+            context=context, compcoef=compcoef)
+
     def __init__(
         self,
         _ids: Collection[uuid.UUID],


Test patch:
diff --git a/tests/test_edgeql_data_migration.py b/tests/test_edgeql_data_migration.py
--- a/tests/test_edgeql_data_migration.py
+++ b/tests/test_edgeql_data_migration.py
@@ -10294,6 +10294,24 @@ async def test_edgeql_migration_alias_07(self):
             ],
         )
 
+    async def test_edgeql_migration_tuple_01(self):
+        await self.migrate(r'''
+            type Bag {
+                property switching_tuple -> tuple<name: str, weight: int64>;
+            };
+        ''')
+
+        with self.assertRaisesRegex(
+            AssertionError,
+            r"Please specify a conversion expression to alter the type of "
+            r"property 'switching_tuple'"
+        ):
+            await self.migrate(r'''
+                type Bag {
+                    property switching_tuple -> tuple<name: str, age: int64>;
+                };
+            ''')
+
 
 class TestEdgeQLDataMigrationNonisolated(tb.DDLTestCase):
     TRANSACTION_ISOLATION = False
Repository: edgedb/edgedb

Issue:
Fails to migrate to empty module
<!-- Please search existing issues to avoid creating duplicates. -->
- EdgeDB Version: 1.0-rc.3+2b303d3
- OS Version: macOS

Steps to Reproduce:

1. `start migration to { module default {} };`
2. `populate migration;`
3. `commit migration;`

```
edgedb error: SchemaError: cannot get item data: item '7c3aaab2-5d0f-11ec-b61a-f38cc326c29d' is not present in the schema <FlatSchema gen:5933 at 0x10aa70580>
```

<!-- If the issue is about a query error, please also provide your schema -->
Schema:
```
type A {
    property name -> str;
}
type B {
    property name -> str;
}
type C extending A, B {
}
```


Discussion:

Resolving patch:
diff --git a/edb/pgsql/delta.py b/edb/pgsql/delta.py
--- a/edb/pgsql/delta.py
+++ b/edb/pgsql/delta.py
@@ -5096,10 +5096,12 @@ def apply(
                 if target_is_affected and current_target is not None:
                     affected_targets.add(current_target)
             else:
-                if source.is_view(schema):
+                if source.is_view(eff_schema):
                     continue
 
-                affected_sources.add(source)
+                current_source = schema.get_by_id(source.id, None)
+                if current_source:
+                    affected_sources.add(current_source)
 
                 if target_is_affected:
                     affected_targets.add(target)


Test patch:
diff --git a/tests/test_edgeql_data_migration.py b/tests/test_edgeql_data_migration.py
--- a/tests/test_edgeql_data_migration.py
+++ b/tests/test_edgeql_data_migration.py
@@ -10312,6 +10312,20 @@ async def test_edgeql_migration_tuple_01(self):
                 };
             ''')
 
+    async def test_edgeql_migration_inheritance_to_empty_01(self):
+        await self.migrate(r'''
+            type A {
+                property name -> str;
+            }
+            type B {
+                property name -> str;
+            }
+            type C extending A, B {
+            }
+        ''')
+
+        await self.migrate('')
+
 
 class TestEdgeQLDataMigrationNonisolated(tb.DDLTestCase):
     TRANSACTION_ISOLATION = False
diff --git a/tests/test_schema.py b/tests/test_schema.py
--- a/tests/test_schema.py
+++ b/tests/test_schema.py
@@ -6668,6 +6668,18 @@ def test_schema_migrations_extend_enum_01(self):
             scalar type foo extending enum<Foo, Bar, Baz>;
         """])
 
+    def test_schema_to_empty_01(self):
+        self._assert_migration_equivalence([r"""
+            type A {
+                property name -> str;
+            }
+            type B {
+                property name -> str;
+            }
+            type C extending A, B {
+            }
+        """])
+
     def test_schema_migrations_union_01(self):
         with self.assertRaisesRegex(
             errors.QueryError,
Repository: edgedb/edgedb

Issue:
Cannot drop multi link in parent type
<!-- Please search existing issues to avoid creating duplicates. -->
- EdgeDB Version: `1.0-rc.3+2b303d3`, `1.0-rc.2+7f1c22d`
- OS Version: macOS

Steps to Reproduce:

```
edgedb> ALTER TYPE D {
.......     DROP LINK multi_link;
....... };
Error: InternalServerError: relation "edgedbpub.d504948c-5d32-11ec-b73c-a7c895ab6088" does not exist
  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
```

<!-- If the issue is about a query error, please also provide your schema -->
Schema:

```
    type C;
    type D {
        multi link multi_link -> C;
    };
    type E extending default::D;
```


Discussion:

Resolving patch:
diff --git a/edb/pgsql/delta.py b/edb/pgsql/delta.py
--- a/edb/pgsql/delta.py
+++ b/edb/pgsql/delta.py
@@ -2576,7 +2576,7 @@ def alter_ancestor_inhviews(
         exclude_children: FrozenSet[s_sources.Source] = frozenset(),
     ) -> None:
         for base in obj.get_ancestors(schema).objects(schema):
-            if has_table(base, schema):
+            if has_table(base, schema) and not context.is_deleting(base):
                 self.alter_inhview(
                     schema,
                     context,


Test patch:
diff --git a/tests/test_edgeql_ddl.py b/tests/test_edgeql_ddl.py
--- a/tests/test_edgeql_ddl.py
+++ b/tests/test_edgeql_ddl.py
@@ -12276,6 +12276,21 @@ async def test_edgeql_ddl_linkprop_partial_paths(self):
             };
         """)
 
+    async def test_edgeql_ddl_drop_parent_multi_link(self):
+        await self.con.execute(r"""
+            CREATE TYPE C;
+            CREATE TYPE D {
+                CREATE MULTI LINK multi_link -> C;
+            };
+            CREATE TYPE E EXTENDING D
+        """)
+
+        await self.con.execute(r"""
+            ALTER TYPE D {
+                DROP LINK multi_link;
+            };
+        """)
+
 
 class TestConsecutiveMigrations(tb.DDLTestCase):
     TRANSACTION_ISOLATION = False
Repository: edgedb/edgedb

Issue:
`contains` doesn't work on objects
```
SELECT contains(array_agg(User), (SELECT User FILTER .name = 'Alice'));
```
gives
```
      edb.errors.InternalServerError: function edgedbstd.a92fa307-62e2-11ec-81a8-bffaba810525(uuid[], uuid, uuid) does not exist
```


Discussion:

Resolving patch:
diff --git a/edb/edgeql/compiler/func.py b/edb/edgeql/compiler/func.py
--- a/edb/edgeql/compiler/func.py
+++ b/edb/edgeql/compiler/func.py
@@ -804,8 +804,18 @@ def finalize_args(
             elif arg_scope is not None:
                 arg_scope.collapse()
 
+            # Object type arguments to functions may be overloaded, so
+            # we populate a path id field so that we can also pass the
+            # type as an argument on the pgsql side. If the param type
+            # is "anytype", though, then it can't be overloaded on
+            # that argument.
             arg_type = setgen.get_set_type(arg, ctx=ctx)
-            if isinstance(arg_type, s_objtypes.ObjectType):
+            if (
+                isinstance(arg_type, s_objtypes.ObjectType)
+                and barg.param
+                and not barg.param.get_type(ctx.env.schema).is_any(
+                    ctx.env.schema)
+            ):
                 arg_type_path_id = pathctx.extend_path_id(
                     arg.path_id,
                     ptrcls=arg_type.getptr(


Test patch:
diff --git a/tests/test_edgeql_functions.py b/tests/test_edgeql_functions.py
--- a/tests/test_edgeql_functions.py
+++ b/tests/test_edgeql_functions.py
@@ -3527,6 +3527,17 @@ async def test_edgeql_functions_contains_04(self):
             {False},
         )
 
+    async def test_edgeql_functions_contains_05(self):
+        await self.assert_query_result(
+            r'''
+                SELECT contains(
+                    array_agg(User),
+                    (SELECT User FILTER .name = 'Elvis')
+                )
+            ''',
+            [True],
+        )
+
     async def test_edgeql_functions_find_01(self):
         await self.assert_query_result(
             r'''SELECT find(<str>{}, <str>{});''',
Repository: edgedb/edgedb

Issue:
Internal name used in `DuplicateDatabaseDefinitionError` message
- EdgeDB Version: 1.0-rc.4+dev6235.d2021113023.gd81c0a75f.cv202111180000

Error message when attempting to create database that already exists contains a random prefix to the database name (I assume some internal name?):

```
edgedb> create database edgedb;
Error: DuplicateDatabaseDefinitionError: database "V2f0ec3dce0_edgedb" already exists
```



Discussion:

Resolving patch:
diff --git a/edb/server/server.py b/edb/server/server.py
--- a/edb/server/server.py
+++ b/edb/server/server.py
@@ -259,6 +259,9 @@ def get_listen_port(self):
     def get_loop(self):
         return self.__loop
 
+    def get_tenant_id(self):
+        return self._tenant_id
+
     def in_dev_mode(self):
         return self._devmode
 


Test patch:
diff --git a/tests/test_database.py b/tests/test_database.py
--- a/tests/test_database.py
+++ b/tests/test_database.py
@@ -60,3 +60,17 @@ async def test_database_create_02(self):
                 r'characters are not supported'):
             await self.con.execute(
                 f'CREATE DATABASE mytestdb_{"x" * s_def.MAX_NAME_LENGTH};')
+
+    async def test_database_create_03(self):
+        if not self.has_create_database:
+            self.skipTest("create database is not supported by the backend")
+
+        await self.con.execute('CREATE DATABASE databasename;')
+
+        try:
+            with self.assertRaisesRegex(
+                    edgedb.DuplicateDatabaseDefinitionError,
+                    r'database "databasename" already exists'):
+                await self.con.execute('CREATE DATABASE databasename;')
+        finally:
+            await self.con.execute('DROP DATABASE databasename;')
Repository: edgedb/edgedb

Issue:
Incorrect cardinality inference on update
A cardinality inference bug in `update` queries. Using the [query builder schema](https://github.com/edgedb/edgedb-js/blob/master/qb/dbschema/default.esdl) the following query has inferred cardinality `Many`:

```
WITH
  __scope_0_Hero := DETACHED default::Hero
UPDATE __scope_0_Hero
FILTER (__scope_0_Hero.name = "Spider-Man")
SET {
  name := ("The Amazing " ++ __scope_0_Hero.name)
}
```

Though `Hero.name` has an exclusive constraint. Regression possibly introduced in https://github.com/edgedb/edgedb/pull/3585.


Discussion:
It is indeed a regression from #3585

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
@@ -835,7 +835,7 @@ def _is_ptr_or_self_ref(
         return (
             isinstance(srccls, s_objtypes.ObjectType)
             and (
-                env.set_types[ir_set] == srccls
+                ir_expr.path_id == result_expr.path_id
                 or (
                     (rptr := ir_set.rptr) is not None
                     and isinstance(rptr.ptrref, irast.PointerRef)
@@ -888,7 +888,7 @@ def extract_filters(
                         _ptr = left_stype.getptr(schema, sn.UnqualName('id'))
                         ptrs.append(_ptr)
                     else:
-                        while env.set_types[left] != result_stype:
+                        while left.path_id != result_set.path_id:
                             assert left.rptr is not None
                             _ptr = env.schema.get(left.rptr.ptrref.name,
                                                   type=s_pointers.Pointer)


Test patch:
diff --git a/tests/test_edgeql_ir_card_inference.py b/tests/test_edgeql_ir_card_inference.py
--- a/tests/test_edgeql_ir_card_inference.py
+++ b/tests/test_edgeql_ir_card_inference.py
@@ -931,3 +931,34 @@ def test_edgeql_ir_card_inference_106(self):
 % OK %
         AT_MOST_ONE
         """
+
+    def test_edgeql_ir_card_inference_107(self):
+        """
+        WITH
+          __scope_0_Hero := DETACHED default::User
+        UPDATE __scope_0_Hero
+        FILTER (__scope_0_Hero.name = "Spider-Man")
+        SET {
+          name := ("The Amazing " ++ __scope_0_Hero.name)
+        }
+% OK %
+        AT_MOST_ONE
+        """
+
+    def test_edgeql_ir_card_inference_108(self):
+        """
+        WITH
+          __scope_0_Hero := DETACHED default::User
+        SELECT __scope_0_Hero
+        FILTER (__scope_0_Hero.name = "Spider-Man")
+% OK %
+        AT_MOST_ONE
+        """
+
+    def test_edgeql_ir_card_inference_109(self):
+        """
+        select User
+        filter (detached (select User limit 1)).name = 'Alice'
+% OK %
+        MANY
+        """
Repository: edgedb/edgedb

Issue:
`set module` is not fully rolled back with compiled query
<!-- Please search existing issues to avoid creating duplicates. -->
- EdgeDB Version: 2.0-dev.6420+local
- OS Version: macOS

Steps to Reproduce:

```
edgedb> start transaction;
OK: START TRANSACTION
edgedb[tx]> set module t2;
OK: SET ALIAS
edgedb[tx]> select AAA {};
{}
edgedb[tx]> rollback;
OK: ROLLBACK TRANSACTION
edgedb> select AAA {};
{}
```

The final `select` is expected to result like this:

```
edgedb> select AAA {a:=1};
error: InvalidReferenceError: object type or alias 'default::AAA' does not exist
  ┌─ query:1:8
  │
1 │ select AAA {a:=1};
  │        ^^^ error
```

Schema:

```
module t2 {
    type AAA {}
}
```


Discussion:
I took a look at this, and it seems the problem is a little fiddlier than that; `set module` does get fully rolled back, but the query still hits the query cache, and so never goes to the compiler, which would fail

Resolving patch:
diff --git a/edb/server/compiler/compiler.py b/edb/server/compiler/compiler.py
--- a/edb/server/compiler/compiler.py
+++ b/edb/server/compiler/compiler.py
@@ -1877,8 +1877,7 @@ def _try_compile(
                 if comp.requires_restart:
                     unit.config_requires_restart = True
 
-                if ctx.state.current_tx().is_implicit():
-                    unit.modaliases = ctx.state.current_tx().get_modaliases()
+                unit.modaliases = ctx.state.current_tx().get_modaliases()
 
                 if comp.config_op is not None:
                     unit.config_ops.append(comp.config_op)


Test patch:
diff --git a/tests/test_server_proto.py b/tests/test_server_proto.py
--- a/tests/test_server_proto.py
+++ b/tests/test_server_proto.py
@@ -464,6 +464,35 @@ async def test_server_proto_set_reset_alias_05(self):
                 SELECT foo::len('aaa')
             ''')
 
+    async def test_server_proto_set_reset_alias_06(self):
+        await self.con.query('START TRANSACTION')
+
+        await self.con.execute('''
+            SET MODULE test;
+        ''')
+        await self.con.query('select Tmp2')
+        await self.con.query('ROLLBACK')
+
+        with self.assertRaises(edgedb.InvalidReferenceError):
+            await self.con.query('select Tmp2')
+
+    async def test_server_proto_set_reset_alias_07(self):
+        await self.con.query('START TRANSACTION')
+
+        await self.con.execute('''
+            SET MODULE test;
+        ''')
+        await self.con.query('select Tmp2')
+
+        await self.con.execute('''
+            SET MODULE default;
+        ''')
+
+        with self.assertRaises(edgedb.InvalidReferenceError):
+            await self.con.query('select Tmp2')
+
+        await self.con.query('ROLLBACK')
+
     async def test_server_proto_basic_datatypes_01(self):
         for _ in range(10):
             self.assertEqual(