crbench//

← all cases

Fixed #36273 -- Moved Index system checks from Model to Index.check().

Tier 2 easy python · local · real merged PR from django/django #8638d8bf74c1a58302c97d4436ad2eb08438145b

Ground-truth defects

d1 · correctness · high
In the new Index.check() (django/db/models/indexes.py), the local-field validation passes the raw self.fields set to model._check_local_fields: "{*self.fields, *self.include, *references}". self.fields keeps the leading "-" descending-ordering prefix, whereas the old Model._check_indexes built the field list from index.fields_orders (which strips the prefix). So an index declared with a descending field, e.g. Index(fields=["-author"]), is looked up as "-author", fails to match the real "author" field, and raises a spurious models.E012 ("indexes refers to the nonexistent field -author") on a perfectly valid model.
d2 · correctness · medium
The database-feature warnings moved into Index.check() (W037/W040/W043 in django/db/models/indexes.py) keep iterating over the whole model with "any(... for index in model._meta.indexes)" even though check() now runs once per index. For W040 it tests "any(index.include for index in model._meta.indexes)" and for W043 "any(index.contains_expressions for index in model._meta.indexes)", so when any single index on the model triggers the condition the warning is emitted once for every index on the model instead of once. (W037 likewise ignores its loop variable, testing "any(self.condition is not None for index in ...)".) The result is duplicate W037/W040/W043 warnings proportional to the number of indexes on the model.

The change under review

diff
diff --git a/django/db/models/base.py b/django/db/models/base.py
index eaedd4874896..72ba0471a44e 100644
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -2115,93 +2115,13 @@ def _check_unique_together(cls):
 
     @classmethod
     def _check_indexes(cls, databases):
-        """Check fields, names, and conditions of indexes."""
         errors = []
-        references = set()
-        for index in cls._meta.indexes:
-            # Index name can't start with an underscore or a number, restricted
-            # for cross-database compatibility with Oracle.
-            if index.name[0] == "_" or index.name[0].isdigit():
-                errors.append(
-                    checks.Error(
-                        "The index name '%s' cannot start with an underscore "
-                        "or a number." % index.name,
-                        obj=cls,
-                        id="models.E033",
-                    ),
-                )
-            if len(index.name) > index.max_name_length:
-                errors.append(
-                    checks.Error(
-                        "The index name '%s' cannot be longer than %d "
-                        "characters." % (index.name, index.max_name_length),
-                        obj=cls,
-                        id="models.E034",
-                    ),
-                )
-            if index.contains_expressions:
-                for expression in index.expressions:
-                    references.update(
-                        ref[0] for ref in cls._get_expr_references(expression)
-                    )
         for db in databases:
             if not router.allow_migrate_model(db, cls):
                 continue
             connection = connections[db]
-            if not (
-                connection.features.supports_partial_indexes
-                or "supports_partial_indexes" in cls._meta.required_db_features
-            ) and any(index.condition is not None for index in cls._meta.indexes):
-                errors.append(
-                    checks.Warning(
-                        "%s does not support indexes with conditions."
-                        % connection.display_name,
-                        hint=(
-                            "Conditions will be ignored. Silence this warning "
-                            "if you don't care about it."
-                        ),
-                        obj=cls,
-                        id="models.W037",
-                    )
-                )
-            if not (
-                connection.features.supports_covering_indexes
-                or "supports_covering_indexes" in cls._meta.required_db_features
-            ) and any(index.include for index in cls._meta.indexes):
-                errors.append(
-                    checks.Warning(
-                        "%s does not support indexes with non-key columns."
-                        % connection.display_name,
-                        hint=(
-                            "Non-key columns will be ignored. Silence this "
-                            "warning if you don't care about it."
-                        ),
-                        obj=cls,
-                        id="models.W040",
-                    )
-                )
-            if not (
-                connection.features.supports_expression_indexes
-                or "supports_expression_indexes" in cls._meta.required_db_features
-            ) and any(index.contains_expressions for index in cls._meta.indexes):
-                errors.append(
-                    checks.Warning(
-                        "%s does not support indexes on expressions."
-                        % connection.display_name,
-                        hint=(
-                            "An index won't be created. Silence this warning "
-                            "if you don't care about it."
-                        ),
-                        obj=cls,
-                        id="models.W043",
-                    )
-                )
-        fields = [
-            field for index in cls._meta.indexes for field, _ in index.fields_orders
-        ]
-        fields += [include for index in cls._meta.indexes for include in index.include]
-        fields += references
-        errors.extend(cls._check_local_fields(fields, "indexes"))
+            for index in cls._meta.indexes:
+                errors.extend(index.check(cls, connection))
         return errors
 
     @classmethod
diff --git a/django/db/models/indexes.py b/django/db/models/indexes.py
index 7bea0a663a00..176f719fe568 100644
--- a/django/db/models/indexes.py
+++ b/django/db/models/indexes.py
@@ -1,5 +1,6 @@
 from types import NoneType
 
+from django.core import checks
 from django.db.backends.utils import names_digest, split_identifier
 from django.db.models.expressions import Col, ExpressionList, F, Func, OrderBy
 from django.db.models.functions import Collate
@@ -82,6 +83,92 @@ def __init__(
     def contains_expressions(self):
         return bool(self.expressions)
 
+    def check(self, model, connection):
+        """Check fields, names, and conditions of indexes."""
+        errors = []
+        # Index name can't start with an underscore or a number (restricted
+        # for cross-database compatibility with Oracle)
+        if self.name[0] == "_" or self.name[0].isdigit():
+            errors.append(
+                checks.Error(
+                    "The index name '%s' cannot start with an underscore "
+                    "or a number." % self.name,
+                    obj=model,
+                    id="models.E033",
+                ),
+            )
+        if len(self.name) > self.max_name_length:
+            errors.append(
+                checks.Error(
+                    "The index name '%s' cannot be longer than %d "
+                    "characters." % (self.name, self.max_name_length),
+                    obj=model,
+                    id="models.E034",
+                ),
+            )
+        references = set()
+        if self.contains_expressions:
+            for expression in self.expressions:
+                references.update(
+                    ref[0] for ref in model._get_expr_references(expression)
+                )
+        errors.extend(
+            model._check_local_fields(
+                {*self.fields, *self.include, *references}, "indexes"
+            )
+        )
+        # Database-feature checks:
+        required_db_features = model._meta.required_db_features
+        if not (
+            connection.features.supports_partial_indexes
+            or "supports_partial_indexes" in required_db_features
+        ) and any(self.condition is not None for index in model._meta.indexes):
+            errors.append(
+                checks.Warning(
+                    "%s does not support indexes with conditions."
+                    % connection.display_name,
+                    hint=(
+                        "Conditions will be ignored. Silence this warning "
+                        "if you don't care about it."
+                    ),
+                    obj=model,
+                    id="models.W037",
+                )
+            )
+        if not (
+            connection.features.supports_covering_indexes
+            or "supports_covering_indexes" in required_db_features
+        ) and any(index.include for index in model._meta.indexes):
+            errors.append(
+                checks.Warning(
+                    "%s does not support indexes with non-key columns."
+                    % connection.display_name,
+                    hint=(
+                        "Non-key columns will be ignored. Silence this "
+                        "warning if you don't care about it."
+                    ),
+                    obj=model,
+                    id="models.W040",
+                )
+            )
+        if not (
+            connection.features.supports_expression_indexes
+            or "supports_expression_indexes" in required_db_features
+        ) and any(index.contains_expressions for index in model._meta.indexes):
+            errors.append(
+                checks.Warning(
+                    "%s does not support indexes on expressions."
+                    % connection.display_name,
+                    hint=(
+                        "An index won't be created. Silence this warning "
+                        "if you don't care about it."
+                    ),
+                    obj=model,
+                    id="models.W043",
+                )
+            )
+        return errors
+
     def _get_condition_sql(self, model, schema_editor):
         if self.condition is None:
             return None
diff --git a/tests/invalid_models_tests/test_models.py b/tests/invalid_models_tests/test_models.py
index c44fe56f8937..faa0db9da7bd 100644
--- a/tests/invalid_models_tests/test_models.py
+++ b/tests/invalid_models_tests/test_models.py
@@ -175,7 +175,7 @@ class Meta:
                 indexes = [models.Index(fields=["missing_field"], name="name")]
 
         self.assertEqual(
-            Model.check(),
+            Model.check(databases=self.databases),
             [
                 Error(
                     "'indexes' refers to the nonexistent field 'missing_field'.",
@@ -193,7 +193,7 @@ class Meta:
                 indexes = [models.Index(fields=["m2m"], name="name")]
 
         self.assertEqual(
-            Model.check(),
+            Model.check(databases=self.databases),
             [
                 Error(
                     "'indexes' refers to a ManyToManyField 'm2m', but "
@@ -215,7 +215,7 @@ class Meta:
                 indexes = [models.Index(fields=["field2", "field1"], name="name")]
 
         self.assertEqual(
-            Bar.check(),
+            Bar.check(databases=self.databases),
             [
                 Error(
                     "'indexes' refers to field 'field1' which is not local to "
@@ -244,7 +244,7 @@ class Meta:
                     models.Index(fields=["foo_1_id", "foo_2"], name="index_name")
                 ]
 
-        self.assertEqual(Bar.check(), [])
+        self.assertEqual(Bar.check(databases=self.databases), [])
 
     def test_pointing_to_composite_primary_key(self):
         class Model(models.Model):
@@ -256,7 +256,7 @@ class Meta:
                 indexes = [models.Index(fields=["pk", "name"], name="name")]
 
         self.assertEqual(
-            Model.check(),
+            Model.check(databases=self.databases),
             [
                 Error(
                     "'indexes' refers to a CompositePrimaryKey 'pk', but "
@@ -276,7 +276,7 @@ class Meta:
                 ]
 
         self.assertEqual(
-            Model.check(),
+            Model.check(databases=self.databases),
             [
                 Error(
                     "The index name '%sindex_name' cannot start with an "
@@ -296,7 +296,7 @@ class Meta:
                 indexes = [models.Index(fields=["id"], name=index_name)]
 
         self.assertEqual(
-            Model.check(),
+            Model.check(databases=self.databases),
             [
                 Error(
                     "The index name '%s' cannot be longer than 30 characters."
@@ -499,7 +499,7 @@ class Meta:
                 indexes = [models.Index(fields=["name"], include=["pk"], name="name")]
 
         self.assertEqual(
-            Model.check(),
+            Model.check(databases=self.databases),
             [
                 Error(
                     "'indexes' refers to a CompositePrimaryKey 'pk', but "
@@ -539,6 +539,7 @@ class Meta:
 
         self.assertEqual(Model.check(databases=self.databases), [])
 
+    @skipUnlessDBFeature("supports_expression_indexes")
     def test_func_index_complex_expression_custom_lookup(self):
         class Model(models.Model):
             height = models.IntegerField()
@@ -554,15 +555,16 @@ class Meta:
                 ]
 
         with register_lookup(models.IntegerField, Abs):
-            self.assertEqual(Model.check(), [])
+            self.assertEqual(Model.check(databases=self.databases), [])
 
+    @skipUnlessDBFeature("supports_expression_indexes")
     def test_func_index_pointing_to_missing_field(self):
         class Model(models.Model):
             class Meta:
                 indexes = [models.Index(Lower("missing_field").desc(), name="name")]
 
         self.assertEqual(
-            Model.check(),
+            Model.check(databases=self.databases),
             [
                 Error(
                     "'indexes' refers to the nonexistent field 'missing_field'.",
@@ -572,6 +574,7 @@ class Meta:
             ],
         )
 
+    @skipUnlessDBFeature("supports_expression_indexes")
     def test_func_index_pointing_to_missing_field_nested(self):
         class Model(models.Model):
             class Meta:
@@ -580,7 +583,7 @@ class Meta:
                 ]
 
         self.assertEqual(
-            Model.check(),
+            Model.check(databases=self.databases),
             [
                 Error(
                     "'indexes' refers to the nonexistent field 'missing_field'.",
@@ -590,6 +593,7 @@ class Meta:
             ],
         )
 
+    @skipUnlessDBFeature("supports_expression_indexes")
     def test_func_index_pointing_to_m2m_field(self):
         class Model(models.Model):
             m2m = models.ManyToManyField("self")
@@ -598,7 +602,7 @@ class Meta:
                 indexes = [models.Index(Lower("m2m"), name="name")]
 
         self.assertEqual(
-            Model.check(),
+            Model.check(databases=self.databases),
             [
                 Error(
                     "'indexes' refers to a ManyToManyField 'm2m', but "
@@ -609,6 +613,7 @@ class Meta:
             ],
         )
 
+    @skipUnlessDBFeature("supports_expression_indexes")
     def test_func_index_pointing_to_non_local_field(self):
         class Foo(models.Model):
             field1 = models.CharField(max_length=15)
@@ -618,7 +623,7 @@ class Meta:
                 indexes = [models.Index(Lower("field1"), name="name")]
 
         self.assertEqual(
-            Bar.check(),
+            Bar.check(databases=self.databases),
             [
                 Error(
                     "'indexes' refers to field 'field1' which is not local to "
@@ -630,6 +635,7 @@ class Meta:
             ],
         )
 
+    @skipUnlessDBFeature("supports_expression_indexes")
     def test_func_index_pointing_to_fk(self):
         class Foo(models.Model):
             pass
@@ -643,8 +649,9 @@ class Meta:
                     models.Index(Lower("foo_1_id"), Lower("foo_2"), name="index_name"),
                 ]
 
-        self.assertEqual(Bar.check(), [])
+        self.assertEqual(Bar.check(databases=self.databases), [])
 
+    @skipUnlessDBFeature("supports_expression_indexes")
     def test_func_index_pointing_to_composite_primary_key(self):
         class Model(models.Model):
             pk = models.CompositePrimaryKey("version", "name")
@@ -655,7 +662,7 @@ class Meta:
                 indexes = [models.Index(Abs("pk"), name="name")]
 
         self.assertEqual(
-            Model.check(),
+            Model.check(databases=self.databases),
             [
                 Error(
                     "'indexes' refers to a CompositePrimaryKey 'pk', but "

Leaderboard for this case

easy · 8 of 9 bots fully caught it (89% solve rate) · 94% avg coverage.

#BotResultCaughtCoverageFindingsFalse alarms
1 Claude Code (Opus 5.5) solved 2/2 100.0% 4 0
2 Cubic solved 2/2 100.0% 3 0
3 cursor solved 2/2 100.0% 2 0
4 Drape (Deep Review) solved 2/2 100.0% 7 0
5 Drape (Review) solved 2/2 100.0% 4 0
6 greptile solved 2/2 100.0% 4 0
7 Mjolnir (Opus 5.5) solved 2/2 100.0% 7 0
8 Mjolnir (Sonnet 5.5) solved 2/2 100.0% 6 0
9 qodo partial 1/2 33.3% 2 0

Bot results

Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 high ✓ exact
d2 medium ✓ exact
valid · impact high
Before the change, the E033/E034 name checks and the `_check_local_fields` call ran outside the `for db in databases` loop. Now everything goes through `index.check(cls, connection)` inside that loop, and `Model.check()` turns a missing `databases` into `[]`, so with no databases these checks never run. The test edits that add `databases=self.databases` hide this. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The name and field checks used to run once per model. They now run once for every database the model is allowed on, so a model routed to several databases gets the same E033/E034/E012 errors repeated. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d1 · impact high
valid · matches d2 · impact medium
raw comments (4)
django/db/models/base.py:2123
`_check_indexes` now runs every index check, including the database-independent ones, only inside the `for db in databases` loop. `Model.check()` turns a missing `databases` argument into an empty list, so with no databases (for example a plain `Model.check()` or `manage.py check` without database tags) the loop never runs. That silently drops the E033/E034 name checks and the nonexistent, M2M, non-local and composite-pk field checks (E012/E013/E016). The test changes that add `databases=self.databases` hide this regression.
django/db/models/base.py:2124
Name and field errors (E033, E034, E012, etc.) used to be reported once. They are now produced once per database because `index.check()` runs for each allowed database. With several databases configured, users get duplicate errors.
django/db/models/indexes.py:118
The field check uses `self.fields`, which keeps the '-' prefix for descending fields. The old code used `fields_orders`, which strips it. A valid index such as `Index(fields=['-name'], name='idx')` now fails with "'indexes' refers to the nonexistent field '-name'" (models.E012).
django/db/models/indexes.py:125
`any(self.condition is not None for index in model._meta.indexes)` is a mix of per-index and per-model logic. The generator ignores `index` and only tests `self`. More generally, each index's `check()` evaluates model-wide conditions. W040 (`any(index.include ...)`) and W043 (`any(index.contains_expressions ...)`) are now emitted once per index on the model, not once per database. For example, a model with 3 indexes where only one has `include` gets 3 identical W040 warnings.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 high ✓ off by one
d2 medium ✓ exact
valid · impact medium
Before the change, the name (E033/E034) and local-field checks ran outside the per-database loop. They now run inside it, so `Model.check()` with no databases (`databases` defaults to []) or with every alias rejected by the router skips them entirely, and several allowed aliases repeat them. The tests had to be changed to pass `databases=self.databases`, which confirms the regression. [grounded: diff] [consensus 5/5: valid=5]
valid · matches d2 · impact medium
valid · matches d1 · impact high
raw comments (4)
django/db/models/base.py:2124
<!-- cubic:v=9551eb51-0e0d-4a38-9b3f-de19d133759a --> <!-- cubic:review-run=74d44118-966d-58f7-bdce-393c4fed9f8e --> <!-- metadata:{"confidence":10} --> P2: When `Model.check()` has no databases, or routers reject every alias, this loop skips structural index validation; with multiple allowed aliases, it reports the same structural errors once per alias. Keep name, expression-reference, and local-field validation outside the database loop, and run only database-feature checks per connection. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At django/db/models/base.py, line 2124: <comment>When `Model.check()` has no databases, or routers reject every alias, this loop skips structural index validation; with multiple allowed aliases, it reports the same structural errors once per alias. Keep name, expression-reference, and local-field validation outside the database loop, and run only database-feature checks per connection.</comment> <file context> @@ -2115,93 +2115,13 @@ def _check_unique_together(cls): - fields += references - errors.extend(cls._check_local_fields(fields, "indexes")) + for index in cls._meta.indexes: + errors.extend(index.check(cls, connection)) return errors </file context> ``` </details>
django/db/models/indexes.py:125
<!-- cubic:v=0da3aeca-8760-4da9-a456-de058f7cf656 --> <!-- cubic:review-run=74d44118-966d-58f7-bdce-393c4fed9f8e --> <!-- metadata:{"confidence":9} --> P2: When a model has multiple indexes, these model-wide feature checks emit duplicate warnings because `Model._check_indexes()` invokes `check()` once per index. Emit each feature warning once at model level, or make each check apply only to `self` (and use the iterated `index` value consistently). <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At django/db/models/indexes.py, line 125: <comment>When a model has multiple indexes, these model-wide feature checks emit duplicate warnings because `Model._check_indexes()` invokes `check()` once per index. Emit each feature warning once at model level, or make each check apply only to `self` (and use the iterated `index` value consistently).</comment> <file context> @@ -82,6 +83,92 @@ def __init__( + if not ( + connection.features.supports_partial_indexes + or "supports_partial_indexes" in required_db_features + ) and any(self.condition is not None for index in model._meta.indexes): + errors.append( + checks.Warning( </file context> ``` </details>
django/db/models/indexes.py:117
<!-- cubic:v=ee338535-ee45-43c5-bcec-1b8892b406fa --> <!-- cubic:review-run=74d44118-966d-58f7-bdce-393c4fed9f8e --> <!-- metadata:{"confidence":10} --> P2: An index using descending syntax such as `fields=["-created_at"]` now fails model checks with `models.E012` because this passes the raw `-created_at` string to `_check_local_fields()`. Validate the normalized field names from `fields_orders`, which is also what index creation uses. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At django/db/models/indexes.py, line 117: <comment>An index using descending syntax such as `fields=["-created_at"]` now fails model checks with `models.E012` because this passes the raw `-created_at` string to `_check_local_fields()`. Validate the normalized field names from `fields_orders`, which is also what index creation uses.</comment> <file context> @@ -82,6 +83,92 @@ def __init__( + ) + errors.extend( + model._check_local_fields( + {*self.fields, *self.include, *references}, "indexes" + ) + ) </file context> ``` </details> ```suggestion {field for field, _ in self.fields_orders} | set(self.include) | references, "indexes" ```
PR-level
<!-- cubic:review-summary:start --> **3 issues found** across 3 files <!-- cubic:review-summary:end --> <details> <summary>Prompt for AI agents (unresolved issues)</summary> ```text Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately. <file name="django/db/models/base.py"> <violation number="1" location="django/db/models/base.py:2124"> P2: When `Model.check()` has no databases, or routers reject every alias, this loop skips structural index validation; with multiple allowed aliases, it reports the same structural errors once per alias. Keep name, expression-reference, and local-field validation outside the database loop, and run only database-feature checks per connection.</violation> </file> <file name="django/db/models/indexes.py"> <violation number="1" location="django/db/models/indexes.py:117"> P2: An index using descending syntax such as `fields=["-created_at"]` now fails model checks with `models.E012` because this passes the raw `-created_at` string to `_check_local_fields()`. Validate the normalized field names from `fields_orders`, which is also what index creation uses.</violation> <violation number="2" location="django/db/models/indexes.py:125"> P2: When a model has multiple indexes, these model-wide feature checks emit duplicate warnings because `Model._check_indexes()` invokes `check()` once per index. Emit each feature warning once at model level, or make each check apply only to `self` (and use the iterated `index` value consistently).</violation> </file> ``` </details> <sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/36/ai_pr_review_github_delivery_e34e4eadd2d23df307f23e7fe343aa11e1dda0d2c8a725352e0212150e51cbc2?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F36)</sub> <!-- cubic:review-post:ai_pr_review_github_delivery_e34e4eadd2d23df307f23e7fe343aa11e1dda0d2c8a725352e0212150e51cbc2:1593a3898a08314f2590f5ab8897dbdba1bb393e:74d44118-966d-58f7-bdce-393c4fed9f8e -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 high ✓ exact
d2 medium ✓ exact
valid · matches d1 · impact high
valid · matches d2 · impact medium
raw comments (3)
django/db/models/indexes.py:119
### Descending index fields fail checks **High Severity** <!-- DESCRIPTION START --> Field validation now passes `self.fields` into `_check_local_fields` instead of the stripped names from `self.fields_orders`. Descending entries keep the `-` prefix, so valid indexes are reported as referring to a nonexistent field via `models.E012`. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: 19904490-d066-40b8-a5b3-8c8176f50d73 --> <!-- LOCATIONS START django/db/models/indexes.py#L114-L119 LOCATIONS END --> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90Ojk4ZTNjNDgwLWRhMDMtNDRiNC1hM2M2LTU0ZDE2ZDFlOWZkMiIsImVuY3J5cHRpb25LZXkiOiIxMjJSUVR4ZWRiRXAzU0JMMWMzNEtaNjh0QzRIMGVPQzFyU01xSGZOc2JNIiwiYnJhbmNoIjoidDItZGphbmdvLTM2MjczIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90Ojk4ZTNjNDgwLWRhMDMtNDRiNC1hM2M2LTU0ZDE2ZDFlOWZkMiIsImVuY3J5cHRpb25LZXkiOiIxMjJSUVR4ZWRiRXAzU0JMMWMzNEtaNjh0QzRIMGVPQzFyU01xSGZOc2JNIiwiYnJhbmNoIjoidDItZGphbmdvLTM2MjczIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6MzcsImNvbW1pdFNoYSI6IjdkOTJiMzgwNWIzZWI4M2RmZGM3M2QwZTQyNDBjMDQ4YWZhMzc0NmUiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 7d92b3805b3eb83dfdc73d0e4240c048afa3746e. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
django/db/models/indexes.py:169
### Index warnings duplicate across indexes **Medium Severity** <!-- DESCRIPTION START --> Covering-index and expression-index warnings still use `any(...)` over `model._meta.indexes` after the check moved onto each `Index`. If any index uses `include` or expressions, every index on the model emits `models.W040` or `models.W043`. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: 37d1913c-5854-4032-ba0d-e843ecefba7d --> <!-- LOCATIONS START django/db/models/indexes.py#L137-L169 LOCATIONS END --> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmJiNDA4NjhiLWIyOWMtNGZkYi05OGNmLTljYTI5NDI1OGIwMCIsImVuY3J5cHRpb25LZXkiOiJyeGRnNGc5eFpoQWJuZThUSlRVUVhBclRCWFhURDdxM1BrQnJCLWk1Y05RIiwiYnJhbmNoIjoidDItZGphbmdvLTM2MjczIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmJiNDA4NjhiLWIyOWMtNGZkYi05OGNmLTljYTI5NDI1OGIwMCIsImVuY3J5cHRpb25LZXkiOiJyeGRnNGc5eFpoQWJuZThUSlRVUVhBclRCWFhURDdxM1BrQnJCLWk1Y05RIiwiYnJhbmNoIjoidDItZGphbmdvLTM2MjczIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6MzcsImNvbW1pdFNoYSI6IjdkOTJiMzgwNWIzZWI4M2RmZGM3M2QwZTQyNDBjMDQ4YWZhMzc0NmUiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 7d92b3805b3eb83dfdc73d0e4240c048afa3746e. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
PR-level
<!-- BUGBOT_REVIEW --> Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues. <!-- BUGBOT_FIX_ALL --> <a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTozZGFlMzVlNy1jOTg5LTRkNDktOTY4ZS1mYjVlYmM0NmY2YmMiLCJlbmNyeXB0aW9uS2V5IjoidTZoUTZUaWdMVkctSy1SdUF5Z3V4RUJZYlVrcEszaDkxZGJobEktMzFFRSIsImJyYW5jaCI6InQyLWRqYW5nby0zNjI3MyIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <!-- /BUGBOT_FIX_ALL --> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN --> <sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END --> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 7d92b3805b3eb83dfdc73d0e4240c048afa3746e. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 high ✓ exact
d2 medium ✓ exact
valid · impact medium
Name/field checks previously ran once outside the db loop; now Index.check (which includes them) runs per database, duplicating errors with multiple databases. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d1 · impact high
valid · matches d2 · impact medium
valid · impact low
The model-wide any() is evaluated inside each index's check, so W043 is emitted once per index rather than once per model/db as before. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The old code passed an ordered list; a set of strings has hash-randomized iteration order, so error order is nondeterministic across runs. [grounded: diff] [consensus 3/3: valid=3]
valid · impact high
All index checks now live inside the databases loop; with no databases (default check()), name and field errors are no longer reported. Tests had to be changed to pass databases. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The check runs per index and tests self.condition, so each conditional index adds its own W037, whereas previously the warning was emitted once per model per db. [grounded: diff] [consensus 3/3: valid=3]
raw comments (7)
django/db/models/base.py:2125
**Index errors duplicated for every database** With several databases, name and field errors (E033, E034, E012…) are emitted once per database because `index.check` is called inside the database loop. Separate database-independent checks from per-connection feature checks. ``` django/db/models/base.py:2121 continue django/db/models/base.py:2122 connection = connections[db] django/db/models/base.py:2123 for index in cls._meta.indexes: django/db/models/base.py:2124 errors.extend(index.check(cls, connection)) django/db/models/indexes.py:86 def check(self, model, connection): django/db/models/indexes.py:87 """Check fields, names, and conditions of indexes.""" django/db/models/indexes.py:88 errors = [] django/db/models/indexes.py:89 # Index name can't start with an underscore or a number (restricted django/db/models/indexes.py:90 # for cross-database compatibility with Oracle) django/db/models/indexes.py:91 if self.name[0] == "_" or self.name[0].isdigit(): ```
django/db/models/indexes.py:117
**Descending index fields reported as nonexistent** `self.fields` keeps the '-' prefix for descending fields, so `Index(fields=['-name'])` is checked as field '-name'. The old code used `fields_orders`, which strips it. Use `field for field, _ in self.fields_orders`. ``` django/db/models/indexes.py:115 errors.extend( django/db/models/indexes.py:116 model._check_local_fields( django/db/models/indexes.py:117 {*self.fields, *self.include, *references}, "indexes" django/db/models/indexes.py:118 ) django/db/models/indexes.py:66 self.fields = list(fields) django/db/models/indexes.py:67 # A list of 2-tuple with the field name and ordering ('' or 'DESC'). django/db/models/indexes.py:68 self.fields_orders = [ django/db/models/indexes.py:69 (field_name.removeprefix("-"), "DESC" if field_name.startswith("-") else "") django/db/models/indexes.py:70 for field_name in self.fields django/db/models/indexes.py:71 ] ```
django/db/models/indexes.py:141
**Covering-index warning emitted once per index** `any(index.include for index in model._meta.indexes)` checks the whole model and runs once for each index. If any index has `include`, every index adds its own W040, so the warning is duplicated N times. Test `self.include` only. ``` django/db/models/indexes.py:138 if not ( django/db/models/indexes.py:139 connection.features.supports_covering_indexes django/db/models/indexes.py:140 or "supports_covering_indexes" in required_db_features django/db/models/indexes.py:141 ) and any(index.include for index in model._meta.indexes): ```
django/db/models/indexes.py:157
**Expression-index warning emitted once per index** `any(index.contains_expressions for index in model._meta.indexes)` checks the whole model and runs once for each index. So W043 is repeated once per index whenever any index uses expressions. Test `self.contains_expressions` only. ``` django/db/models/indexes.py:154 if not ( django/db/models/indexes.py:155 connection.features.supports_expression_indexes django/db/models/indexes.py:156 or "supports_expression_indexes" in required_db_features django/db/models/indexes.py:157 ) and any(index.contains_expressions for index in model._meta.indexes): ```
django/db/models/indexes.py:116
**Field error order is nondeterministic** The field names are passed to `_check_local_fields` as a set. With string hash randomization, errors for several bad fields come out in a different order on each run, where they used to follow declaration order. Use a list, or dict.fromkeys to remove duplicates, so declaration order is kept. ``` django/db/models/indexes.py:114 ) django/db/models/indexes.py:115 errors.extend( django/db/models/indexes.py:116 model._check_local_fields( django/db/models/indexes.py:117 {*self.fields, *self.include, *references}, "indexes" ```
django/db/models/base.py:2124
**Index name and field checks skipped without databases** All index checks now run inside the per-database loop. A plain `manage.py check` or `runserver` passes no databases, so bad index names and missing, M2M or non-local fields are never reported. Keep the name and field checks outside the `databases` loop. ``` django/db/models/base.py:2118 errors = [] django/db/models/base.py:2119 for db in databases: django/db/models/base.py:2120 if not router.allow_migrate_model(db, cls): django/db/models/base.py:2121 continue django/db/models/base.py:1675 databases = kwargs.get("databases") or [] django/db/models/indexes.py:89 # Index name can't start with an underscore or a number (restricted django/db/models/indexes.py:90 # for cross-database compatibility with Oracle) django/db/models/indexes.py:91 if self.name[0] == "_" or self.name[0].isdigit(): django/db/models/indexes.py:92 errors.append( django/db/models/indexes.py:93 checks.Error( ```
django/db/models/indexes.py:125
**W037 repeated for each conditional index** On a backend without partial indexes, each conditional index adds its own W037, because Index.check runs once per index. A model with two conditional indexes gets the warning twice per database instead of once. Emit this model-level warning once, in Model._check_indexes. ``` django/db/models/indexes.py:121 required_db_features = model._meta.required_db_features django/db/models/indexes.py:122 if not ( django/db/models/indexes.py:123 connection.features.supports_partial_indexes django/db/models/indexes.py:124 or "supports_partial_indexes" in required_db_features django/db/models/indexes.py:125 ) and any(self.condition is not None for index in model._meta.indexes): ```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 high ✓ exact
d2 medium ✓ off by one
valid · matches d1 · impact high
valid · matches d2 · impact medium
valid · impact high
The removed code ran E033/E034 and the field-reference checks once, outside the database loop. Now `Index.check` (which includes those checks) runs only inside `for db in databases`. So `Model.check()` with no databases skips them entirely, and with several migratable databases they repeat once per database. The tests had to be changed to pass `databases=` to keep passing. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
Before the change, a list was passed in declaration order. Now it is a set of strings, and string hashing is randomized per process, so the order of several E012/E013 errors can differ between runs. A field listed in both fields and include is also now reported once instead of twice. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
django/db/models/indexes.py:117
**Descending index fields reported as nonexistent** `Index.check` validates `self.fields`, which keeps the '-' prefix for descending fields (e.g. '-name'). The old code validated `fields_orders`, which has the prefix stripped. Valid descending indexes now fail with E012. Use field names from self.fields_orders instead of self.fields. ``` django/db/models/indexes.py:115 errors.extend( django/db/models/indexes.py:116 model._check_local_fields( django/db/models/indexes.py:117 {*self.fields, *self.include, *references}, "indexes" django/db/models/indexes.py:118 ) ```
django/db/models/indexes.py:120
**Same feature warning repeated once per index** W040/W043 run once per index but test any() over all of the model's indexes, so one covering index among three gives W040 three times. W037 repeats once per conditional index. Check self.include and self.contains_expressions instead, or warn once per model. ``` django/db/models/indexes.py:119 ) django/db/models/indexes.py:120 # Database-feature checks: django/db/models/indexes.py:121 required_db_features = model._meta.required_db_features django/db/models/indexes.py:122 if not ( ```
django/db/models/base.py:2119
**Field checks skipped or duplicated per database** Name and field-reference checks now run inside the per-database loop. With no databases, E012/E013/E016/E033/E034 vanish; with several databases each repeats once per database. Run name and field checks once outside the database loop; keep only feature checks inside. ``` django/db/models/base.py:2119 for db in databases: django/db/models/base.py:2120 if not router.allow_migrate_model(db, cls): django/db/models/base.py:2121 continue django/db/models/base.py:2122 connection = connections[db] ```
django/db/models/indexes.py:116
**Error order and duplicates change with set** `Index.check` passes a set of field names to `_check_local_fields`. Several bad fields now come out in hash-dependent order, which varies between runs. A field listed in both fields and include is reported once instead of twice. Pass an ordered list, deduplicated with dict.fromkeys if needed. ``` django/db/models/indexes.py:115 errors.extend( django/db/models/indexes.py:116 model._check_local_fields( django/db/models/indexes.py:117 {*self.fields, *self.include, *references}, "indexes" django/db/models/indexes.py:118 ) ```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 high ✓ exact
d2 medium ✓ exact
valid · impact medium
Before the change, the name checks (E033/E034) and the field-reference checks (_check_local_fields) ran outside the `for db in databases` loop. Now they only run inside it, so `check()` with no databases (databases=[]), or a model that every router excludes, gets no index validation at all. The test edits that add `databases=self.databases` confirm this. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d1 · impact high
valid · matches d2 · impact medium
valid · impact low
These func-index reference tests used to run on every backend. Now they are skipped on backends without expression-index support, so the structural reference checks (E012/E013/E016/E048) lose coverage there. The skips are only needed because W043 would now appear on those backends. [grounded: diff] [consensus 3/4: valid=3, minor=1]
raw comments (5)
django/db/models/base.py:2124
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Index validation gets skipped** Running the standard model checks without an explicit database, or checking a model that migration routers exclude, now skips all index validation because `index.check()` is only reached inside the database loop. This suppresses database-independent errors for invalid index names and nonexistent, non-local, many-to-many, or composite-primary-key fields that were previously checked outside the loop.
django/db/models/indexes.py:118
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Descending fields fail validation** Passing `self.fields` directly to `_check_local_fields()` treats the `-` prefix of a descending index as part of the field name. A valid index such as `Index(fields=["-created_at"], ...)` is therefore checked as referring to a field literally named `-created_at` and incorrectly produces `models.E012`. The normalized names from `fields_orders` should be validated as before.
django/db/models/base.py:2124
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Feature warnings are duplicated** `_check_indexes()` invokes `Index.check()` for every index, but the unsupported-feature checks inspect the model's entire index collection. A model with multiple indexes can consequently receive duplicate W040 and W043 warnings for each index, while W037 is duplicated when multiple conditional indexes exist. These model-wide checks previously ran once per model and database, so the extra warnings add noise to check output.
tests/invalid_models_tests/test_models.py:560
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Structural tests skip backends** This feature decorator, along with those added to the related missing-field, many-to-many, non-local, foreign-key, and composite-primary-key cases, skips backend-independent expression-reference validation on databases without expression-index support. Those references remain invalid regardless of whether the backend can create the index, so the skipped coverage can hide regressions on unsupported backends. The tests should keep asserting the structural results and account separately for W043 where needed.
PR-level
<h3>Greptile Summary</h3> This PR moves model-index validation from `Model._check_indexes()` into `Index.check()` and updates invalid-model tests to supply database aliases. - Consolidates index name, field-reference, and backend-feature checks on `Index`. - Introduces regressions for database-less checks, descending field names, and warning cardinality. - Restricts several backend-independent expression validation tests to expression-index-capable databases. <h3>Confidence Score: 3/5</h3> The PR is not safe to merge because ordinary checks can omit index errors and valid descending indexes can be falsely rejected. Moving all validation behind database and router selection removes previously unconditional structural checks, while validating raw descending field strings produces erroneous nonexistent-field errors; duplicate warnings and reduced cross-backend test coverage are additional non-blocking concerns. **Files Needing Attention:** django/db/models/base.py, django/db/models/indexes.py, tests/invalid_models_tests/test_models.py <details><summary><h3>Important Files Changed</h3></summary> | Filename | Overview | |----------|----------| | django/db/models/base.py | Delegates all index checks inside the database/router loop, suppressing structural validation when no eligible database is selected and repeatedly invoking model-wide warnings. | | django/db/models/indexes.py | Adds consolidated index validation but checks descending field strings without normalization and repeats model-wide feature checks per index. | | tests/invalid_models_tests/test_models.py | Updates checks to select databases but unnecessarily skips backend-independent expression-reference cases on unsupported backends. | </details> <details open><summary><h3>Flowchart</h3></summary> ```mermaid %%{init: {'theme': 'neutral'}}%% flowchart TD A[Model.check databases] --> B{Each selected database} B --> C{Router allows migration} C -->|Yes| D{Each model index} C -->|No| E[Skip all index checks] D --> F[Index.check] F --> G[Name and field validation] F --> H[Model-wide backend feature warnings] ``` </details> <!-- greptile_other_comments_section --> <sub>Reviews (1): Last reviewed commit: ["Update django/db/models/base.py and 2 mo..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/09c178ed6a54e2e87482df4f47e56b0055d1013e) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284420)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 high ✓ exact
d2 medium ✓ exact
valid · impact high
Before this change, the E033/E034 name checks and the field checks ran outside the `for db in databases` loop. Now they run only inside it. `Model.check` sets `databases = kwargs.get("databases") or []`, so with no databases these checks never run, and with several databases they are repeated once per database. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d1 · impact high
valid · matches d2 · impact medium
valid · impact high
This is the same regression as finding 0. The name and field-reference checks were moved into the per-database loop, so they are skipped when no databases are passed and duplicated when several are. [grounded: diff] [consensus 3/3: valid=3]
valid · impact high
The old code built the list from `fields_orders`, which strips the leading '-'. `self.fields` keeps the raw names such as '-name', so a valid descending index now gets a false E012 error. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
`check()` is called once per index, but each warning still tests every index on the model, so W040/W043 are emitted once per index. The W037 test checks `self.condition` and ignores its loop variable, so it fires once per conditional index. Before, each warning appeared once per database. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
A set of strings iterates in an order that depends on per-process hash randomization. When an index has several bad fields, the error order can change between runs. The old code used an ordered list. [grounded: diff] [consensus 3/3: valid=3]
raw comments (7)
PR-level
[P1] Database-independent index checks are skipped when no databases are given, and repeated once per database django/db/models/base.py:2118-2124 `index.check()` is now only called inside `for db in databases`. That loop now also runs the E033/E034 name checks and the nonexistent/M2M/non-local field checks, which don't depend on any database. `Model.check()` sets `databases = kwargs.get("databases") or []`, and `manage.py check` passes `databases=None` unless `--database` is given. So in the default case these errors are never reported: an index on a misspelled field now passes system checks silently. When several databases are passed, the same errors are emitted once per database, and any database excluded by the router skips them. The test changes that add `databases=self.databases` and `skipUnlessDBFeature("supports_expression_indexes")` hide this regression instead of covering it.
PR-level
[P1] Index fields with a descending prefix are reported as nonexistent django/db/models/indexes.py:115-119 The field check now uses `self.fields`, which keeps the raw strings including the `-` prefix, instead of the stripped names from `fields_orders`. A valid index such as `models.Index(fields=["-name"], name="idx")` now raises models.E012 with "'indexes' refers to the nonexistent field '-name'", because `_check_local_fields` looks up `-name` in the model's fields.
PR-level
[P2] Feature warnings are emitted once per index on the model instead of once django/db/models/indexes.py:121-170 `check()` runs once for each index, but the W037/W040/W043 conditions still use `any(... for index in model._meta.indexes)` over all of the model's indexes. If one index has `include` or expressions, every index on the model reports the W040/W043 warning, so a model with N indexes gets N copies. The W037 test `any(self.condition is not None for index in ...)` mixes the two scopes: it tests `self` inside a loop over all indexes. These checks should test only `self`, or stay at model level.
PR-level
[P1] Index name and field checks now run only when databases are passed django/db/models/base.py:2118-2124 The name checks (E033/E034) and the field-reference checks (E012/E013/E016) used to run outside the `for db in databases` loop. They are now inside `index.check(cls, connection)`, which is called only from within that loop. `Model.check()` builds its list with `kwargs.get("databases") or []`, so when no databases are passed these checks never run. That covers plain `manage.py check` without `--database` and the automatic system checks run by `BaseCommand.execute`. The checks are also skipped for any model whose `allow_migrate_model` is False on every database. So an index on a nonexistent field, or a name that starts with an underscore or digit, is no longer reported. The test changes that add `databases=self.databases` everywhere only hide this regression. Also, with several databases these database-independent errors are now reported once per database.
PR-level
[P1] Descending index fields like `"-name"` are reported as nonexistent fields django/db/models/indexes.py:115-119 The old code built the field list from `index.fields_orders`, which strips the leading `-`. The new code passes `self.fields` straight to `_check_local_fields`, and that list still holds the raw strings such as `"-name"`. Any valid `Index(fields=["-name"], name=...)` now gets a false `models.E012` error: "'indexes' refers to the nonexistent field '-name'." That breaks system checks for existing projects that use descending indexes.
PR-level
[P2] W040/W043 are emitted once per index, and W037 once per conditional index django/db/models/indexes.py:120-170 `check()` runs once for each index, but each feature warning still tests the whole model with `any(... for index in model._meta.indexes)`. When the backend lacks covering or expression index support and any index on the model uses `include` or expressions, every index on the model emits its own W040/W043. Indexes that don't use the feature emit it too, so a model with 3 indexes gets 3 identical warnings. The W037 condition `any(self.condition is not None for index in ...)` ignores its loop variable, so it emits once for each conditional index. Before this change each warning appeared once per model per database. These checks should test only `self` (e.g. `self.include`, `self.contains_expressions`).
PR-level
[P3] Field-check errors come out in nondeterministic order django/db/models/indexes.py:115-119 The fields are now collected into a set literal, `{*self.fields, *self.include, *references}`, and string hashes are randomized per process. When an index has more than one bad field, the order of the E012/E013/E016 errors can change between runs. Order-sensitive `assertEqual` checks on the error list can then fail intermittently. The old code used an ordered list.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 high ✓ exact
d2 medium ✓ exact
valid · matches d1 · impact high
valid · impact medium
Name and field checks used to run outside the databases loop. They now run only inside it, after the `allow_migrate_model` gate. So `check()` with no databases skips them, and with several databases they repeat once per DB. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d2 · impact medium
valid · impact high
The removed code used `fields_orders`, which strips the '-' prefix. `self.fields` keeps it, so a descending index such as `"-name"` gets a false E012 error. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
`Index.check` runs once per index, but W040 and W043 scan every index on the model. A model with N indexes therefore gets N copies of the warning, where it used to get one per DB. The W037 'wrong condition' sub-claim is overstated (it effectively tests self.condition), but the duplicate warnings are real. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
E033, E034 and the field checks now run only for databases that pass `allow_migrate_model`. `Model.check()` with no databases no longer reports them, which is why the tests had to start passing `databases`. [grounded: diff] [consensus 3/3: valid=3]
raw comments (6)
django/db/models/indexes.py:111
[P1] Descending index fields now reported as nonexistent `self.fields` keeps the `-` prefix (e.g. `"-name"`), whereas the old code used `fields_orders`, which strips it. `_check_local_fields` now receives `"-name"`, so any `Index(fields=["-name"], ...)` on a real model is reported as "'indexes' refers to the nonexistent field '-name'" (models.E012). This is a regression for valid descending indexes. Use the field names from `self.fields_orders` instead.
django/db/models/base.py:2117
[P1] Index checks are skipped when no databases are passed Name checks (E033/E034) and field checks (E012 etc.) used to run unconditionally, and only the feature warnings depended on the connection. Now everything runs inside `for db in databases` and is gated by `router.allow_migrate_model`. `Model.check()` with no `databases` returns no index errors at all. The same happens when the router disallows migration on every DB. The edited tests had to be changed to pass `databases=self.databases` to keep passing, which confirms the behavior change. With several databases, E033/E034/E012 are also repeated once per DB.
django/db/models/indexes.py:122
[P2] Feature warnings use the wrong index and are duplicated per index `Index.check` is called once per index, but the W037/W040/W043 conditions still scan `model._meta.indexes`. The W037 condition even reads `self.condition` rather than `index.condition` inside the generator. On a DB lacking the feature, a model with N indexes where any one has a condition, include or expression gets the warning N times, including for indexes that don't use the feature. Each condition should test only `self` (for example `self.condition is not None`, `self.include`, `self.contains_expressions`).
django/db/models/indexes.py:114
[P1] Index fields are validated with raw `fields`, so descending indexes are reported as missing fields The new check passes `self.fields` to `_check_local_fields`. The removed code used `fields_orders`, which strips the `-` prefix. For `Index(fields=["-name"])`, `self.fields` still contains `"-name"`, so the check emits a bogus E012 "refers to the nonexistent field '-name'" for every valid descending index. Using the names from `fields_orders` would avoid this. The set literal also makes the order of reported errors nondeterministic.
django/db/models/indexes.py:122
[P1] Feature warnings use the wrong index and duplicate once per index `Index.check` runs once per index. W037 tests `self.condition is not None for index in model._meta.indexes`, so it looks at this index's condition but loops over every index. W040 and W043 scan all of `model._meta.indexes`. A model with N indexes where any one has a condition, `include` or expressions on an unsupported backend therefore gets N copies of the warning, including indexes that don't use the feature. W037 can also be wrong in the other direction: it checks only the current index's condition, not whether any index has one. Each check should look only at `self`.
django/db/models/base.py:2117
[P2] Index name and field checks no longer run unless a migratable database is passed The E033, E034 and field-reference checks used to run unconditionally. They now sit inside `for db in databases` after the `allow_migrate_model` check. `Model.check()` with no `databases` argument, or a model that a router excludes from every database, now skips them entirely. Invalid index names and missing fields then go unreported. This is why the tests had to be changed to pass `databases=self.databases`. The database-independent checks should stay outside the per-database loop.
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 high ✗ —
d2 medium ✓ exact
valid · impact medium
Before the change, the E033/E034 name checks and the field and expression-reference checks ran outside the `for db in databases` loop. Now they only run inside it, after `router.allow_migrate_model` approves the database. So `Model.check()` with no databases reports nothing for a malformed index. With several allowed databases, the same errors are reported once per database. The diff's test edits, which add `databases=self.databases` so these errors still show up, confirm the behaviour changed. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d2 · impact medium
raw comments (4)
django/db/models/base.py:2124
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 1\. Default checks miss invalid indexes <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>_check_indexes()</i></b> now calls <b><i>Index.check()</i></b> only inside the selected-database loop after router approval, although that method contains name, field, and expression-reference validation. When <b><i>Model.check()</i></b> or the standard check command supplies no databases, or every alias is router-denied, malformed indexes are absent from check output; selecting multiple allowed aliases also repeats those database-independent errors. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description Database-independent index validation now runs only for selected, router-approved databases. This causes default checks to omit invalid index names and fields, while multiple selected databases duplicate the same structural errors. ## Fix Focus Areas - django/db/models/base.py[2117-2125] - django/db/models/indexes.py[86-120] ## Recommended Fix Separate structural index validation from backend-feature validation. Run each index's name, field, and expression-reference checks once regardless of database selection, then run only connection-specific feature checks inside the router-approved database loop. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
django/db/models/indexes.py:125
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 2\. One index triggers repeated warnings <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>Index.check()</i></b> runs once per index, but each feature predicate scans every index in <b><i>model._meta.indexes</i></b> rather than inspecting <b><i>self</i></b>. If any one index uses conditions, included columns, or expressions on an unsupported backend, every index emits the corresponding identical warning, including indexes that do not use that feature. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description Backend feature predicates inspect all indexes even though the method is invoked separately for each index. A feature used by one index consequently produces the same warning from every index on the model. ## Fix Focus Areas - django/db/models/indexes.py[121-169] - django/db/models/base.py[2123-2124] ## Recommended Fix Replace the collection-wide predicates with checks of the current index: use `self.condition is not None`, `self.include`, and `self.contains_expressions`. Add coverage using one feature-dependent index and one ordinary index, asserting that only one warning is returned. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
PR-level
<h3>PR Summary by Qodo</h3> Delegate model index validation to Index.check() <code>✨ Enhancement</code> <code>🧪 Tests</code> <code>🕐 20-40 Minutes</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <details> <summary>AI Description</summary> <dl> <dd> <br/> ><pre> >• Adds an overridable <b><i>Index.check()</i></b> hook for index-specific system validation. >• Delegates model checks per allowed database connection, aligning indexes with constraints. >• Updates backend-sensitive tests for database-scoped index validation. ></pre> </dd> </dl> </details> <details> <summary>Diagram</summary> <dl> <dd> <br/> ```mermaid classDiagram class Model { +check(databases) -_check_indexes(databases) } class Index { +check(model, connection) } class DatabaseConnection { +features +display_name } class SystemChecks { +Error +Warning } Model --> DatabaseConnection : selects allowed database Model --> Index : delegates validation Index --> DatabaseConnection : reads backend features Index --> SystemChecks : returns diagnostics ``` </dd> </dl> </details> <details> <summary>High-Level Assessment</summary> <dl> <dd> <br/> >The delegated check hook is the preferred approach because it mirrors constraint validation, keeps index-specific rules with Index, and permits subclasses to extend validation. Retaining validation in Model._check_indexes() was considered but would preserve tighter coupling and limit custom index extensibility. </dd> </dl> </details> <details> <summary> Files changed (3) <code> +111 / -97 </code> </summary> <dl> <dd> <br/> <details> <summary>Enhancement (1) <code> +87 / -0 </code></summary> <dl> <dd> <details> <summary>indexes.py<code>Add database-aware Index.check() validation hook</code> <code>+87/-0</code></summary> <br/> >Add database-aware Index.check() validation hook > ><pre> >• Introduces &#x27;Index.check(model, connection)&#x27; and moves name, field-reference, expression, and backend-feature validation into the index class. The hook returns the existing system-check errors and warnings while allowing index subclasses to customize validation. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/36/files#diff-0b5bafe2c73718e1b80cd140411dfa403e1b04880ddfba4a7065b9eac5f740c9'>django/db/models/indexes.py</a> </details> </dd> </dl> </details> <details> <summary>Refactor (1) <code> +2 / -82 </code></summary> <dl> <dd> <details> <summary>base.py<code>Delegate index checks to each Index instance</code> <code>+2/-82</code></summary> <br/> >Delegate index checks to each Index instance > ><pre> >• Replaces model-level index validation logic with database-scoped calls to &#x27;Index.check()&#x27;. Migration routing remains responsible for selecting which database connections participate. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/36/files#diff-1c8b882c73bfda668d5451d4578c97191b0ebc0f088d0c0ba2296ab89b428c44'>django/db/models/base.py</a> </details> </dd> </dl> </details> <details> <summary>Tests (1) <code> +22 / -15 </code></summary> <dl> <dd> <details> <summary>test_models.py<code>Make index validation tests database-aware</code> <code>+22/-15</code></summary> <br/> >Make index validation tests database-aware > ><pre> >• Passes the configured test databases into index-related model checks. Expression-index field validation tests now run only on backends that support expression indexes. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/36/files#diff-8d58c4d1755fbc59fdcb4385fb823cbf8e7a9a76350fd4506590e1878328128d'>tests/invalid_models_tests/test_models.py</a> </details> </dd> </dl> </details> </dd> </dl> </details>
PR-level
<h3>Code Review by Qodo</h3> <code>🐞 Bugs (2)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <br/> <img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> <details> <summary> 1. Default checks miss invalid indexes <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>_check_indexes()</i></b> now calls <b><i>Index.check()</i></b> only inside the selected-database loop after router >approval, although that method contains name, field, and expression-reference validation. When ><b><i>Model.check()</i></b> or the standard check command supplies no databases, or every alias is >router-denied, malformed indexes are absent from check output; selecting multiple allowed aliases >also repeats those database-independent errors. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[django/db/models/base.py[R2123-2124]](https://github.com/drape-io/crbench-qodo-2026-09/pull/36/files#diff-1c8b882c73bfda668d5451d4578c97191b0ebc0f088d0c0ba2296ab89b428c44R2123-R2124)</code> > >```diff >+ for index in cls._meta.indexes: >+ errors.extend(index.check(cls, connection)) >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >Model checks normalize omitted databases to an empty collection, while the new call to ><b><i>Index.check()</i></b> is nested entirely inside the database and router gates. The moved E033/E034 and >local-field validation therefore cannot execute during the standard no-database path. ></pre> > > <code>[django/db/models/base.py[1675-1695]](https://github.com/drape-io/crbench-qodo-2026-09/blob/0d5d817c72d634168a8858c366260bdf103bdf9b/django/db/models/base.py/#L1675-L1695)</code> > <code>[django/db/models/base.py[2117-2125]](https://github.com/drape-io/crbench-qodo-2026-09/blob/0d5d817c72d634168a8858c366260bdf103bdf9b/django/db/models/base.py/#L2117-L2125)</code> > <code>[django/db/models/indexes.py[89-119]](https://github.com/drape-io/crbench-qodo-2026-09/blob/0d5d817c72d634168a8858c366260bdf103bdf9b/django/db/models/indexes.py/#L89-L119)</code> > <code>[django/core/management/commands/check.py[81-88]](https://github.com/drape-io/crbench-qodo-2026-09/blob/0d5d817c72d634168a8858c366260bdf103bdf9b/django/core/management/commands/check.py/#L81-L88)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Database-independent index validation now runs only for selected, router-approved databases. This causes default checks to omit invalid index names and fields, while multiple selected databases duplicate the same structural errors. > >## Fix Focus Areas >- django/db/models/base.py[2117-2125] >- django/db/models/indexes.py[86-120] > >## Recommended Fix >Separate structural index validation from backend-feature validation. Run each index's name, field, and expression-reference checks once regardless of database selection, then run only connection-specific feature checks inside the router-approved database loop. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <br/> <img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> <details> <summary> 2. One index triggers repeated warnings <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>Index.check()</i></b> runs once per index, but each feature predicate scans every index in ><b><i>model._meta.indexes</i></b> rather than inspecting <b><i>self</i></b>. If any one index uses conditions, included >columns, or expressions on an unsupported backend, every index emits the corresponding identical >warning, including indexes that do not use that feature. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[django/db/models/indexes.py[125]](https://github.com/drape-io/crbench-qodo-2026-09/pull/36/files#diff-0b5bafe2c73718e1b80cd140411dfa403e1b04880ddfba4a7065b9eac5f740c9R125-R125)</code> > >```diff >+ ) and any(self.condition is not None for index in model._meta.indexes): >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The caller iterates over every model index, while all three warning branches use <b><i>any()</i></b> over the >same complete index collection. Thus a two-index model with only one conditional index invokes the >satisfied conditional predicate twice; the analogous constraint implementation checks each object&#x27;s >own properties instead. ></pre> > > <code>[django/db/models/base.py[2117-2125]](https://github.com/drape-io/crbench-qodo-2026-09/blob/0d5d817c72d634168a8858c366260bdf103bdf9b/django/db/models/base.py/#L2117-L2125)</code> > <code>[django/db/models/indexes.py[121-169]](https://github.com/drape-io/crbench-qodo-2026-09/blob/0d5d817c72d634168a8858c366260bdf103bdf9b/django/db/models/indexes.py/#L121-L169)</code> > <code>[django/db/models/constraints.py[338-400]](https://github.com/drape-io/crbench-qodo-2026-09/blob/0d5d817c72d634168a8858c366260bdf103bdf9b/django/db/models/constraints.py/#L338-L400)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Backend feature predicates inspect all indexes even though the method is invoked separately for each index. A feature used by one index consequently produces the same warning from every index on the model. > >## Fix Focus Areas >- django/db/models/indexes.py[121-169] >- django/db/models/base.py[2123-2124] > >## Recommended Fix >Replace the collection-wide predicates with checks of the current index: use `self.condition is not None`, `self.include`, and `self.contains_expressions`. Add coverage using one feature-dependent index and one ordinary index, asserting that only one warning is returned. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-context:start --> <details><summary><strong>Context sources</strong></summary> <div>Review mode: <code>⚖️ Balanced</code>: This refactors Django model validation across multiple code paths and database backends, with behavior-sensitive index checks and test changes; it carries genuine framework-level risk but is not dense enough to require redundant extended passes.</div> <!-- qodo-context:end --> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:start --> <details> <summary><strong>Tip of the day</strong></summary> <br/> <pre>💡 Did you know, you can reply &#x27;qodo&#x27; on any finding to push back, ask questions, or dig deeper</pre> <a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:end --> <!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/0d5d817c72d634168a8858c366260bdf103bdf9b --> <a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>